WeKnora/internal/handler/knowledge.go

3238 lines
113 KiB
Go
Raw Normal View History

2025-08-05 07:08:07 +00:00
package handler
import (
"context"
2025-08-05 07:08:07 +00:00
"encoding/json"
goerrors "errors"
2025-08-05 07:08:07 +00:00
"fmt"
"net/http"
"strconv"
"strings"
"time"
2025-08-05 07:08:07 +00:00
"github.com/Tencent/WeKnora/internal/application/access"
"github.com/Tencent/WeKnora/internal/application/repository"
feat(knowledge): flag documents that stop making progress (#3557) * feat(knowledge): flag documents that stop making progress A document stuck in processing looked the same as one still working: a spinner that polled forever, no hint of where it stopped, and, hours later, a generic housekeeping failure. - The batch and spans endpoints return last_activity_at for in-flight rows: the later of updated_at and the newest span write. updated_at only moves at stage transitions; span writes keep moving while a long stage still works. - After 20 minutes with no progress, the list and card views show "may be stuck" with a tooltip. The timeline shows the stage it stopped at and a stop-parsing button, plus a "last progress" stat. Both pollers back off to 15s while everything in flight is stalled. - When housekeeping fails a row, the error names the stalled stage and the time of the last progress. It closes the row's open spans with TASK_STALLED (the running stage fails, the rest are cancelled), so the timeline shows where the run stopped instead of a spinner. * fix(knowledge): locate stalls in finalizing and tell backlog from stuck - Housekeeping reads the stall site from the latest attempt. It takes the running stages, or, when none runs (post-process closes its stage once enrichment is fanned out), the innermost running spans, mapped back to their stage. Those spans fail with TASK_STALLED and are named in the message; every stalled stage is listed in pipeline order. The other open spans are cancelled. Every closed span gets a duration, and the message leaves out the time when the heartbeat query failed. - The spans tree prefers a TASK_STALLED failure for last_error over a later subtask failure. current_stage falls back to the stage owning a running subspan. - Batch and spans responses flag rows quiet past the stall hint whose work is still queued (waiting_in_queue), using the sweep's own probes. At most 20 rows are probed per request, cached for a minute. The UI shows these as queued, with no stop button in the banner. * fix(knowledge): answer stall verdicts from one shared queue scan - Probing a quiet document for a backlog rescanned the whole queue once per document. When the document was absent, which is exactly the stuck case, the scan ran to the end, and it read a Redis error as "nothing queued". QueuedKnowledgeIDs now collects every referenced knowledge ID in one pass and returns list errors. HousekeepingService keeps that snapshot for a minute, shared across requests and single-flight. A failed scan is not cached. - With the per-request cap of 20 gone, every quiet row on a page gets a verdict. The response carries it as stall_state (queued or stalled), replacing waiting_in_queue. The UI marks a row as stuck only on a "stalled" verdict. A row with no verdict, because the probe failed, shows as ordinary processing instead of inviting a stop.
2026-09-22 13:34:08 +00:00
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/config"
2025-08-05 07:08:07 +00:00
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/filetransport"
2025-08-05 07:08:07 +00:00
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/middleware"
feat(observability): extend Langfuse tracing across asynq pipeline Previously the Langfuse integration only traced in-process HTTP requests (chat / search / eval), so file uploads and every downstream asynq task (document parse, chunk embedding, OCR/VLM, summary / question gen, wiki ingest, datasource sync, etc.) produced either disconnected shallow traces or no observation at all. This change threads one trace end-to-end: - tracer: add SPAN observation type and StartSpan; add ResumeTrace so a worker can attach to an upstream trace without emitting a duplicate trace-create; StartGeneration now auto-picks parentObservationId from ctx so nested trace -> span -> generation trees render correctly. - types.TracingContext + LangfuseTracingCarrier: embed on all 17 asynq payloads so trace_id / parent_obs_id / user_id / session_id serialise into every job. - langfuse.InjectTracing: injected at 28 enqueue sites before json.Marshal so the HTTP-layer trace survives the Redis hop. - langfuse.AsynqMiddleware: mux.Use hook that peeks the payload, either resumes the upstream trace or opens a standalone asynq.<type> trace for scheduled jobs, and wraps the handler in a SPAN with task metadata (id / queue / retry / payload_bytes) plus ERROR level on failure. - GinMiddleware.shouldTrace: whitelist ingestion / knowledge-mutation / FAQ / wiki / datasource endpoints so the root trace actually starts. - Tests: tracer_test.go covers span nesting, error status, and ResumeTrace no-trace-create guarantee; asynq_test.go covers InjectTracing round-trip, middleware resume path, and standalone trace fallback. - Docs: docs/Langfuse\u96c6\u6210.md now lists the covered task types and documents the cross-process propagation model. No behavioural change when Langfuse is disabled (all new code paths are no-ops and carriers serialise to empty strings with omitempty).
2026-04-24 04:23:30 +00:00
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
2025-08-05 07:08:07 +00:00
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/Tencent/WeKnora/internal/utils"
secutils "github.com/Tencent/WeKnora/internal/utils"
2025-08-05 07:08:07 +00:00
"github.com/gin-gonic/gin"
"github.com/hibiken/asynq"
2025-08-05 07:08:07 +00:00
)
// KnowledgeHandler processes HTTP requests related to knowledge resources
type KnowledgeHandler struct {
cfg *config.Config
kgService interfaces.KnowledgeService
kbService interfaces.KnowledgeBaseService
kbShareService interfaces.KBShareService
agentShareService interfaces.AgentShareService
feat(gallery): add an image gallery tab with schema-driven filters (#3694) * feat(image): observe image attributes and let the policy decide OCR Describe each image with the VLM as before, but ask it to also observe two attributes about the image in the same round — how much body text it carries (contain.text) and whether it presents data visually (contain.data_visual) — then let a small pure function decide whether that image is worth a second, separate OCR round. Per-class OCR was the first shape of this idea; a class (chart / photo / logo) is only an indirect proxy for 'is there text worth reading here', and the class table has to grow whenever a new kind of image shows up. The decision actually needs the observed attributes, so it reads them directly, and the attribute set is a backend registry row rather than a new class. The observation and the caption share one VLM call; OCR stays a separate call (prompt isolation, see #3291). An attribute the model does not answer for is left absent rather than filled with a conservative default, so the trace never claims an observation that did not happen, and an incomplete observation falls back to the on_unobserved policy (OCR still runs). The registry also carries the panel's display text, so a new attribute needs no frontend change. Off by default: image_attrs_enabled=false keeps today's behaviour (one caption and one OCR per image). KB config: image_processing_config.image_attrs_enabled / image_actions; per-upload override via process_config. Registry: GET /api/v1/image-attrs/schema. * feat(gallery): add image gallery tab with schema-driven filters Adds a 4th knowledge-base tab parallel to Documents/Wiki/Graph that browses every image asset in a KB. Backend: - GET /api/v1/knowledge-bases/:id/images lists image assets projected from chunks.image_info, with keyword (caption/OCR), multi-value attribute (attr_<name>=<value>), is_enabled and sort filters applied in memory, plus pagination. - Resolves the source knowledge item title (SourceName) via a batched GetKnowledgeBatch so the viewer can show a human-readable source. Frontend: - ImageGallery.vue: thumbnail grid + search/sort + schema-driven filter panel (from GET /image-attrs/schema) + single-image viewer with prev/next, attributes/caption/OCR/source. - Wired as the gallery tab in KnowledgeBase.vue; i18n keys in all 5 locales. * feat(gallery): drive filters/search/sort from a configurable attribute contract The gallery UI is no longer hardcoded: it renders from a self-describing contract served by GET /knowledge-bases/:id/gallery-config (live attribute sources, every attribute's definition with usage flags merged across the config tiers, and the caller's search activation state). - Attribute sources form an open registry (types.RegisterGalleryAttrSource); a builtin source models caption/ocr_text/timestamps/enabled so the gallery has zero special cases. - Usage resolution: user > KB > system > source, field by field; the system tier lives in system_settings (gallery.policy, JSON, no rebuild), the KB tier slot is wired in the engine but not stored yet. - Search activation is the user's own record: mode (all|custom) plus per-field on/off in users.preferences.gallery; source declarations never set defaults (unrecorded = off in custom mode). - image_info is read through a gallery-local struct, removing the compile dependency on the attribute-pipeline types; the gallery builds and runs with or without that feature deployed. - ListImages validates search_in / sort_by / attr_filters against the contract; ineligible fields are dropped, not served. * fix(frontend): inline the shared graph-drawer stylesheet (@import instead of <style src>) plugin-vue 6.0.6 keys unscoped src-style descriptors by the imported file path, so AgentStreamDisplay.vue and WikiBrowser.vue — both importing components/css/wiki-graph-drawer.less — overwrite each other during the build and the second one crashes with "reading 'scoped'". Adding the gallery changed the module order enough to make the collision hit every time. Inlining the same stylesheet keeps the emitted CSS identical and removes the shared descriptor key. * feat(gallery): render attributes from short labels with descriptions in tooltips A source could only say one thing about a value, so the filter panel had to put a full sentence inside a checkbox. Attributes and their values now carry two pieces of text: a short label for the space-constrained controls (checkbox, search field, sort option) and a description for wherever there is room (tooltip, detail panel). The contract's value list becomes an array of {value, label, description}, and the display helpers resolve each field separately: the gallery stamps the short name on a control and moves the sentence into a tooltip. Translation overlays are looked up per field, so a source that ships no gallery-specific text still picks up the attribute pipeline's own wording. * fix(gallery): let locale text win over the contract's wording The filter panel read the backend's own label before asking the locale, so a translated value never got a chance: the contract ships its own default-language wording, and it shadowed the overlay for every locale. Built keys were also off by a segment — imageAttr.<name> has to be imageAttr.<name>.label, and the gallery's own keys live under knowledgeEditor.wikiBrowser.gallery.attr — so builtin and system attributes fell through to English on a Chinese UI. * feat(gallery): top bar layout, pinned panels and per-value verdicts The toolbar moves onto its own row above the grid, so the controls no longer eat into the space the images are there for: search box, the two scope switches, sort field and direction, and the result count all sit in one flex row. The settings behind them are no longer inline either — each opens as a popover under its control and can be pinned to a right-hand rail, where the two panels take turns as tabs instead of both claiming width at once. Filtering gains a third state per attribute value. Where a value could only be picked or not picked, it can now be "off" (hide those images), "on" (show them whatever else says) or neutral (leave them alone), which is what lets one attribute's rules talk about an image another attribute tried to hide without the pair of them cancelling each other out: a forced display outranks a forced hide, and anything no rule speaks about stays visible. The switch that used to only exist inside the panel now has a toolbar home as well. "筛选:全显示" genuinely drops the attribute constraint instead of imposing it against a panel the user cannot see. Filtering used to empty the list the moment it was switched on. Any image whose attribute was never observed — every image ingested before the attribute pipeline existed — read as a mismatch for every filter, which is not narrowing a list but losing it. Absence now stays silence: an attribute no image carries places no constraint on it, until the pipeline catches up and fills the value in. Co-authored-by: WorkBuddy * feat(gallery): expose the image attribute pipeline as a gallery source The gallery's contract resolved to a single source, so the filter panel could only offer "Enabled" while the attributes the observe-and-describe pipeline fills in — contain.text, contain.data_visual — never reached the UI. The registry is a gallery attribute source like any other: every attribute it declares is offered to the gallery, filterable by default, with the config tiers able to override the usage flags at runtime. The registration lives in the attribute pipeline's own commit; this branch carried an earlier, squapshot of that work which predated the split of an attribute value into a short label and a description, so the registry's value shape and this file have been brought in line with it. Both PRs now hold byte-identical copies of the source hook, which is what lets either one land first and the other merge cleanly afterwards. Co-authored-by: WorkBuddy * fix(gallery): viewer race, pin icon, panel anchoring and scope wording Opening the viewer rendered the img element with the previous or empty source while the proxy fetch was still producing a blob, and the error that empty source fired locked the viewer in its failure state even after the real image arrived. The resolved source now lands before the flag is consulted, and a token keeps a slow fetch of one image from overwriting a faster one that navigated past it. The pin button drew nothing: TDesign has no "pushpin" glyph, so the button rendered as an empty shell. It now uses pin / pin-filled, keeps its place beside the tab bar, and a pinned rail assigns its columns explicitly — the panel precedes the main section in the DOM, so leaving the grid to source order handed the wide column to the panel and squeezed the images into the rail. The floating panel no longer appears at a hardcoded offset: it anchors just below the arrow that summoned it, the arrow flips up while its panel is out, a second press retracts, and any click elsewhere in the toolbar closes it. When a rail is pinned the arrows turn to the requested tab instead of spawning a second surface. The scope words (全部 / 全显示 / 自定义) become plain status text rather than a second dropdown — they name the current mode, and only the arrow beside them opens the panel that changes it. Co-authored-by: WorkBuddy * fix(web): align the OCR-on-unobserved switch with the other setting rows The switch sat bare inside its setting-row while every other switch on the page is wrapped in setting-control, which is what reserves the right column and centers the control vertically. With the row laid out from the top, the bare switch hugged the row's upper edge and crowded the description text — visibly out of place next to its neighbors. Wrapping it in setting-control gives it the same right-aligned, centered slot as the rest. Co-authored-by: WorkBuddy * fix(web): move the OCR-on-unobserved row out of the vertical schema row The row lived inside setting-row-vertical, whose descendant rule stretches every setting-info and setting-control beneath it to 100% width. Two full-width flex children side by side cannot fit, so the control overflowed the container and the switch landed past the right edge — visibly further out than the switch on the row above. The row and its note now sit beside the vertical block instead of inside it, under their own condition, so the switch shares the ordinary row layout and its right edge lines up with the "image attribute observation" switch above. Co-authored-by: WorkBuddy * fix(gallery): applying a verdict now activates the filter scope Setting an off/on verdict while the panel's master switch was off silently ignored it: buildParams only attaches attr_rules in custom scope, and setVerdict never flipped the scope. A verdict the user just expressed now switches the scope to custom; clearing the last meaningful verdict returns to all, since custom with no rules constrains nothing. * fix(gallery): search checkboxes stay visible and idle panels read as dimmed The search panel hid its field checkboxes while the master switch was on, so the only way to reach them was to flip the switch first. They now sit next to the switch like the filter panel's verdicts do: dimmed in all-field mode (where they carry no weight) yet clickable, and touching one drops the mode to custom. The filter panel's verdict rows dim the same way while the filter switch is off. * fix(gallery): bulk verdict row, neutral default mark, panel polish The clear-filters button never matched what the panel is for, so it is now a bulk verdict row: one set of -/off/on buttons that applies the chosen position to every value of every value-typed attribute, with the default mark turned into a language-neutral dash. The panel head drops its second divider (the tab bar already draws one) and the tabs follow the toolbar's order: search left, filter right. * fix(gallery): drop the all-fields caption and center the order arrow The caption above the search checkboxes showed and hid with the master switch, shoving the checkboxes down on every flip; it said nothing the dimmed state doesn't, so it is gone. The order button's arrow is an inline svg, which sits on the text baseline and reads as riding high; it now centers against the label. * fix(gallery): center the order arrow for real vertical-align never applied: the icon is a flex item inside the button's inline-flex text wrapper, and the wrapper's default stretch pins the explicitly-sized 16px icon to the top of the 22px line box. align-items: center on the wrapper is what actually centers it. * fix(gallery): shorten panel tab labels in en and ru The two-word labels overflowed the 300px panel and forced the tab bar into scroll arrows; single-word labels fit in every locale that was affected. * docs: drop the image pipeline rewrite from this branch The rewritten 'Go 侧接手后' paragraph belongs to the image attribute observation work (#3635), which this branch carries as a prerequisite and which already documents the caption_ocr / observation_driven split. Keeping a competing rewrite of the same paragraph on the gallery branch makes it collide with upstream, which extended that paragraph with the custom_instructions and inline HTML table notes. Restoring the shared wording keeps the gallery branch free of this file so upstream's edits merge cleanly. * style: gofmt the gallery attribute types Struct field tags in the resolved gallery config were one column narrow, so gofmt rebroke the alignment block. Whitespace only. * style(gallery): use design tokens in the gallery styles The style guard ratchet fails on any new violation. ImageGallery.vue shipped with 47 TDesign token fallbacks, 21 literal font sizes, 4 literal radii and a 0.15s transition; all of them now read the --app-* / --td-* tokens, which is what the guard asks for and what dark mode depends on. * lint(gallery): fix the golangci-lint findings in the gallery code lll: the three over-long swagger @Param lines and one registry row were shortened. ineffassign: ctx was assigned before the access check and then reassigned, so the first value was dead; it is now declared once, after the check. errcheck: the three unchecked c.Error calls in ListImages. revive: the AttrSpec / AttrValue doc comment block was attached to the wrong type and split into one block each. staticcheck S1016: the gallery registration converts the registry value instead of restating its fields. * lint(gallery): wrap the image query select and check the last c.Error * style: reformat the wrapped image select in chunk.go * fix(gallery): address review findings on ordering, KB switch and blob lifetime - sortImageAssets: swap operands for desc instead of negating, keeping a strict weak ordering so ties page stably - ImageGallery: reload on knowledgeBaseId change, drop stale list responses, fetch thumbnails in parallel with one cached blob per URL, revoke blobs on unmount, default sort to builtin:created_at - KnowledgeBase: non-wiki KBs with a stale wiki/graph tab fall back to documents again - handler: move ListImages godoc out of ListKnowledgeFolders' block and document attr_filters / attr_rules - DecideOCR: a payload with no OCR conditions uses the built-in policy instead of silently skipping OCR * docs(parsing): describe the caption_ocr and observation_driven image pipelines Carried over from #3635, which this PR supersedes. * fix(gallery): load local:// and other storage handles through the KB file proxy The gallery's own scheme check only caught resource://, provider:// and storage://, so local:// (the default storage), minio://, cos:// and s3:// images went straight into <img src> and never rendered. Resolve through isProviderFileURL, the scheme list chat and wiki already use, and lock the routing with a test. * fix(kb-editor): keep API-customised OCR conditions on save and upload The KB editor always wrote the registry default into image_actions.ocr.on, so any unrelated edit replaced a knowledge base's custom OCR conditions with the default table; the upload dialog did the same for the per-document override. Keep a stored custom list and fall back to the registry default only when there is none, and show the conditions actually in effect instead of the default table in both panels. * perf(gallery): de-duplicate, filter, sort and page images in SQL Every gallery request used to read every image-bearing chunk of the KB, OCR text included, decode it in Go and page in memory. A single query now expands the image_info arrays, keeps one row per image URL, applies the keyword / attribute / verdict / enabled filters and the sort, and returns only the page with the filtered total. The expansion carries narrow scalars only; filters and JSON sort keys are evaluated on the winning entry of each image, and the page's JSON is read back for its rows alone. Postgres runs the query with JIT off, since the fixed 100-rows-per-call estimate of jsonb_array_elements otherwise prices it ~100x high and compilation dominates. On 20k images with 2 KB of OCR text each (40k chunks), a page drops from ~750 ms to ~100-200 ms on postgres and ~200 ms on sqlite; keyword search over OCR text stays a full scan (~400-600 ms) until the text is indexed. The filter semantics are pinned against both databases. * perf(gallery): serve the gallery from a trigger-maintained chunk_images table Reading images out of chunks.image_info meant parsing every image chunk of the knowledge base on each request, so a page still cost time in proportion to the KB. chunk_images (versioned/000113, sqlite/000032) keeps one row per image_info entry with caption, OCR text and attributes as columns; triggers on chunks keep it in step with every write path, and the migration backfills existing chunks. Copies of one image stay separate rows and the query lists the copy on the most recently updated chunk through an indexed anti-join, so writes decide nothing and concurrent writers need no locking. On postgres, caption and OCR text get pg_trgm indexes when the extension is available. On 20k images with 2 KB of OCR text each (40k chunks): postgres first page 10 ms, page 500 41 ms, keyword 2 ms, filters 23 ms sqlite first page 3 ms, page 500 39 ms, keyword 147 ms, filters 51 ms down from ~100-600 ms. Writing those 40k image chunks costs 7.0 s instead of 1.3 s on postgres (1.9 s instead of 1.0 s on sqlite), mostly the trigram indexes; status and enable-flag updates patch rows in place. --------- Co-authored-by: tayadwx <tayadwx@users.noreply.github.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-25 04:33:59 +00:00
chunkService interfaces.ChunkService
systemSettingSvc interfaces.SystemSettingService
userSvc interfaces.UserService
asynqClient interfaces.TaskEnqueuer
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
spanRepo repository.KnowledgeSpanRepository
feat(knowledge): flag documents that stop making progress (#3557) * feat(knowledge): flag documents that stop making progress A document stuck in processing looked the same as one still working: a spinner that polled forever, no hint of where it stopped, and, hours later, a generic housekeeping failure. - The batch and spans endpoints return last_activity_at for in-flight rows: the later of updated_at and the newest span write. updated_at only moves at stage transitions; span writes keep moving while a long stage still works. - After 20 minutes with no progress, the list and card views show "may be stuck" with a tooltip. The timeline shows the stage it stopped at and a stop-parsing button, plus a "last progress" stat. Both pollers back off to 15s while everything in flight is stalled. - When housekeeping fails a row, the error names the stalled stage and the time of the last progress. It closes the row's open spans with TASK_STALLED (the running stage fails, the rest are cancelled), so the timeline shows where the run stopped instead of a spinner. * fix(knowledge): locate stalls in finalizing and tell backlog from stuck - Housekeeping reads the stall site from the latest attempt. It takes the running stages, or, when none runs (post-process closes its stage once enrichment is fanned out), the innermost running spans, mapped back to their stage. Those spans fail with TASK_STALLED and are named in the message; every stalled stage is listed in pipeline order. The other open spans are cancelled. Every closed span gets a duration, and the message leaves out the time when the heartbeat query failed. - The spans tree prefers a TASK_STALLED failure for last_error over a later subtask failure. current_stage falls back to the stage owning a running subspan. - Batch and spans responses flag rows quiet past the stall hint whose work is still queued (waiting_in_queue), using the sweep's own probes. At most 20 rows are probed per request, cached for a minute. The UI shows these as queued, with no stop button in the banner. * fix(knowledge): answer stall verdicts from one shared queue scan - Probing a quiet document for a backlog rescanned the whole queue once per document. When the document was absent, which is exactly the stuck case, the scan ran to the end, and it read a Redis error as "nothing queued". QueuedKnowledgeIDs now collects every referenced knowledge ID in one pass and returns list errors. HousekeepingService keeps that snapshot for a minute, shared across requests and single-flight. A failed scan is not cached. - With the per-request cap of 20 gone, every quiet row on a page gets a verdict. The response carries it as stall_state (queued or stalled), replacing waiting_in_queue. The UI marks a row as stuck only on a "stalled" verdict. A row with no verdict, because the probe failed, shows as ordinary processing instead of inviting a stop.
2026-09-22 13:34:08 +00:00
backlog backlogProbe
}
// backlogProbe tells a backlogged document (work still queued) from a stuck
// one; HousekeepingService implements it with the sweep's own probes.
type backlogProbe interface {
QueuedWork(ctx context.Context, ids []string) (map[string]bool, error)
}
// stallHintAfter is how long an in-flight row may go without progress before
// it gets a stall verdict; keep in step with PROCESSING_STALL_THRESHOLD_MS in
// the frontend.
const stallHintAfter = 20 * time.Minute
// stallVerdicts probes ids (all quiet past stallHintAfter) and returns each
// one's StallState. Nil when the probe is unavailable or failed: an unknown
// row gets no verdict rather than being called stuck.
func (h *KnowledgeHandler) stallVerdicts(ctx context.Context, ids []string) map[string]string {
if h.backlog == nil || len(ids) == 0 {
return nil
}
queued, err := h.backlog.QueuedWork(ctx, ids)
if err != nil {
logger.Warnf(ctx, "backlog probe failed: %v", err)
return nil
}
out := make(map[string]string, len(ids))
for _, id := range ids {
out[id] = types.StallStateStalled
if queued[id] {
out[id] = types.StallStateQueued
}
}
return out
2025-08-05 07:08:07 +00:00
}
// NewKnowledgeHandler creates a new knowledge handler instance
func NewKnowledgeHandler(
cfg *config.Config,
2025-08-05 07:08:07 +00:00
kgService interfaces.KnowledgeService,
kbService interfaces.KnowledgeBaseService,
kbShareService interfaces.KBShareService,
agentShareService interfaces.AgentShareService,
feat(gallery): add an image gallery tab with schema-driven filters (#3694) * feat(image): observe image attributes and let the policy decide OCR Describe each image with the VLM as before, but ask it to also observe two attributes about the image in the same round — how much body text it carries (contain.text) and whether it presents data visually (contain.data_visual) — then let a small pure function decide whether that image is worth a second, separate OCR round. Per-class OCR was the first shape of this idea; a class (chart / photo / logo) is only an indirect proxy for 'is there text worth reading here', and the class table has to grow whenever a new kind of image shows up. The decision actually needs the observed attributes, so it reads them directly, and the attribute set is a backend registry row rather than a new class. The observation and the caption share one VLM call; OCR stays a separate call (prompt isolation, see #3291). An attribute the model does not answer for is left absent rather than filled with a conservative default, so the trace never claims an observation that did not happen, and an incomplete observation falls back to the on_unobserved policy (OCR still runs). The registry also carries the panel's display text, so a new attribute needs no frontend change. Off by default: image_attrs_enabled=false keeps today's behaviour (one caption and one OCR per image). KB config: image_processing_config.image_attrs_enabled / image_actions; per-upload override via process_config. Registry: GET /api/v1/image-attrs/schema. * feat(gallery): add image gallery tab with schema-driven filters Adds a 4th knowledge-base tab parallel to Documents/Wiki/Graph that browses every image asset in a KB. Backend: - GET /api/v1/knowledge-bases/:id/images lists image assets projected from chunks.image_info, with keyword (caption/OCR), multi-value attribute (attr_<name>=<value>), is_enabled and sort filters applied in memory, plus pagination. - Resolves the source knowledge item title (SourceName) via a batched GetKnowledgeBatch so the viewer can show a human-readable source. Frontend: - ImageGallery.vue: thumbnail grid + search/sort + schema-driven filter panel (from GET /image-attrs/schema) + single-image viewer with prev/next, attributes/caption/OCR/source. - Wired as the gallery tab in KnowledgeBase.vue; i18n keys in all 5 locales. * feat(gallery): drive filters/search/sort from a configurable attribute contract The gallery UI is no longer hardcoded: it renders from a self-describing contract served by GET /knowledge-bases/:id/gallery-config (live attribute sources, every attribute's definition with usage flags merged across the config tiers, and the caller's search activation state). - Attribute sources form an open registry (types.RegisterGalleryAttrSource); a builtin source models caption/ocr_text/timestamps/enabled so the gallery has zero special cases. - Usage resolution: user > KB > system > source, field by field; the system tier lives in system_settings (gallery.policy, JSON, no rebuild), the KB tier slot is wired in the engine but not stored yet. - Search activation is the user's own record: mode (all|custom) plus per-field on/off in users.preferences.gallery; source declarations never set defaults (unrecorded = off in custom mode). - image_info is read through a gallery-local struct, removing the compile dependency on the attribute-pipeline types; the gallery builds and runs with or without that feature deployed. - ListImages validates search_in / sort_by / attr_filters against the contract; ineligible fields are dropped, not served. * fix(frontend): inline the shared graph-drawer stylesheet (@import instead of <style src>) plugin-vue 6.0.6 keys unscoped src-style descriptors by the imported file path, so AgentStreamDisplay.vue and WikiBrowser.vue — both importing components/css/wiki-graph-drawer.less — overwrite each other during the build and the second one crashes with "reading 'scoped'". Adding the gallery changed the module order enough to make the collision hit every time. Inlining the same stylesheet keeps the emitted CSS identical and removes the shared descriptor key. * feat(gallery): render attributes from short labels with descriptions in tooltips A source could only say one thing about a value, so the filter panel had to put a full sentence inside a checkbox. Attributes and their values now carry two pieces of text: a short label for the space-constrained controls (checkbox, search field, sort option) and a description for wherever there is room (tooltip, detail panel). The contract's value list becomes an array of {value, label, description}, and the display helpers resolve each field separately: the gallery stamps the short name on a control and moves the sentence into a tooltip. Translation overlays are looked up per field, so a source that ships no gallery-specific text still picks up the attribute pipeline's own wording. * fix(gallery): let locale text win over the contract's wording The filter panel read the backend's own label before asking the locale, so a translated value never got a chance: the contract ships its own default-language wording, and it shadowed the overlay for every locale. Built keys were also off by a segment — imageAttr.<name> has to be imageAttr.<name>.label, and the gallery's own keys live under knowledgeEditor.wikiBrowser.gallery.attr — so builtin and system attributes fell through to English on a Chinese UI. * feat(gallery): top bar layout, pinned panels and per-value verdicts The toolbar moves onto its own row above the grid, so the controls no longer eat into the space the images are there for: search box, the two scope switches, sort field and direction, and the result count all sit in one flex row. The settings behind them are no longer inline either — each opens as a popover under its control and can be pinned to a right-hand rail, where the two panels take turns as tabs instead of both claiming width at once. Filtering gains a third state per attribute value. Where a value could only be picked or not picked, it can now be "off" (hide those images), "on" (show them whatever else says) or neutral (leave them alone), which is what lets one attribute's rules talk about an image another attribute tried to hide without the pair of them cancelling each other out: a forced display outranks a forced hide, and anything no rule speaks about stays visible. The switch that used to only exist inside the panel now has a toolbar home as well. "筛选:全显示" genuinely drops the attribute constraint instead of imposing it against a panel the user cannot see. Filtering used to empty the list the moment it was switched on. Any image whose attribute was never observed — every image ingested before the attribute pipeline existed — read as a mismatch for every filter, which is not narrowing a list but losing it. Absence now stays silence: an attribute no image carries places no constraint on it, until the pipeline catches up and fills the value in. Co-authored-by: WorkBuddy * feat(gallery): expose the image attribute pipeline as a gallery source The gallery's contract resolved to a single source, so the filter panel could only offer "Enabled" while the attributes the observe-and-describe pipeline fills in — contain.text, contain.data_visual — never reached the UI. The registry is a gallery attribute source like any other: every attribute it declares is offered to the gallery, filterable by default, with the config tiers able to override the usage flags at runtime. The registration lives in the attribute pipeline's own commit; this branch carried an earlier, squapshot of that work which predated the split of an attribute value into a short label and a description, so the registry's value shape and this file have been brought in line with it. Both PRs now hold byte-identical copies of the source hook, which is what lets either one land first and the other merge cleanly afterwards. Co-authored-by: WorkBuddy * fix(gallery): viewer race, pin icon, panel anchoring and scope wording Opening the viewer rendered the img element with the previous or empty source while the proxy fetch was still producing a blob, and the error that empty source fired locked the viewer in its failure state even after the real image arrived. The resolved source now lands before the flag is consulted, and a token keeps a slow fetch of one image from overwriting a faster one that navigated past it. The pin button drew nothing: TDesign has no "pushpin" glyph, so the button rendered as an empty shell. It now uses pin / pin-filled, keeps its place beside the tab bar, and a pinned rail assigns its columns explicitly — the panel precedes the main section in the DOM, so leaving the grid to source order handed the wide column to the panel and squeezed the images into the rail. The floating panel no longer appears at a hardcoded offset: it anchors just below the arrow that summoned it, the arrow flips up while its panel is out, a second press retracts, and any click elsewhere in the toolbar closes it. When a rail is pinned the arrows turn to the requested tab instead of spawning a second surface. The scope words (全部 / 全显示 / 自定义) become plain status text rather than a second dropdown — they name the current mode, and only the arrow beside them opens the panel that changes it. Co-authored-by: WorkBuddy * fix(web): align the OCR-on-unobserved switch with the other setting rows The switch sat bare inside its setting-row while every other switch on the page is wrapped in setting-control, which is what reserves the right column and centers the control vertically. With the row laid out from the top, the bare switch hugged the row's upper edge and crowded the description text — visibly out of place next to its neighbors. Wrapping it in setting-control gives it the same right-aligned, centered slot as the rest. Co-authored-by: WorkBuddy * fix(web): move the OCR-on-unobserved row out of the vertical schema row The row lived inside setting-row-vertical, whose descendant rule stretches every setting-info and setting-control beneath it to 100% width. Two full-width flex children side by side cannot fit, so the control overflowed the container and the switch landed past the right edge — visibly further out than the switch on the row above. The row and its note now sit beside the vertical block instead of inside it, under their own condition, so the switch shares the ordinary row layout and its right edge lines up with the "image attribute observation" switch above. Co-authored-by: WorkBuddy * fix(gallery): applying a verdict now activates the filter scope Setting an off/on verdict while the panel's master switch was off silently ignored it: buildParams only attaches attr_rules in custom scope, and setVerdict never flipped the scope. A verdict the user just expressed now switches the scope to custom; clearing the last meaningful verdict returns to all, since custom with no rules constrains nothing. * fix(gallery): search checkboxes stay visible and idle panels read as dimmed The search panel hid its field checkboxes while the master switch was on, so the only way to reach them was to flip the switch first. They now sit next to the switch like the filter panel's verdicts do: dimmed in all-field mode (where they carry no weight) yet clickable, and touching one drops the mode to custom. The filter panel's verdict rows dim the same way while the filter switch is off. * fix(gallery): bulk verdict row, neutral default mark, panel polish The clear-filters button never matched what the panel is for, so it is now a bulk verdict row: one set of -/off/on buttons that applies the chosen position to every value of every value-typed attribute, with the default mark turned into a language-neutral dash. The panel head drops its second divider (the tab bar already draws one) and the tabs follow the toolbar's order: search left, filter right. * fix(gallery): drop the all-fields caption and center the order arrow The caption above the search checkboxes showed and hid with the master switch, shoving the checkboxes down on every flip; it said nothing the dimmed state doesn't, so it is gone. The order button's arrow is an inline svg, which sits on the text baseline and reads as riding high; it now centers against the label. * fix(gallery): center the order arrow for real vertical-align never applied: the icon is a flex item inside the button's inline-flex text wrapper, and the wrapper's default stretch pins the explicitly-sized 16px icon to the top of the 22px line box. align-items: center on the wrapper is what actually centers it. * fix(gallery): shorten panel tab labels in en and ru The two-word labels overflowed the 300px panel and forced the tab bar into scroll arrows; single-word labels fit in every locale that was affected. * docs: drop the image pipeline rewrite from this branch The rewritten 'Go 侧接手后' paragraph belongs to the image attribute observation work (#3635), which this branch carries as a prerequisite and which already documents the caption_ocr / observation_driven split. Keeping a competing rewrite of the same paragraph on the gallery branch makes it collide with upstream, which extended that paragraph with the custom_instructions and inline HTML table notes. Restoring the shared wording keeps the gallery branch free of this file so upstream's edits merge cleanly. * style: gofmt the gallery attribute types Struct field tags in the resolved gallery config were one column narrow, so gofmt rebroke the alignment block. Whitespace only. * style(gallery): use design tokens in the gallery styles The style guard ratchet fails on any new violation. ImageGallery.vue shipped with 47 TDesign token fallbacks, 21 literal font sizes, 4 literal radii and a 0.15s transition; all of them now read the --app-* / --td-* tokens, which is what the guard asks for and what dark mode depends on. * lint(gallery): fix the golangci-lint findings in the gallery code lll: the three over-long swagger @Param lines and one registry row were shortened. ineffassign: ctx was assigned before the access check and then reassigned, so the first value was dead; it is now declared once, after the check. errcheck: the three unchecked c.Error calls in ListImages. revive: the AttrSpec / AttrValue doc comment block was attached to the wrong type and split into one block each. staticcheck S1016: the gallery registration converts the registry value instead of restating its fields. * lint(gallery): wrap the image query select and check the last c.Error * style: reformat the wrapped image select in chunk.go * fix(gallery): address review findings on ordering, KB switch and blob lifetime - sortImageAssets: swap operands for desc instead of negating, keeping a strict weak ordering so ties page stably - ImageGallery: reload on knowledgeBaseId change, drop stale list responses, fetch thumbnails in parallel with one cached blob per URL, revoke blobs on unmount, default sort to builtin:created_at - KnowledgeBase: non-wiki KBs with a stale wiki/graph tab fall back to documents again - handler: move ListImages godoc out of ListKnowledgeFolders' block and document attr_filters / attr_rules - DecideOCR: a payload with no OCR conditions uses the built-in policy instead of silently skipping OCR * docs(parsing): describe the caption_ocr and observation_driven image pipelines Carried over from #3635, which this PR supersedes. * fix(gallery): load local:// and other storage handles through the KB file proxy The gallery's own scheme check only caught resource://, provider:// and storage://, so local:// (the default storage), minio://, cos:// and s3:// images went straight into <img src> and never rendered. Resolve through isProviderFileURL, the scheme list chat and wiki already use, and lock the routing with a test. * fix(kb-editor): keep API-customised OCR conditions on save and upload The KB editor always wrote the registry default into image_actions.ocr.on, so any unrelated edit replaced a knowledge base's custom OCR conditions with the default table; the upload dialog did the same for the per-document override. Keep a stored custom list and fall back to the registry default only when there is none, and show the conditions actually in effect instead of the default table in both panels. * perf(gallery): de-duplicate, filter, sort and page images in SQL Every gallery request used to read every image-bearing chunk of the KB, OCR text included, decode it in Go and page in memory. A single query now expands the image_info arrays, keeps one row per image URL, applies the keyword / attribute / verdict / enabled filters and the sort, and returns only the page with the filtered total. The expansion carries narrow scalars only; filters and JSON sort keys are evaluated on the winning entry of each image, and the page's JSON is read back for its rows alone. Postgres runs the query with JIT off, since the fixed 100-rows-per-call estimate of jsonb_array_elements otherwise prices it ~100x high and compilation dominates. On 20k images with 2 KB of OCR text each (40k chunks), a page drops from ~750 ms to ~100-200 ms on postgres and ~200 ms on sqlite; keyword search over OCR text stays a full scan (~400-600 ms) until the text is indexed. The filter semantics are pinned against both databases. * perf(gallery): serve the gallery from a trigger-maintained chunk_images table Reading images out of chunks.image_info meant parsing every image chunk of the knowledge base on each request, so a page still cost time in proportion to the KB. chunk_images (versioned/000113, sqlite/000032) keeps one row per image_info entry with caption, OCR text and attributes as columns; triggers on chunks keep it in step with every write path, and the migration backfills existing chunks. Copies of one image stay separate rows and the query lists the copy on the most recently updated chunk through an indexed anti-join, so writes decide nothing and concurrent writers need no locking. On postgres, caption and OCR text get pg_trgm indexes when the extension is available. On 20k images with 2 KB of OCR text each (40k chunks): postgres first page 10 ms, page 500 41 ms, keyword 2 ms, filters 23 ms sqlite first page 3 ms, page 500 39 ms, keyword 147 ms, filters 51 ms down from ~100-600 ms. Writing those 40k image chunks costs 7.0 s instead of 1.3 s on postgres (1.9 s instead of 1.0 s on sqlite), mostly the trigram indexes; status and enable-flag updates patch rows in place. --------- Co-authored-by: tayadwx <tayadwx@users.noreply.github.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-25 04:33:59 +00:00
chunkService interfaces.ChunkService,
systemSettingSvc interfaces.SystemSettingService,
userSvc interfaces.UserService,
asynqClient interfaces.TaskEnqueuer,
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
spanRepo repository.KnowledgeSpanRepository,
feat(knowledge): flag documents that stop making progress (#3557) * feat(knowledge): flag documents that stop making progress A document stuck in processing looked the same as one still working: a spinner that polled forever, no hint of where it stopped, and, hours later, a generic housekeeping failure. - The batch and spans endpoints return last_activity_at for in-flight rows: the later of updated_at and the newest span write. updated_at only moves at stage transitions; span writes keep moving while a long stage still works. - After 20 minutes with no progress, the list and card views show "may be stuck" with a tooltip. The timeline shows the stage it stopped at and a stop-parsing button, plus a "last progress" stat. Both pollers back off to 15s while everything in flight is stalled. - When housekeeping fails a row, the error names the stalled stage and the time of the last progress. It closes the row's open spans with TASK_STALLED (the running stage fails, the rest are cancelled), so the timeline shows where the run stopped instead of a spinner. * fix(knowledge): locate stalls in finalizing and tell backlog from stuck - Housekeeping reads the stall site from the latest attempt. It takes the running stages, or, when none runs (post-process closes its stage once enrichment is fanned out), the innermost running spans, mapped back to their stage. Those spans fail with TASK_STALLED and are named in the message; every stalled stage is listed in pipeline order. The other open spans are cancelled. Every closed span gets a duration, and the message leaves out the time when the heartbeat query failed. - The spans tree prefers a TASK_STALLED failure for last_error over a later subtask failure. current_stage falls back to the stage owning a running subspan. - Batch and spans responses flag rows quiet past the stall hint whose work is still queued (waiting_in_queue), using the sweep's own probes. At most 20 rows are probed per request, cached for a minute. The UI shows these as queued, with no stop button in the banner. * fix(knowledge): answer stall verdicts from one shared queue scan - Probing a quiet document for a backlog rescanned the whole queue once per document. When the document was absent, which is exactly the stuck case, the scan ran to the end, and it read a Redis error as "nothing queued". QueuedKnowledgeIDs now collects every referenced knowledge ID in one pass and returns list errors. HousekeepingService keeps that snapshot for a minute, shared across requests and single-flight. A failed scan is not cached. - With the per-request cap of 20 gone, every quiet row on a page gets a verdict. The response carries it as stall_state (queued or stalled), replacing waiting_in_queue. The UI marks a row as stuck only on a "stalled" verdict. A row with no verdict, because the probe failed, shows as ordinary processing instead of inviting a stop.
2026-09-22 13:34:08 +00:00
housekeeping *service.HousekeepingService,
2025-08-05 07:08:07 +00:00
) *KnowledgeHandler {
feat(knowledge): flag documents that stop making progress (#3557) * feat(knowledge): flag documents that stop making progress A document stuck in processing looked the same as one still working: a spinner that polled forever, no hint of where it stopped, and, hours later, a generic housekeeping failure. - The batch and spans endpoints return last_activity_at for in-flight rows: the later of updated_at and the newest span write. updated_at only moves at stage transitions; span writes keep moving while a long stage still works. - After 20 minutes with no progress, the list and card views show "may be stuck" with a tooltip. The timeline shows the stage it stopped at and a stop-parsing button, plus a "last progress" stat. Both pollers back off to 15s while everything in flight is stalled. - When housekeeping fails a row, the error names the stalled stage and the time of the last progress. It closes the row's open spans with TASK_STALLED (the running stage fails, the rest are cancelled), so the timeline shows where the run stopped instead of a spinner. * fix(knowledge): locate stalls in finalizing and tell backlog from stuck - Housekeeping reads the stall site from the latest attempt. It takes the running stages, or, when none runs (post-process closes its stage once enrichment is fanned out), the innermost running spans, mapped back to their stage. Those spans fail with TASK_STALLED and are named in the message; every stalled stage is listed in pipeline order. The other open spans are cancelled. Every closed span gets a duration, and the message leaves out the time when the heartbeat query failed. - The spans tree prefers a TASK_STALLED failure for last_error over a later subtask failure. current_stage falls back to the stage owning a running subspan. - Batch and spans responses flag rows quiet past the stall hint whose work is still queued (waiting_in_queue), using the sweep's own probes. At most 20 rows are probed per request, cached for a minute. The UI shows these as queued, with no stop button in the banner. * fix(knowledge): answer stall verdicts from one shared queue scan - Probing a quiet document for a backlog rescanned the whole queue once per document. When the document was absent, which is exactly the stuck case, the scan ran to the end, and it read a Redis error as "nothing queued". QueuedKnowledgeIDs now collects every referenced knowledge ID in one pass and returns list errors. HousekeepingService keeps that snapshot for a minute, shared across requests and single-flight. A failed scan is not cached. - With the per-request cap of 20 gone, every quiet row on a page gets a verdict. The response carries it as stall_state (queued or stalled), replacing waiting_in_queue. The UI marks a row as stuck only on a "stalled" verdict. A row with no verdict, because the probe failed, shows as ordinary processing instead of inviting a stop.
2026-09-22 13:34:08 +00:00
var backlog backlogProbe
if housekeeping != nil {
backlog = housekeeping
}
return &KnowledgeHandler{
feat(knowledge): flag documents that stop making progress (#3557) * feat(knowledge): flag documents that stop making progress A document stuck in processing looked the same as one still working: a spinner that polled forever, no hint of where it stopped, and, hours later, a generic housekeeping failure. - The batch and spans endpoints return last_activity_at for in-flight rows: the later of updated_at and the newest span write. updated_at only moves at stage transitions; span writes keep moving while a long stage still works. - After 20 minutes with no progress, the list and card views show "may be stuck" with a tooltip. The timeline shows the stage it stopped at and a stop-parsing button, plus a "last progress" stat. Both pollers back off to 15s while everything in flight is stalled. - When housekeeping fails a row, the error names the stalled stage and the time of the last progress. It closes the row's open spans with TASK_STALLED (the running stage fails, the rest are cancelled), so the timeline shows where the run stopped instead of a spinner. * fix(knowledge): locate stalls in finalizing and tell backlog from stuck - Housekeeping reads the stall site from the latest attempt. It takes the running stages, or, when none runs (post-process closes its stage once enrichment is fanned out), the innermost running spans, mapped back to their stage. Those spans fail with TASK_STALLED and are named in the message; every stalled stage is listed in pipeline order. The other open spans are cancelled. Every closed span gets a duration, and the message leaves out the time when the heartbeat query failed. - The spans tree prefers a TASK_STALLED failure for last_error over a later subtask failure. current_stage falls back to the stage owning a running subspan. - Batch and spans responses flag rows quiet past the stall hint whose work is still queued (waiting_in_queue), using the sweep's own probes. At most 20 rows are probed per request, cached for a minute. The UI shows these as queued, with no stop button in the banner. * fix(knowledge): answer stall verdicts from one shared queue scan - Probing a quiet document for a backlog rescanned the whole queue once per document. When the document was absent, which is exactly the stuck case, the scan ran to the end, and it read a Redis error as "nothing queued". QueuedKnowledgeIDs now collects every referenced knowledge ID in one pass and returns list errors. HousekeepingService keeps that snapshot for a minute, shared across requests and single-flight. A failed scan is not cached. - With the per-request cap of 20 gone, every quiet row on a page gets a verdict. The response carries it as stall_state (queued or stalled), replacing waiting_in_queue. The UI marks a row as stuck only on a "stalled" verdict. A row with no verdict, because the probe failed, shows as ordinary processing instead of inviting a stop.
2026-09-22 13:34:08 +00:00
backlog: backlog,
cfg: cfg,
kgService: kgService,
kbService: kbService,
kbShareService: kbShareService,
agentShareService: agentShareService,
feat(gallery): add an image gallery tab with schema-driven filters (#3694) * feat(image): observe image attributes and let the policy decide OCR Describe each image with the VLM as before, but ask it to also observe two attributes about the image in the same round — how much body text it carries (contain.text) and whether it presents data visually (contain.data_visual) — then let a small pure function decide whether that image is worth a second, separate OCR round. Per-class OCR was the first shape of this idea; a class (chart / photo / logo) is only an indirect proxy for 'is there text worth reading here', and the class table has to grow whenever a new kind of image shows up. The decision actually needs the observed attributes, so it reads them directly, and the attribute set is a backend registry row rather than a new class. The observation and the caption share one VLM call; OCR stays a separate call (prompt isolation, see #3291). An attribute the model does not answer for is left absent rather than filled with a conservative default, so the trace never claims an observation that did not happen, and an incomplete observation falls back to the on_unobserved policy (OCR still runs). The registry also carries the panel's display text, so a new attribute needs no frontend change. Off by default: image_attrs_enabled=false keeps today's behaviour (one caption and one OCR per image). KB config: image_processing_config.image_attrs_enabled / image_actions; per-upload override via process_config. Registry: GET /api/v1/image-attrs/schema. * feat(gallery): add image gallery tab with schema-driven filters Adds a 4th knowledge-base tab parallel to Documents/Wiki/Graph that browses every image asset in a KB. Backend: - GET /api/v1/knowledge-bases/:id/images lists image assets projected from chunks.image_info, with keyword (caption/OCR), multi-value attribute (attr_<name>=<value>), is_enabled and sort filters applied in memory, plus pagination. - Resolves the source knowledge item title (SourceName) via a batched GetKnowledgeBatch so the viewer can show a human-readable source. Frontend: - ImageGallery.vue: thumbnail grid + search/sort + schema-driven filter panel (from GET /image-attrs/schema) + single-image viewer with prev/next, attributes/caption/OCR/source. - Wired as the gallery tab in KnowledgeBase.vue; i18n keys in all 5 locales. * feat(gallery): drive filters/search/sort from a configurable attribute contract The gallery UI is no longer hardcoded: it renders from a self-describing contract served by GET /knowledge-bases/:id/gallery-config (live attribute sources, every attribute's definition with usage flags merged across the config tiers, and the caller's search activation state). - Attribute sources form an open registry (types.RegisterGalleryAttrSource); a builtin source models caption/ocr_text/timestamps/enabled so the gallery has zero special cases. - Usage resolution: user > KB > system > source, field by field; the system tier lives in system_settings (gallery.policy, JSON, no rebuild), the KB tier slot is wired in the engine but not stored yet. - Search activation is the user's own record: mode (all|custom) plus per-field on/off in users.preferences.gallery; source declarations never set defaults (unrecorded = off in custom mode). - image_info is read through a gallery-local struct, removing the compile dependency on the attribute-pipeline types; the gallery builds and runs with or without that feature deployed. - ListImages validates search_in / sort_by / attr_filters against the contract; ineligible fields are dropped, not served. * fix(frontend): inline the shared graph-drawer stylesheet (@import instead of <style src>) plugin-vue 6.0.6 keys unscoped src-style descriptors by the imported file path, so AgentStreamDisplay.vue and WikiBrowser.vue — both importing components/css/wiki-graph-drawer.less — overwrite each other during the build and the second one crashes with "reading 'scoped'". Adding the gallery changed the module order enough to make the collision hit every time. Inlining the same stylesheet keeps the emitted CSS identical and removes the shared descriptor key. * feat(gallery): render attributes from short labels with descriptions in tooltips A source could only say one thing about a value, so the filter panel had to put a full sentence inside a checkbox. Attributes and their values now carry two pieces of text: a short label for the space-constrained controls (checkbox, search field, sort option) and a description for wherever there is room (tooltip, detail panel). The contract's value list becomes an array of {value, label, description}, and the display helpers resolve each field separately: the gallery stamps the short name on a control and moves the sentence into a tooltip. Translation overlays are looked up per field, so a source that ships no gallery-specific text still picks up the attribute pipeline's own wording. * fix(gallery): let locale text win over the contract's wording The filter panel read the backend's own label before asking the locale, so a translated value never got a chance: the contract ships its own default-language wording, and it shadowed the overlay for every locale. Built keys were also off by a segment — imageAttr.<name> has to be imageAttr.<name>.label, and the gallery's own keys live under knowledgeEditor.wikiBrowser.gallery.attr — so builtin and system attributes fell through to English on a Chinese UI. * feat(gallery): top bar layout, pinned panels and per-value verdicts The toolbar moves onto its own row above the grid, so the controls no longer eat into the space the images are there for: search box, the two scope switches, sort field and direction, and the result count all sit in one flex row. The settings behind them are no longer inline either — each opens as a popover under its control and can be pinned to a right-hand rail, where the two panels take turns as tabs instead of both claiming width at once. Filtering gains a third state per attribute value. Where a value could only be picked or not picked, it can now be "off" (hide those images), "on" (show them whatever else says) or neutral (leave them alone), which is what lets one attribute's rules talk about an image another attribute tried to hide without the pair of them cancelling each other out: a forced display outranks a forced hide, and anything no rule speaks about stays visible. The switch that used to only exist inside the panel now has a toolbar home as well. "筛选:全显示" genuinely drops the attribute constraint instead of imposing it against a panel the user cannot see. Filtering used to empty the list the moment it was switched on. Any image whose attribute was never observed — every image ingested before the attribute pipeline existed — read as a mismatch for every filter, which is not narrowing a list but losing it. Absence now stays silence: an attribute no image carries places no constraint on it, until the pipeline catches up and fills the value in. Co-authored-by: WorkBuddy * feat(gallery): expose the image attribute pipeline as a gallery source The gallery's contract resolved to a single source, so the filter panel could only offer "Enabled" while the attributes the observe-and-describe pipeline fills in — contain.text, contain.data_visual — never reached the UI. The registry is a gallery attribute source like any other: every attribute it declares is offered to the gallery, filterable by default, with the config tiers able to override the usage flags at runtime. The registration lives in the attribute pipeline's own commit; this branch carried an earlier, squapshot of that work which predated the split of an attribute value into a short label and a description, so the registry's value shape and this file have been brought in line with it. Both PRs now hold byte-identical copies of the source hook, which is what lets either one land first and the other merge cleanly afterwards. Co-authored-by: WorkBuddy * fix(gallery): viewer race, pin icon, panel anchoring and scope wording Opening the viewer rendered the img element with the previous or empty source while the proxy fetch was still producing a blob, and the error that empty source fired locked the viewer in its failure state even after the real image arrived. The resolved source now lands before the flag is consulted, and a token keeps a slow fetch of one image from overwriting a faster one that navigated past it. The pin button drew nothing: TDesign has no "pushpin" glyph, so the button rendered as an empty shell. It now uses pin / pin-filled, keeps its place beside the tab bar, and a pinned rail assigns its columns explicitly — the panel precedes the main section in the DOM, so leaving the grid to source order handed the wide column to the panel and squeezed the images into the rail. The floating panel no longer appears at a hardcoded offset: it anchors just below the arrow that summoned it, the arrow flips up while its panel is out, a second press retracts, and any click elsewhere in the toolbar closes it. When a rail is pinned the arrows turn to the requested tab instead of spawning a second surface. The scope words (全部 / 全显示 / 自定义) become plain status text rather than a second dropdown — they name the current mode, and only the arrow beside them opens the panel that changes it. Co-authored-by: WorkBuddy * fix(web): align the OCR-on-unobserved switch with the other setting rows The switch sat bare inside its setting-row while every other switch on the page is wrapped in setting-control, which is what reserves the right column and centers the control vertically. With the row laid out from the top, the bare switch hugged the row's upper edge and crowded the description text — visibly out of place next to its neighbors. Wrapping it in setting-control gives it the same right-aligned, centered slot as the rest. Co-authored-by: WorkBuddy * fix(web): move the OCR-on-unobserved row out of the vertical schema row The row lived inside setting-row-vertical, whose descendant rule stretches every setting-info and setting-control beneath it to 100% width. Two full-width flex children side by side cannot fit, so the control overflowed the container and the switch landed past the right edge — visibly further out than the switch on the row above. The row and its note now sit beside the vertical block instead of inside it, under their own condition, so the switch shares the ordinary row layout and its right edge lines up with the "image attribute observation" switch above. Co-authored-by: WorkBuddy * fix(gallery): applying a verdict now activates the filter scope Setting an off/on verdict while the panel's master switch was off silently ignored it: buildParams only attaches attr_rules in custom scope, and setVerdict never flipped the scope. A verdict the user just expressed now switches the scope to custom; clearing the last meaningful verdict returns to all, since custom with no rules constrains nothing. * fix(gallery): search checkboxes stay visible and idle panels read as dimmed The search panel hid its field checkboxes while the master switch was on, so the only way to reach them was to flip the switch first. They now sit next to the switch like the filter panel's verdicts do: dimmed in all-field mode (where they carry no weight) yet clickable, and touching one drops the mode to custom. The filter panel's verdict rows dim the same way while the filter switch is off. * fix(gallery): bulk verdict row, neutral default mark, panel polish The clear-filters button never matched what the panel is for, so it is now a bulk verdict row: one set of -/off/on buttons that applies the chosen position to every value of every value-typed attribute, with the default mark turned into a language-neutral dash. The panel head drops its second divider (the tab bar already draws one) and the tabs follow the toolbar's order: search left, filter right. * fix(gallery): drop the all-fields caption and center the order arrow The caption above the search checkboxes showed and hid with the master switch, shoving the checkboxes down on every flip; it said nothing the dimmed state doesn't, so it is gone. The order button's arrow is an inline svg, which sits on the text baseline and reads as riding high; it now centers against the label. * fix(gallery): center the order arrow for real vertical-align never applied: the icon is a flex item inside the button's inline-flex text wrapper, and the wrapper's default stretch pins the explicitly-sized 16px icon to the top of the 22px line box. align-items: center on the wrapper is what actually centers it. * fix(gallery): shorten panel tab labels in en and ru The two-word labels overflowed the 300px panel and forced the tab bar into scroll arrows; single-word labels fit in every locale that was affected. * docs: drop the image pipeline rewrite from this branch The rewritten 'Go 侧接手后' paragraph belongs to the image attribute observation work (#3635), which this branch carries as a prerequisite and which already documents the caption_ocr / observation_driven split. Keeping a competing rewrite of the same paragraph on the gallery branch makes it collide with upstream, which extended that paragraph with the custom_instructions and inline HTML table notes. Restoring the shared wording keeps the gallery branch free of this file so upstream's edits merge cleanly. * style: gofmt the gallery attribute types Struct field tags in the resolved gallery config were one column narrow, so gofmt rebroke the alignment block. Whitespace only. * style(gallery): use design tokens in the gallery styles The style guard ratchet fails on any new violation. ImageGallery.vue shipped with 47 TDesign token fallbacks, 21 literal font sizes, 4 literal radii and a 0.15s transition; all of them now read the --app-* / --td-* tokens, which is what the guard asks for and what dark mode depends on. * lint(gallery): fix the golangci-lint findings in the gallery code lll: the three over-long swagger @Param lines and one registry row were shortened. ineffassign: ctx was assigned before the access check and then reassigned, so the first value was dead; it is now declared once, after the check. errcheck: the three unchecked c.Error calls in ListImages. revive: the AttrSpec / AttrValue doc comment block was attached to the wrong type and split into one block each. staticcheck S1016: the gallery registration converts the registry value instead of restating its fields. * lint(gallery): wrap the image query select and check the last c.Error * style: reformat the wrapped image select in chunk.go * fix(gallery): address review findings on ordering, KB switch and blob lifetime - sortImageAssets: swap operands for desc instead of negating, keeping a strict weak ordering so ties page stably - ImageGallery: reload on knowledgeBaseId change, drop stale list responses, fetch thumbnails in parallel with one cached blob per URL, revoke blobs on unmount, default sort to builtin:created_at - KnowledgeBase: non-wiki KBs with a stale wiki/graph tab fall back to documents again - handler: move ListImages godoc out of ListKnowledgeFolders' block and document attr_filters / attr_rules - DecideOCR: a payload with no OCR conditions uses the built-in policy instead of silently skipping OCR * docs(parsing): describe the caption_ocr and observation_driven image pipelines Carried over from #3635, which this PR supersedes. * fix(gallery): load local:// and other storage handles through the KB file proxy The gallery's own scheme check only caught resource://, provider:// and storage://, so local:// (the default storage), minio://, cos:// and s3:// images went straight into <img src> and never rendered. Resolve through isProviderFileURL, the scheme list chat and wiki already use, and lock the routing with a test. * fix(kb-editor): keep API-customised OCR conditions on save and upload The KB editor always wrote the registry default into image_actions.ocr.on, so any unrelated edit replaced a knowledge base's custom OCR conditions with the default table; the upload dialog did the same for the per-document override. Keep a stored custom list and fall back to the registry default only when there is none, and show the conditions actually in effect instead of the default table in both panels. * perf(gallery): de-duplicate, filter, sort and page images in SQL Every gallery request used to read every image-bearing chunk of the KB, OCR text included, decode it in Go and page in memory. A single query now expands the image_info arrays, keeps one row per image URL, applies the keyword / attribute / verdict / enabled filters and the sort, and returns only the page with the filtered total. The expansion carries narrow scalars only; filters and JSON sort keys are evaluated on the winning entry of each image, and the page's JSON is read back for its rows alone. Postgres runs the query with JIT off, since the fixed 100-rows-per-call estimate of jsonb_array_elements otherwise prices it ~100x high and compilation dominates. On 20k images with 2 KB of OCR text each (40k chunks), a page drops from ~750 ms to ~100-200 ms on postgres and ~200 ms on sqlite; keyword search over OCR text stays a full scan (~400-600 ms) until the text is indexed. The filter semantics are pinned against both databases. * perf(gallery): serve the gallery from a trigger-maintained chunk_images table Reading images out of chunks.image_info meant parsing every image chunk of the knowledge base on each request, so a page still cost time in proportion to the KB. chunk_images (versioned/000113, sqlite/000032) keeps one row per image_info entry with caption, OCR text and attributes as columns; triggers on chunks keep it in step with every write path, and the migration backfills existing chunks. Copies of one image stay separate rows and the query lists the copy on the most recently updated chunk through an indexed anti-join, so writes decide nothing and concurrent writers need no locking. On postgres, caption and OCR text get pg_trgm indexes when the extension is available. On 20k images with 2 KB of OCR text each (40k chunks): postgres first page 10 ms, page 500 41 ms, keyword 2 ms, filters 23 ms sqlite first page 3 ms, page 500 39 ms, keyword 147 ms, filters 51 ms down from ~100-600 ms. Writing those 40k image chunks costs 7.0 s instead of 1.3 s on postgres (1.9 s instead of 1.0 s on sqlite), mostly the trigram indexes; status and enable-flag updates patch rows in place. --------- Co-authored-by: tayadwx <tayadwx@users.noreply.github.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-25 04:33:59 +00:00
chunkService: chunkService,
systemSettingSvc: systemSettingSvc,
userSvc: userSvc,
asynqClient: asynqClient,
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
spanRepo: spanRepo,
}
2025-08-05 07:08:07 +00:00
}
// requireKBOwnershipOrAdmin enforces the same "KB creator OR Admin+" matrix
// used by OwnedKBOrAdmin for routes whose KB id comes from the request body.
func (h *KnowledgeHandler) requireKBOwnershipOrAdmin(c *gin.Context, kbID string) error {
evalErr := middleware.EvaluateOwnershipOrRole(
c.Request.Context(),
h.cfg,
types.TenantRoleAdmin,
func() (string, error) { return resolveKBCreatorByKBID(c, h.kbService, kbID) },
)
if evalErr == nil {
return nil
}
if goerrors.Is(evalErr, middleware.ErrResourceNotFound) {
return errors.NewNotFoundError("knowledge base not found")
}
if goerrors.Is(evalErr, middleware.ErrOwnershipForbidden) {
return errors.NewForbiddenError("No permission to operate on this knowledge base")
}
logger.ErrorWithFields(c.Request.Context(), evalErr, map[string]interface{}{
"kb_id": secutils.SanitizeForLog(kbID),
})
return errors.NewInternalServerError("cannot verify knowledge base ownership")
}
2025-08-05 07:08:07 +00:00
// validateKnowledgeBaseAccess validates access permissions to a knowledge base
// using the ":id" URL path parameter. It delegates to validateKnowledgeBaseAccessWithKBID.
func (h *KnowledgeHandler) validateKnowledgeBaseAccess(c *gin.Context) (*types.KnowledgeBase, string, uint64, types.OrgMemberRole, error) {
kbID := secutils.SanitizeForLog(c.Param("id"))
return h.validateKnowledgeBaseAccessWithKBID(c, kbID)
}
// validateKnowledgeBaseAccessWithKBID validates access to the given knowledge base ID (e.g. from query or body).
// Enforces per-API-key KB scope before tenant/share/agent resolution.
// Returns the knowledge base, kbID, effective tenant ID, permission, and error.
func (h *KnowledgeHandler) validateKnowledgeBaseAccessWithKBID(
c *gin.Context,
kbID string,
) (*types.KnowledgeBase, string, uint64, types.OrgMemberRole, error) {
kbID = secutils.SanitizeForLog(kbID)
grant, err := resolveHandlerKBAccess(c, kbID, h.kbService, h.kbShareService, h.agentShareService)
if err != nil {
return nil, kbID, 0, "", err
}
return grant.KnowledgeBase, kbID, grant.EffectiveTenantID, grant.Permission, nil
}
func (h *KnowledgeHandler) validateKnowledgeBaseWriteAccessWithKBID(
c *gin.Context,
kbID string,
) (*types.KnowledgeBase, string, uint64, types.OrgMemberRole, error) {
grant, err := resolveHandlerKBAccessFor(
c,
kbID,
h.kbService,
h.kbShareService,
h.agentShareService,
types.OrgRoleEditor,
)
if err != nil {
return nil, kbID, 0, "", err
2025-08-05 07:08:07 +00:00
}
if err := access.RequireKBWrite(grant.Context(c.Request.Context()), grant.KnowledgeBase); err != nil {
return nil, kbID, 0, "", kbAccessHTTPError(err)
}
return grant.KnowledgeBase, kbID, grant.EffectiveTenantID, grant.Permission, nil
}
// resolveKnowledgeAndValidateKBAccess resolves a document and checks its parent
// KB using the same policy as KB routes. The persisted document supplies the KB
// and owner reference, so unguarded callers do not need an additional KB lookup.
func (h *KnowledgeHandler) resolveKnowledgeAndValidateKBAccess(
c *gin.Context,
knowledgeID string,
requiredPermission types.OrgMemberRole,
) (*types.Knowledge, context.Context, error) {
ctx := c.Request.Context()
request := middleware.KBAccessRequest(c)
if request.Caller.TenantID == 0 {
return nil, ctx, errors.NewUnauthorizedError("Unauthorized")
}
knowledge, err := h.kgService.GetKnowledgeByIDOnly(ctx, knowledgeID)
if err != nil || knowledge == nil {
return nil, ctx, errors.NewNotFoundError("Knowledge not found")
}
if err := requireTenantAPIKeyKnowledgeBase(ctx, knowledge.KnowledgeBaseID); err != nil {
return nil, ctx, err
}
if grant, ok := resolvedKBAccess(c, knowledge.KnowledgeBaseID, requiredPermission); ok {
if grant.EffectiveTenantID != knowledge.TenantID {
return nil, ctx, errors.NewForbiddenError("Permission denied to access this knowledge")
}
return knowledge, grant.Context(ctx), nil
}
kb := &types.KnowledgeBase{ID: knowledge.KnowledgeBaseID, TenantID: knowledge.TenantID}
grant, err := access.ResolveKB(ctx, request, kb, requiredPermission, h.kbShareService, h.agentShareService)
if goerrors.Is(err, access.ErrForbidden) {
return nil, ctx, errors.NewForbiddenError("Permission denied to access this knowledge")
}
if err != nil {
return nil, ctx, kbAccessHTTPError(err)
}
return knowledge, grant.Context(ctx), nil
2025-08-05 07:08:07 +00:00
}
// handleDuplicateKnowledgeError handles cases where duplicate knowledge is detected
// Returns true if the error was a duplicate error and was handled, false otherwise
func (h *KnowledgeHandler) handleDuplicateKnowledgeError(c *gin.Context,
err error, knowledge *types.Knowledge, duplicateType string,
) bool {
if dupErr, ok := err.(*types.DuplicateKnowledgeError); ok {
ctx := c.Request.Context()
logger.Warnf(ctx, "Detected duplicate %s: %s", duplicateType, secutils.SanitizeForLog(dupErr.Error()))
2025-08-05 07:08:07 +00:00
c.JSON(http.StatusConflict, gin.H{
"success": false,
"message": dupErr.Error(),
"data": knowledge, // knowledge contains the existing document
"code": fmt.Sprintf("duplicate_%s", duplicateType),
})
return true
}
return false
}
// enqueueKnowledgeListDelete enqueues an async batch-delete task for the
// given knowledge IDs and returns the asynq task ID.
func (h *KnowledgeHandler) enqueueKnowledgeListDelete(
ctx context.Context, tenantID uint64, kbID string, ids []string,
) (string, error) {
payload := types.KnowledgeListDeletePayload{
KnowledgeBaseID: kbID,
TenantID: tenantID,
KnowledgeIDs: ids,
Initiator: types.TaskInitiatorFromContext(ctx),
}
langfuse.InjectTracing(ctx, &payload)
payloadBytes, err := json.Marshal(payload)
if err != nil {
return "", fmt.Errorf("marshal payload: %w", err)
}
task := asynq.NewTask(types.TypeKnowledgeListDelete, payloadBytes,
asynq.Queue(types.QueueMaintenance), asynq.MaxRetry(3), asynq.Timeout(2*time.Hour))
info, err := h.asynqClient.Enqueue(task)
if err != nil {
return "", fmt.Errorf("enqueue task: %w", err)
}
return info.ID, nil
}
// enqueueKnowledgeListReparse enqueues an async batch-reparse task for the
// given knowledge IDs and returns the asynq task ID.
func (h *KnowledgeHandler) enqueueKnowledgeListReparse(
ctx context.Context, tenantID uint64, kbID string, ids []string, processConfig *types.KnowledgeProcessOverrides,
) (string, error) {
payload := types.KnowledgeListReparsePayload{
KnowledgeBaseID: kbID,
TenantID: tenantID,
KnowledgeIDs: ids,
ProcessConfig: processConfig,
Initiator: types.TaskInitiatorFromContext(ctx),
}
langfuse.InjectTracing(ctx, &payload)
payloadBytes, err := json.Marshal(payload)
if err != nil {
return "", fmt.Errorf("marshal payload: %w", err)
}
task := asynq.NewTask(types.TypeKnowledgeListReparse, payloadBytes,
asynq.Queue(types.QueueMaintenance), asynq.MaxRetry(3), asynq.Timeout(time.Hour))
info, err := h.asynqClient.Enqueue(task)
if err != nil {
return "", fmt.Errorf("enqueue task: %w", err)
}
return info.ID, nil
}
// CreateKnowledgeFromFile godoc
// @Summary 从文件创建知识
// @Description 上传文件并创建知识条目
// @Tags 知识管理
// @Accept multipart/form-data
// @Produce json
// @Param id path string true "知识库ID"
// @Param file formData file true "上传的文件"
// @Param fileName formData string false "自定义文件名"
// @Param metadata formData string false "元数据JSON"
// @Param enable_multimodel formData bool false "启用多模态处理"
// @Param tag_ids formData string false "分类ID列表,逗号分隔"
// @Param process_config formData string false "处理配置JSON(KnowledgeProcessOverrides)"
// @Success 200 {object} map[string]interface{} "创建的知识"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 409 {object} map[string]interface{} "文件重复"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge-bases/{id}/knowledge/file [post]
2025-08-05 07:08:07 +00:00
func (h *KnowledgeHandler) CreateKnowledgeFromFile(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start creating knowledge from file")
// Validate access to the knowledge base (only owner or admin/editor can create)
_, kbID, effectiveTenantID, permission, err := h.validateKnowledgeBaseAccess(c)
2025-08-05 07:08:07 +00:00
if err != nil {
c.Error(err)
return
}
ctx = types.WithExecutionTenant(c.Request.Context(), effectiveTenantID)
// Check write permission
if permission != types.OrgRoleAdmin && permission != types.OrgRoleEditor {
c.Error(errors.NewForbiddenError("No permission to create knowledge"))
return
}
2025-08-05 07:08:07 +00:00
// Validate file size — read MAX_FILE_SIZE_MB env (50MB default).
// Deliberately not a runtime system_setting; see filesize.go for the
// rationale (nginx / docreader / browser bundle all cache this at
// container startup, so a UI knob would silently mismatch).
maxSizeMB := utils.GetMaxFileSizeMB()
maxSize := maxSizeMB * 1024 * 1024
// Capped before the multipart parse, not after: FormFile buffers the whole
// body first, so the size check below only ever sees an upload we already
// accepted. nginx location /api/ still enforces MAX_FILE_SIZE; this is the
// same cap for requests that reach the app without that proxy.
limitUploadBody(c, maxSize)
2025-08-05 07:08:07 +00:00
// Get the uploaded file
file, err := c.FormFile("file")
if err != nil {
if isRequestBodyTooLarge(err) {
logger.Error(ctx, "File size too large")
c.Error(errors.NewBadRequestError(fmt.Sprintf("文件大小不能超过%dMB", maxSizeMB)))
return
}
2025-08-05 07:08:07 +00:00
logger.Error(ctx, "File upload failed", err)
c.Error(errors.NewBadRequestError("File upload failed").WithDetails(err.Error()))
return
}
if file.Size > maxSize {
logger.Error(ctx, "File size too large")
c.Error(errors.NewBadRequestError(fmt.Sprintf("文件大小不能超过%dMB", maxSizeMB)))
return
}
// Get custom filename if provided (for folder uploads with path)
customFileName := c.PostForm("fileName")
customFileName = secutils.SanitizeForLog(customFileName)
displayFileName := file.Filename
displayFileName = secutils.SanitizeForLog(displayFileName)
if customFileName != "" {
displayFileName = customFileName
logger.Infof(ctx, "Using custom filename: %s (original: %s)", customFileName, displayFileName)
}
logger.Infof(ctx, "File upload successful, filename: %s, size: %.2f KB", displayFileName, float64(file.Size)/1024)
logger.Infof(ctx, "Creating knowledge, knowledge base ID: %s, filename: %s", kbID, displayFileName)
2025-08-05 07:08:07 +00:00
// Parse metadata if provided
var metadata map[string]string
metadataStr := c.PostForm("metadata")
if metadataStr != "" {
if err := json.Unmarshal([]byte(metadataStr), &metadata); err != nil {
logger.Error(ctx, "Failed to parse metadata", err)
c.Error(errors.NewBadRequestError("Invalid metadata format").WithDetails(err.Error()))
return
}
logger.Infof(ctx, "Received file metadata: %s", secutils.SanitizeForLog(fmt.Sprintf("%v", metadata)))
2025-08-05 07:08:07 +00:00
}
enableMultimodelForm := c.PostForm("enable_multimodel")
var enableMultimodel *bool
if enableMultimodelForm != "" {
parseBool, err := strconv.ParseBool(enableMultimodelForm)
if err != nil {
logger.Error(ctx, "Failed to parse enable_multimodel", err)
c.Error(errors.NewBadRequestError("Invalid enable_multimodel format").WithDetails(err.Error()))
return
}
enableMultimodel = &parseBool
}
var processOverrides *types.KnowledgeProcessOverrides
if raw := c.PostForm("process_config"); raw != "" {
processOverrides = &types.KnowledgeProcessOverrides{}
if err := json.Unmarshal([]byte(raw), processOverrides); err != nil {
logger.Error(ctx, "Failed to parse process_config", err)
c.Error(errors.NewBadRequestError("Invalid process_config format").WithDetails(err.Error()))
return
}
}
if enableMultimodel != nil && (processOverrides == nil || processOverrides.EnableMultimodel == nil) {
if processOverrides == nil {
processOverrides = &types.KnowledgeProcessOverrides{EnableMultimodel: enableMultimodel}
} else {
processOverrides.EnableMultimodel = enableMultimodel
}
}
feat: support multi-tag for document knowledge (#1790) * feat: support multi-tag for document knowledge - Add knowledge_tag_relations join table for many-to-many tag-knowledge mapping - Migrate existing single tag_id data to the new table - Update Knowledge struct, filter, payload types (TagID -> Tags/TagIDs) - Rewrite repository layer: SetKnowledgeTags, GetKnowledgeTags, ListIDsByTagIDs - Update tag count references to query knowledge_tag_relations - Update service/handler layers for multi-tag create/list/batch-update - Frontend: multi-select tag sidebar, multi-tag chip display, tag toggle in popup - FAQ tags remain single-tag model (unchanged) * feat(knowledge): tag edit dialog with dynamic overflow and inline creation - Add TagEditDialog component with search, multi-select, and confirm - Replace inline t-popup tag selector with dialog-based editing - Tags overflow with +N badge, visible count adapts to container width via ResizeObserver - Date/card layout: fixed date width, tags flex to fill remaining space - Add persistent new-tag input bar in dialog (Enter to create, auto-select) - Tag creation emits callback to refresh parent tag list immediately - Apply same overflow + dialog trigger to both card view and list view - Add i18n keys: tagEditDialogTitle, tagEditSearch, tagSelectedCount, tagOverflowTip, tagNewPlaceholder * fix: exclude soft-deleted knowledge from tag reference counts CountReferences, BatchCountReferences, and DeleteUnusedTags now JOIN with knowledges table to filter out soft-deleted records when counting knowledge_tag_relations. Previously they queried knowledge_tag_relations directly without the deleted_at check, causing stale tag counts after knowledge deletion. * fix: refresh tag counts after async knowledge deletion completes Add a second delayed tag list refresh (2.5s) after tag deletion to capture updated reference counts for remaining tags. The original immediate refresh handles removing the deleted tag from the list, while this delayed refresh ensures other tags' counts are correct after the async deletion finishes. --------- Co-authored-by: lyingbug <xiayula2014@gmail.com>
2026-06-25 16:18:48 +00:00
// 获取分类ID列表(如果提供),逗号分隔,用于知识多标签分类管理
tagIDs := parseCommaSeparatedTagIDs(c.PostForm("tag_ids"))
channel := c.PostForm("channel")
// Reject malformed .json at the HTTP boundary so users get 400 immediately.
// Kept out of CreateKnowledgeFromFile so datasource sync / IM keep creating
// a knowledge row that fails in async parse instead of vanishing.
jsonCheckName := file.Filename
if customFileName != "" {
if _, base := types.SplitKnowledgeRelativePath(customFileName); base != "" {
jsonCheckName = base
}
}
if err := service.ValidateJSONUploadContent(jsonCheckName, file); err != nil {
logger.Errorf(ctx, "Invalid JSON upload content for %s: %v", jsonCheckName, err)
_ = c.Error(err)
return
}
2025-08-05 07:08:07 +00:00
// Create knowledge entry from the file
feat: support multi-tag for document knowledge (#1790) * feat: support multi-tag for document knowledge - Add knowledge_tag_relations join table for many-to-many tag-knowledge mapping - Migrate existing single tag_id data to the new table - Update Knowledge struct, filter, payload types (TagID -> Tags/TagIDs) - Rewrite repository layer: SetKnowledgeTags, GetKnowledgeTags, ListIDsByTagIDs - Update tag count references to query knowledge_tag_relations - Update service/handler layers for multi-tag create/list/batch-update - Frontend: multi-select tag sidebar, multi-tag chip display, tag toggle in popup - FAQ tags remain single-tag model (unchanged) * feat(knowledge): tag edit dialog with dynamic overflow and inline creation - Add TagEditDialog component with search, multi-select, and confirm - Replace inline t-popup tag selector with dialog-based editing - Tags overflow with +N badge, visible count adapts to container width via ResizeObserver - Date/card layout: fixed date width, tags flex to fill remaining space - Add persistent new-tag input bar in dialog (Enter to create, auto-select) - Tag creation emits callback to refresh parent tag list immediately - Apply same overflow + dialog trigger to both card view and list view - Add i18n keys: tagEditDialogTitle, tagEditSearch, tagSelectedCount, tagOverflowTip, tagNewPlaceholder * fix: exclude soft-deleted knowledge from tag reference counts CountReferences, BatchCountReferences, and DeleteUnusedTags now JOIN with knowledges table to filter out soft-deleted records when counting knowledge_tag_relations. Previously they queried knowledge_tag_relations directly without the deleted_at check, causing stale tag counts after knowledge deletion. * fix: refresh tag counts after async knowledge deletion completes Add a second delayed tag list refresh (2.5s) after tag deletion to capture updated reference counts for remaining tags. The original immediate refresh handles removing the deleted tag from the list, while this delayed refresh ensures other tags' counts are correct after the async deletion finishes. --------- Co-authored-by: lyingbug <xiayula2014@gmail.com>
2026-06-25 16:18:48 +00:00
knowledge, err := h.kgService.CreateKnowledgeFromFile(ctx, kbID, file, metadata, enableMultimodel, customFileName, tagIDs, channel, processOverrides)
2025-08-05 07:08:07 +00:00
// Check for duplicate knowledge error
if err != nil {
if h.handleDuplicateKnowledgeError(c, err, knowledge, "file") {
return
}
if appErr, ok := errors.IsAppError(err); ok {
c.Error(appErr)
return
}
2025-08-05 07:08:07 +00:00
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
logger.Infof(
ctx,
"Knowledge created successfully, ID: %s, title: %s",
secutils.SanitizeForLog(knowledge.ID),
secutils.SanitizeForLog(knowledge.Title),
)
2025-08-05 07:08:07 +00:00
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": knowledge,
})
}
// CreateKnowledgeFromURL godoc
// @Summary 从URL创建知识
// @Description 从指定URL抓取内容并创建知识条目。当提供 file_name/file_type 或 URL 路径含已知文件扩展名时,自动切换为文件下载模式
// @Tags 知识管理
// @Accept json
// @Produce json
// @Param id path string true "知识库ID"
// @Param request body object{url=string,file_name=string,file_type=string,enable_multimodel=bool,title=string,tag_ids=[]string} true "URL请求"
// @Success 201 {object} map[string]interface{} "创建的知识"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 409 {object} map[string]interface{} "URL重复"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge-bases/{id}/knowledge/url [post]
2025-08-05 07:08:07 +00:00
func (h *KnowledgeHandler) CreateKnowledgeFromURL(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start creating knowledge from URL")
// Validate access to the knowledge base (only owner or admin/editor can create)
_, kbID, effectiveTenantID, permission, err := h.validateKnowledgeBaseAccess(c)
2025-08-05 07:08:07 +00:00
if err != nil {
c.Error(err)
return
}
ctx = types.WithExecutionTenant(c.Request.Context(), effectiveTenantID)
// Check write permission
if permission != types.OrgRoleAdmin && permission != types.OrgRoleEditor {
c.Error(errors.NewForbiddenError("No permission to create knowledge"))
return
}
2025-08-05 07:08:07 +00:00
// Parse URL from request body
var req struct {
URL string `json:"url" binding:"required"`
FileName string `json:"file_name"`
FileType string `json:"file_type"`
EnableMultimodel *bool `json:"enable_multimodel"`
Title string `json:"title"`
feat: support multi-tag for document knowledge (#1790) * feat: support multi-tag for document knowledge - Add knowledge_tag_relations join table for many-to-many tag-knowledge mapping - Migrate existing single tag_id data to the new table - Update Knowledge struct, filter, payload types (TagID -> Tags/TagIDs) - Rewrite repository layer: SetKnowledgeTags, GetKnowledgeTags, ListIDsByTagIDs - Update tag count references to query knowledge_tag_relations - Update service/handler layers for multi-tag create/list/batch-update - Frontend: multi-select tag sidebar, multi-tag chip display, tag toggle in popup - FAQ tags remain single-tag model (unchanged) * feat(knowledge): tag edit dialog with dynamic overflow and inline creation - Add TagEditDialog component with search, multi-select, and confirm - Replace inline t-popup tag selector with dialog-based editing - Tags overflow with +N badge, visible count adapts to container width via ResizeObserver - Date/card layout: fixed date width, tags flex to fill remaining space - Add persistent new-tag input bar in dialog (Enter to create, auto-select) - Tag creation emits callback to refresh parent tag list immediately - Apply same overflow + dialog trigger to both card view and list view - Add i18n keys: tagEditDialogTitle, tagEditSearch, tagSelectedCount, tagOverflowTip, tagNewPlaceholder * fix: exclude soft-deleted knowledge from tag reference counts CountReferences, BatchCountReferences, and DeleteUnusedTags now JOIN with knowledges table to filter out soft-deleted records when counting knowledge_tag_relations. Previously they queried knowledge_tag_relations directly without the deleted_at check, causing stale tag counts after knowledge deletion. * fix: refresh tag counts after async knowledge deletion completes Add a second delayed tag list refresh (2.5s) after tag deletion to capture updated reference counts for remaining tags. The original immediate refresh handles removing the deleted tag from the list, while this delayed refresh ensures other tags' counts are correct after the async deletion finishes. --------- Co-authored-by: lyingbug <xiayula2014@gmail.com>
2026-06-25 16:18:48 +00:00
TagIDs []string `json:"tag_ids"`
Channel string `json:"channel"`
ProcessConfig *types.KnowledgeProcessOverrides `json:"process_config"`
2025-08-05 07:08:07 +00:00
}
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to parse URL request", err)
c.Error(errors.NewBadRequestError(err.Error()))
return
}
logger.Infof(ctx, "Received URL request: %s, file_name: %s, file_type: %s",
secutils.SanitizeForLog(req.URL),
secutils.SanitizeForLog(req.FileName),
secutils.SanitizeForLog(req.FileType),
)
// SSRF validation for user-supplied URL
if err := secutils.ValidateURLForSSRF(req.URL); err != nil {
logger.Warnf(ctx, "SSRF validation failed for knowledge URL: %v", err)
fix(initialization): surface upstream and SSRF errors verbatim in test-connection responses Test-connection's "连接失败" was nearly useless for debugging because two layers conspired to swallow the actual upstream error: Backend swallow --------------- checkChatModelConnection and CheckASRModel pattern-matched on the upstream error string (401 / 404 / timeout / ...) and replaced it with a fixed Chinese hint. The original SDK message (request URL, response body, provider's error code description) was discarded. Refactor: extract classifyConnectionError(errMsg) — returns just the short Chinese hint. Callers combine "<hint>:<raw err>" so the hint indicates "where to start looking" and the raw error shows "what actually happened". The status-400 special-case (endpoint reachable, parameter mismatch only) still returns success. Frontend swallow ---------------- ModelEditorDialog.testConnection ignored result.message on success paths (fine), but also overwrote it with a generic i18n string on failure paths and 4xx rejections — even though axios's interceptor already lifts the backend's error.message to error.message. Failure branch now uses error?.message || result.message as the toast content; i18n fallback only when neither is present. SSRF allowlist hint ------------------- SSRF validation failures previously returned "Base URL 未通过安全校验: <reason>" with no mention of how to recover (the allowlist is server-side, not configurable in the UI). Operators hit it and were stuck. New utils.FormatSSRFError(label, rawURL, err) wraps the error with guidance to add the host to SSRF_WHITELIST_EXTRA (the operator-facing append-only escape hatch — SSRF_WHITELIST itself is the project's baseline). The hint echoes the failed host so it can be copy-pasted straight into the env var: Base URL 未通过安全校验:DNS resolution failed for hostname test.local.com ... 如该地址确实可信,请联系运维在服务端环境变量 SSRF_WHITELIST_EXTRA 中加入该主机(支持精确域名 / *.example.com 通配 / IP / CIDR),示例:SSRF_WHITELIST_EXTRA=test.local.com, *.example.com,10.0.0.0/8 All SSRF call sites switch to the helper: initialization (CheckRemoteModel / TestEmbedding / CheckRerank / CheckASR / TestMultimodal / batch validation), model CRUD, mcp_service CRUD, knowledge URL ingest, system ReconnectDocReader.
2026-05-17 07:10:42 +00:00
c.Error(errors.NewBadRequestError(secutils.FormatSSRFError("URL", req.URL, err)))
return
}
logger.Infof(ctx,
"Creating knowledge from URL, knowledge base ID: %s, URL: %s",
secutils.SanitizeForLog(kbID),
secutils.SanitizeForLog(req.URL),
)
2025-08-05 07:08:07 +00:00
// Create knowledge entry from the URL
knowledge, err := h.kgService.CreateKnowledgeFromURL(
feat: support multi-tag for document knowledge (#1790) * feat: support multi-tag for document knowledge - Add knowledge_tag_relations join table for many-to-many tag-knowledge mapping - Migrate existing single tag_id data to the new table - Update Knowledge struct, filter, payload types (TagID -> Tags/TagIDs) - Rewrite repository layer: SetKnowledgeTags, GetKnowledgeTags, ListIDsByTagIDs - Update tag count references to query knowledge_tag_relations - Update service/handler layers for multi-tag create/list/batch-update - Frontend: multi-select tag sidebar, multi-tag chip display, tag toggle in popup - FAQ tags remain single-tag model (unchanged) * feat(knowledge): tag edit dialog with dynamic overflow and inline creation - Add TagEditDialog component with search, multi-select, and confirm - Replace inline t-popup tag selector with dialog-based editing - Tags overflow with +N badge, visible count adapts to container width via ResizeObserver - Date/card layout: fixed date width, tags flex to fill remaining space - Add persistent new-tag input bar in dialog (Enter to create, auto-select) - Tag creation emits callback to refresh parent tag list immediately - Apply same overflow + dialog trigger to both card view and list view - Add i18n keys: tagEditDialogTitle, tagEditSearch, tagSelectedCount, tagOverflowTip, tagNewPlaceholder * fix: exclude soft-deleted knowledge from tag reference counts CountReferences, BatchCountReferences, and DeleteUnusedTags now JOIN with knowledges table to filter out soft-deleted records when counting knowledge_tag_relations. Previously they queried knowledge_tag_relations directly without the deleted_at check, causing stale tag counts after knowledge deletion. * fix: refresh tag counts after async knowledge deletion completes Add a second delayed tag list refresh (2.5s) after tag deletion to capture updated reference counts for remaining tags. The original immediate refresh handles removing the deleted tag from the list, while this delayed refresh ensures other tags' counts are correct after the async deletion finishes. --------- Co-authored-by: lyingbug <xiayula2014@gmail.com>
2026-06-25 16:18:48 +00:00
ctx, kbID, req.URL, req.FileName, req.FileType, req.EnableMultimodel, req.Title, req.TagIDs, req.Channel, req.ProcessConfig,
)
2025-08-05 07:08:07 +00:00
// Check for duplicate knowledge error
if err != nil {
if h.handleDuplicateKnowledgeError(c, err, knowledge, "url") {
return
}
if appErr, ok := errors.IsAppError(err); ok {
c.Error(appErr)
return
}
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
logger.Infof(
ctx,
"Knowledge created successfully from URL, ID: %s, title: %s",
secutils.SanitizeForLog(knowledge.ID),
secutils.SanitizeForLog(knowledge.Title),
)
c.JSON(http.StatusCreated, gin.H{
"success": true,
"data": knowledge,
})
}
// CreateManualKnowledge godoc
// @Summary 手工创建知识
// @Description 手工录入Markdown格式的知识内容
// @Tags 知识管理
// @Accept json
// @Produce json
// @Param id path string true "知识库ID"
// @Param request body types.ManualKnowledgePayload true "手工知识内容"
// @Success 200 {object} map[string]interface{} "创建的知识"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge-bases/{id}/knowledge/manual [post]
func (h *KnowledgeHandler) CreateManualKnowledge(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start creating manual knowledge")
// Validate access to the knowledge base (only owner or admin/editor can create)
_, kbID, effectiveTenantID, permission, err := h.validateKnowledgeBaseAccess(c)
if err != nil {
c.Error(err)
return
}
ctx = types.WithExecutionTenant(c.Request.Context(), effectiveTenantID)
// Check write permission
if permission != types.OrgRoleAdmin && permission != types.OrgRoleEditor {
c.Error(errors.NewForbiddenError("No permission to create knowledge"))
return
}
var req types.ManualKnowledgePayload
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to parse manual knowledge request", err)
c.Error(errors.NewBadRequestError(err.Error()))
return
}
knowledge, err := h.kgService.CreateKnowledgeFromManual(ctx, kbID, &req, req.Channel)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
c.Error(appErr)
return
}
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"kb_id": kbID,
})
c.Error(errors.NewInternalServerError(err.Error()))
return
}
logger.Infof(ctx, "Manual knowledge created successfully, knowledge ID: %s",
secutils.SanitizeForLog(knowledge.ID))
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": knowledge,
})
}
// GetKnowledge godoc
// @Summary 获取知识详情
// @Description 根据ID获取知识条目详情
// @Tags 知识管理
// @Accept json
// @Produce json
// @Param id path string true "知识ID"
// @Success 200 {object} map[string]interface{} "知识详情"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 404 {object} errors.AppError "知识不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge/{id} [get]
2025-08-05 07:08:07 +00:00
func (h *KnowledgeHandler) GetKnowledge(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start retrieving knowledge")
id := secutils.SanitizeForLog(c.Param("id"))
2025-08-05 07:08:07 +00:00
if id == "" {
logger.Error(ctx, "Knowledge ID is empty")
c.Error(errors.NewBadRequestError("Knowledge ID cannot be empty"))
return
}
// Resolve knowledge and validate KB access (at least viewer)
knowledge, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, id, types.OrgRoleViewer)
2025-08-05 07:08:07 +00:00
if err != nil {
c.Error(err)
2025-08-05 07:08:07 +00:00
return
}
// Re-fetch with tenant-scoped service so tags and other joined fields are populated.
if knowledge, err = h.kgService.GetKnowledgeByID(effCtx, id); err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewNotFoundError("Knowledge not found"))
return
}
logger.Infof(ctx, "Knowledge retrieved successfully, ID: %s, title: %s",
secutils.SanitizeForLog(knowledge.ID), secutils.SanitizeForLog(knowledge.Title))
2025-08-05 07:08:07 +00:00
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": knowledge,
})
}
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
// GetKnowledgeSpans godoc
// @Summary 获取知识文档解析的 Span 树(含历史尝试)
// @Description 返回该知识在解析流水线的 trace tree(root → stage → subspan):每段状态、耗时、input/output、错误码、langfuse_trace_id。支持 ?attempt=N 查看历史尝试;不传则返回最新尝试。前端用于渲染时间线 + 多模态/embedding 子节点 + 一键跳转 Langfuse。
// @Tags 知识管理
// @Accept json
// @Produce json
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
// @Param id path string true "知识ID"
// @Param attempt query int false "指定尝试号;省略=最新"
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/knowledge/{id}/spans [get]
//
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
// Always returns the canonical 5-stage timeline; missing stage rows are
// synthesized as "pending" so the frontend timeline always renders five
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
// segments. Subspans (multimodal.image[i], generation.*) ride along under
// each stage as children when present.
func (h *KnowledgeHandler) GetKnowledgeSpans(c *gin.Context) {
ctx := c.Request.Context()
id := secutils.SanitizeForLog(c.Param("id"))
if id == "" {
c.Error(errors.NewBadRequestError("Knowledge ID cannot be empty"))
return
}
knowledge, _, err := h.resolveKnowledgeAndValidateKBAccess(c, id, types.OrgRoleViewer)
if err != nil {
c.Error(err)
return
}
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
// Pick attempt: explicit ?attempt=N wins; otherwise pull the
// latest attempt from the spans table. Lite-mode / fresh installs
// with zero rows fall through to attempt=0, in which case we
// return a placeholder tree (5 pending stages, no root, no
// children) so the UI still renders.
requestedAttempt := 0
if v := strings.TrimSpace(c.Query("attempt")); v != "" {
if n, perr := strconv.Atoi(v); perr == nil && n > 0 {
requestedAttempt = n
}
}
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
rows := []types.KnowledgeProcessingSpan{}
currentAttempt := 0
latestAttempt := 0
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
if h.spanRepo != nil {
latest, lerr := h.spanRepo.LatestAttempt(ctx, knowledge.ID)
if lerr != nil {
logger.Warnf(ctx, "spans LatestAttempt failed for %s: %v", knowledge.ID, lerr)
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
} else {
latestAttempt = latest
}
if requestedAttempt > 0 {
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
currentAttempt = requestedAttempt
} else {
currentAttempt = latestAttempt
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
}
if currentAttempt > 0 {
rows, err = h.spanRepo.ListByAttempt(ctx, knowledge.ID, currentAttempt)
if err != nil {
logger.Warnf(ctx, "spans ListByAttempt failed kid=%s attempt=%d: %v",
knowledge.ID, currentAttempt, err)
rows = nil
}
}
}
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
// Build tree: index by SpanID, then attach to parents. Stages
// missing from the DB are synthesized as "pending" placeholders
// under a synthetic (or real, if present) root so the timeline
// always renders five segments. parse_status threads through so
// pre-tracker historical knowledge (no rows but parse_status is
// already terminal) renders as done/failed instead of pending —
// otherwise legacy completed documents would forever look like
// they're still waiting in the queue.
tree, currentStageName, lastErr := buildSpanTree(knowledge.ID, currentAttempt, rows, knowledge.ParseStatus)
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
resp := gin.H{
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
"knowledge_id": knowledge.ID,
"attempt": currentAttempt,
"latest_attempt": latestAttempt,
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
"parse_status": knowledge.ParseStatus,
"current_attempt": currentAttempt,
"current_stage": currentStageName,
"trace": tree,
}
feat(knowledge): flag documents that stop making progress (#3557) * feat(knowledge): flag documents that stop making progress A document stuck in processing looked the same as one still working: a spinner that polled forever, no hint of where it stopped, and, hours later, a generic housekeeping failure. - The batch and spans endpoints return last_activity_at for in-flight rows: the later of updated_at and the newest span write. updated_at only moves at stage transitions; span writes keep moving while a long stage still works. - After 20 minutes with no progress, the list and card views show "may be stuck" with a tooltip. The timeline shows the stage it stopped at and a stop-parsing button, plus a "last progress" stat. Both pollers back off to 15s while everything in flight is stalled. - When housekeeping fails a row, the error names the stalled stage and the time of the last progress. It closes the row's open spans with TASK_STALLED (the running stage fails, the rest are cancelled), so the timeline shows where the run stopped instead of a spinner. * fix(knowledge): locate stalls in finalizing and tell backlog from stuck - Housekeeping reads the stall site from the latest attempt. It takes the running stages, or, when none runs (post-process closes its stage once enrichment is fanned out), the innermost running spans, mapped back to their stage. Those spans fail with TASK_STALLED and are named in the message; every stalled stage is listed in pipeline order. The other open spans are cancelled. Every closed span gets a duration, and the message leaves out the time when the heartbeat query failed. - The spans tree prefers a TASK_STALLED failure for last_error over a later subtask failure. current_stage falls back to the stage owning a running subspan. - Batch and spans responses flag rows quiet past the stall hint whose work is still queued (waiting_in_queue), using the sweep's own probes. At most 20 rows are probed per request, cached for a minute. The UI shows these as queued, with no stop button in the banner. * fix(knowledge): answer stall verdicts from one shared queue scan - Probing a quiet document for a backlog rescanned the whole queue once per document. When the document was absent, which is exactly the stuck case, the scan ran to the end, and it read a Redis error as "nothing queued". QueuedKnowledgeIDs now collects every referenced knowledge ID in one pass and returns list errors. HousekeepingService keeps that snapshot for a minute, shared across requests and single-flight. A failed scan is not cached. - With the per-request cap of 20 gone, every quiet row on a page gets a verdict. The response carries it as stall_state (queued or stalled), replacing waiting_in_queue. The UI marks a row as stuck only on a "stalled" verdict. A row with no verdict, because the probe failed, shows as ordinary processing instead of inviting a stop.
2026-09-22 13:34:08 +00:00
if isParseInFlight(knowledge.ParseStatus) {
last := spansLastActivity(knowledge.UpdatedAt, rows)
resp["last_activity_at"] = last
if time.Since(last) >= stallHintAfter {
if verdict := h.stallVerdicts(ctx, []string{knowledge.ID})[knowledge.ID]; verdict != "" {
resp["stall_state"] = verdict
}
}
}
if lastError := knowledgeSpansLastError(
currentAttempt,
latestAttempt,
knowledge.ParseStatus,
knowledge.ErrorMessage,
knowledge.UpdatedAt,
lastErr,
); lastError != nil {
resp["last_error"] = lastError
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": resp,
})
}
// knowledgeSpansLastError builds the last_error payload for GetKnowledgeSpans.
// Span failures win when present; otherwise a failed knowledge row without a
// matching span error (recovery / dead-letter paths) surfaces ErrorMessage.
func knowledgeSpansLastError(
currentAttempt, latestAttempt int,
parseStatus, knowledgeErrorMessage string,
knowledgeUpdatedAt time.Time,
spanFailure *types.KnowledgeProcessingSpan,
) gin.H {
if spanFailure != nil {
return gin.H{
"stage": spanFailure.Name,
"code": spanFailure.ErrorCode,
"message": spanFailure.ErrorMessage,
"name": spanFailure.Name,
"error_code": spanFailure.ErrorCode,
"error_message": spanFailure.ErrorMessage,
"finished_at": spanFailure.FinishedAt,
}
}
if currentAttempt != latestAttempt || parseStatus != types.ParseStatusFailed || knowledgeErrorMessage == "" {
return nil
}
errorCode := "UNKNOWN"
if strings.EqualFold(strings.TrimSpace(knowledgeErrorMessage),
"Task interrupted due to application restart") {
errorCode = "SERVER_RESTART"
}
return gin.H{
"stage": "knowledge_processing",
"code": errorCode,
"message": knowledgeErrorMessage,
"name": "knowledge_processing",
"error_code": errorCode,
"error_message": knowledgeErrorMessage,
"finished_at": knowledgeUpdatedAt,
}
}
// missingStageStatusFunc resolves a rowless stage against the real failure:
// earlier → skipped, downstream → cancelled, none → the parse_status fallback (#3452).
fix(knowledge): stop synthesizing never-run stages as failed Closes #3452. buildSpanTree fills every canonical stage that has no span row using a status inferred from knowledge.parse_status, so a failed parse painted all of them "failed". That status carries information it cannot know: it cannot tell "this stage ran and failed" from "this stage never ran". The frontend picks the focused stage with the first failed one in canonical order, so whenever the real failure left an earlier stage rowless, the UI named the earlier stage. On main today a text passage is chunked without ever opening a docreader stage, so an embedding failure reports 文档解析 / docreader as the broken step for content that has no document to parse, and four of five segments render as failures. Once a stage has actually recorded a failure its position is known, so missing stages are now resolved against it: - downstream of the failure, per StageDependencies or canonical order → cancelled, which is what the status is documented to mean - before it → skipped; the stage either did not apply or its row was never written, and neither of those is a failure With no failed row anywhere the parse_status fallback stands unchanged, which is the case it was written for: legacy knowledge parsed before span tracking existed still renders done/failed rather than five pending segments. Also maps parse_status "cancelled" to a cancelled placeholder; it fell through the switch to pending, so a cancelled document showed spinners on the stages it never reached. The DAG walk is redundant with canonical order for today's stage list, where every dependency points at an earlier stage. It is there so the answer stays right if the list is reordered or a stage gains an upstream that is not its predecessor. No frontend change: skipped and cancelled already render, with localized labels in every locale.
2026-09-20 06:10:52 +00:00
func missingStageStatusFunc(
stageRowByName map[string]*types.KnowledgeProcessingSpan, fallback string,
) func(string) string {
failedIdx := -1
for i, name := range types.AllStages {
if row, ok := stageRowByName[name]; ok && row.Status == types.SpanStatusFailed {
failedIdx = i
break
}
}
if failedIdx < 0 {
return func(string) string { return fallback }
}
// Redundant with canonical order today; keeps holding if stages are reordered.
fix(knowledge): stop synthesizing never-run stages as failed Closes #3452. buildSpanTree fills every canonical stage that has no span row using a status inferred from knowledge.parse_status, so a failed parse painted all of them "failed". That status carries information it cannot know: it cannot tell "this stage ran and failed" from "this stage never ran". The frontend picks the focused stage with the first failed one in canonical order, so whenever the real failure left an earlier stage rowless, the UI named the earlier stage. On main today a text passage is chunked without ever opening a docreader stage, so an embedding failure reports 文档解析 / docreader as the broken step for content that has no document to parse, and four of five segments render as failures. Once a stage has actually recorded a failure its position is known, so missing stages are now resolved against it: - downstream of the failure, per StageDependencies or canonical order → cancelled, which is what the status is documented to mean - before it → skipped; the stage either did not apply or its row was never written, and neither of those is a failure With no failed row anywhere the parse_status fallback stands unchanged, which is the case it was written for: legacy knowledge parsed before span tracking existed still renders done/failed rather than five pending segments. Also maps parse_status "cancelled" to a cancelled placeholder; it fell through the switch to pending, so a cancelled document showed spinners on the stages it never reached. The DAG walk is redundant with canonical order for today's stage list, where every dependency points at an earlier stage. It is there so the answer stays right if the list is reordered or a stage gains an upstream that is not its predecessor. No frontend change: skipped and cancelled already render, with localized labels in every locale.
2026-09-20 06:10:52 +00:00
cancelled := map[string]bool{}
var markDependents func(string)
markDependents = func(stage string) {
for candidate, upstreams := range types.StageDependencies {
if cancelled[candidate] {
continue
}
for _, up := range upstreams {
if up == stage {
cancelled[candidate] = true
markDependents(candidate)
break
}
}
}
}
markDependents(types.AllStages[failedIdx])
stageIdx := make(map[string]int, len(types.AllStages))
for i, name := range types.AllStages {
stageIdx[name] = i
}
return func(name string) string {
if cancelled[name] || stageIdx[name] > failedIdx {
return types.SpanStatusCancelled
}
return types.SpanStatusSkipped
}
}
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
// buildSpanTree assembles a flat list of span rows into a parent-child
// tree rooted at the (knowledge, attempt)'s root span. Missing canonical
// stages are filled in with pending placeholders so the UI always renders
// the five timeline segments. Returns the root, the current_stage name
// (the running stage if any), and the most recent failed span if one
// exists.
//
// parseStatus is the knowledge.parse_status string. When the spans table
// has zero rows for this attempt (legacy data parsed before tracking, or
// a fresh knowledge before the pipeline starts), the placeholder status
// is inferred from parseStatus: completed → done, failed → failed,
// otherwise pending. Without this, every historical knowledge would
// render as "all 5 stages pending" forever despite having actually
// completed parsing.
func buildSpanTree(knowledgeID string, attempt int, rows []types.KnowledgeProcessingSpan, parseStatus string) (
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
root *types.SpanTreeNode, currentStage string, lastFailure *types.KnowledgeProcessingSpan,
) {
now := time.Now()
// Build node lookup, identify root.
nodes := make(map[string]*types.SpanTreeNode, len(rows))
var rootRow *types.KnowledgeProcessingSpan
stageRowByName := map[string]*types.KnowledgeProcessingSpan{}
for i := range rows {
r := rows[i]
nodes[r.SpanID] = &types.SpanTreeNode{KnowledgeProcessingSpan: r}
if r.Kind == types.SpanKindRoot && rootRow == nil {
cp := r
rootRow = &cp
}
if r.Kind == types.SpanKindStage {
cp := r
stageRowByName[r.Name] = &cp
}
if r.Status == types.SpanStatusRunning && r.Kind == types.SpanKindStage && currentStage == "" {
currentStage = r.Name
}
feat(knowledge): flag documents that stop making progress (#3557) * feat(knowledge): flag documents that stop making progress A document stuck in processing looked the same as one still working: a spinner that polled forever, no hint of where it stopped, and, hours later, a generic housekeeping failure. - The batch and spans endpoints return last_activity_at for in-flight rows: the later of updated_at and the newest span write. updated_at only moves at stage transitions; span writes keep moving while a long stage still works. - After 20 minutes with no progress, the list and card views show "may be stuck" with a tooltip. The timeline shows the stage it stopped at and a stop-parsing button, plus a "last progress" stat. Both pollers back off to 15s while everything in flight is stalled. - When housekeeping fails a row, the error names the stalled stage and the time of the last progress. It closes the row's open spans with TASK_STALLED (the running stage fails, the rest are cancelled), so the timeline shows where the run stopped instead of a spinner. * fix(knowledge): locate stalls in finalizing and tell backlog from stuck - Housekeeping reads the stall site from the latest attempt. It takes the running stages, or, when none runs (post-process closes its stage once enrichment is fanned out), the innermost running spans, mapped back to their stage. Those spans fail with TASK_STALLED and are named in the message; every stalled stage is listed in pipeline order. The other open spans are cancelled. Every closed span gets a duration, and the message leaves out the time when the heartbeat query failed. - The spans tree prefers a TASK_STALLED failure for last_error over a later subtask failure. current_stage falls back to the stage owning a running subspan. - Batch and spans responses flag rows quiet past the stall hint whose work is still queued (waiting_in_queue), using the sweep's own probes. At most 20 rows are probed per request, cached for a minute. The UI shows these as queued, with no stop button in the banner. * fix(knowledge): answer stall verdicts from one shared queue scan - Probing a quiet document for a backlog rescanned the whole queue once per document. When the document was absent, which is exactly the stuck case, the scan ran to the end, and it read a Redis error as "nothing queued". QueuedKnowledgeIDs now collects every referenced knowledge ID in one pass and returns list errors. HousekeepingService keeps that snapshot for a minute, shared across requests and single-flight. A failed scan is not cached. - With the per-request cap of 20 gone, every quiet row on a page gets a verdict. The response carries it as stall_state (queued or stalled), replacing waiting_in_queue. The UI marks a row as stuck only on a "stalled" verdict. A row with no verdict, because the probe failed, shows as ordinary processing instead of inviting a stop.
2026-09-22 13:34:08 +00:00
// Housekeeping's TASK_STALLED marks where a stuck run stopped;
// an older subtask failure must not hide it.
if r.Status == types.SpanStatusFailed &&
(lastFailure == nil || !isStallFailure(lastFailure) || isStallFailure(&r)) {
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
cp := r
lastFailure = &cp
}
}
feat(knowledge): flag documents that stop making progress (#3557) * feat(knowledge): flag documents that stop making progress A document stuck in processing looked the same as one still working: a spinner that polled forever, no hint of where it stopped, and, hours later, a generic housekeeping failure. - The batch and spans endpoints return last_activity_at for in-flight rows: the later of updated_at and the newest span write. updated_at only moves at stage transitions; span writes keep moving while a long stage still works. - After 20 minutes with no progress, the list and card views show "may be stuck" with a tooltip. The timeline shows the stage it stopped at and a stop-parsing button, plus a "last progress" stat. Both pollers back off to 15s while everything in flight is stalled. - When housekeeping fails a row, the error names the stalled stage and the time of the last progress. It closes the row's open spans with TASK_STALLED (the running stage fails, the rest are cancelled), so the timeline shows where the run stopped instead of a spinner. * fix(knowledge): locate stalls in finalizing and tell backlog from stuck - Housekeeping reads the stall site from the latest attempt. It takes the running stages, or, when none runs (post-process closes its stage once enrichment is fanned out), the innermost running spans, mapped back to their stage. Those spans fail with TASK_STALLED and are named in the message; every stalled stage is listed in pipeline order. The other open spans are cancelled. Every closed span gets a duration, and the message leaves out the time when the heartbeat query failed. - The spans tree prefers a TASK_STALLED failure for last_error over a later subtask failure. current_stage falls back to the stage owning a running subspan. - Batch and spans responses flag rows quiet past the stall hint whose work is still queued (waiting_in_queue), using the sweep's own probes. At most 20 rows are probed per request, cached for a minute. The UI shows these as queued, with no stop button in the banner. * fix(knowledge): answer stall verdicts from one shared queue scan - Probing a quiet document for a backlog rescanned the whole queue once per document. When the document was absent, which is exactly the stuck case, the scan ran to the end, and it read a Redis error as "nothing queued". QueuedKnowledgeIDs now collects every referenced knowledge ID in one pass and returns list errors. HousekeepingService keeps that snapshot for a minute, shared across requests and single-flight. A failed scan is not cached. - With the per-request cap of 20 gone, every quiet row on a page gets a verdict. The response carries it as stall_state (queued or stalled), replacing waiting_in_queue. The UI marks a row as stuck only on a "stalled" verdict. A row with no verdict, because the probe failed, shows as ordinary processing instead of inviting a stop.
2026-09-22 13:34:08 +00:00
if currentStage == "" {
currentStage = stageOfRunningSpan(rows)
}
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
// Pick the synthesized stage status from parse_status. Without this,
// historical knowledge that completed before span tracking was wired
// would render as "5 pending stages" forever — the rows simply
// weren't recorded, but parse_status correctly reads "completed".
// The synthesized stages don't carry duration/timing data; they
// just communicate the inferred terminal state.
syntheticStatus := types.SpanStatusPending
switch parseStatus {
case types.ParseStatusCompleted:
syntheticStatus = types.SpanStatusDone
case types.ParseStatusFailed:
syntheticStatus = types.SpanStatusFailed
fix(knowledge): stop synthesizing never-run stages as failed Closes #3452. buildSpanTree fills every canonical stage that has no span row using a status inferred from knowledge.parse_status, so a failed parse painted all of them "failed". That status carries information it cannot know: it cannot tell "this stage ran and failed" from "this stage never ran". The frontend picks the focused stage with the first failed one in canonical order, so whenever the real failure left an earlier stage rowless, the UI named the earlier stage. On main today a text passage is chunked without ever opening a docreader stage, so an embedding failure reports 文档解析 / docreader as the broken step for content that has no document to parse, and four of five segments render as failures. Once a stage has actually recorded a failure its position is known, so missing stages are now resolved against it: - downstream of the failure, per StageDependencies or canonical order → cancelled, which is what the status is documented to mean - before it → skipped; the stage either did not apply or its row was never written, and neither of those is a failure With no failed row anywhere the parse_status fallback stands unchanged, which is the case it was written for: legacy knowledge parsed before span tracking existed still renders done/failed rather than five pending segments. Also maps parse_status "cancelled" to a cancelled placeholder; it fell through the switch to pending, so a cancelled document showed spinners on the stages it never reached. The DAG walk is redundant with canonical order for today's stage list, where every dependency points at an earlier stage. It is there so the answer stays right if the list is reordered or a stage gains an upstream that is not its predecessor. No frontend change: skipped and cancelled already render, with localized labels in every locale.
2026-09-20 06:10:52 +00:00
case types.ParseStatusCancelled:
syntheticStatus = types.SpanStatusCancelled
}
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
// Synthesize root if no rows came back so the API contract stays
// stable (frontend always expects a `trace` object).
if rootRow == nil {
root = &types.SpanTreeNode{KnowledgeProcessingSpan: types.KnowledgeProcessingSpan{
KnowledgeID: knowledgeID,
Attempt: attempt,
SpanID: "",
Name: "knowledge_processing",
Kind: types.SpanKindRoot,
Status: syntheticStatus,
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
CreatedAt: now,
UpdatedAt: now,
}}
} else {
root = nodes[rootRow.SpanID]
}
// Link real children to their parents. Walk `rows` (not the
// `nodes` map!) so the append order matches the repo's stable
// `ORDER BY id ASC`. Iterating the map directly would give
// callers a different child ordering on every request — Go map
// iteration is intentionally randomised — and the UI would
// flicker subspans into a different order on each refresh.
for i := range rows {
r := &rows[i]
n := nodes[r.SpanID]
if n == nil || n == root {
continue
}
if r.ParentSpanID == "" {
// Real top-level row with no parent and not the root
// itself — attach to root so it doesn't dangle.
root.Children = append(root.Children, n)
continue
}
parent, ok := nodes[r.ParentSpanID]
if !ok {
// Unknown parent (orphan); attach to root.
root.Children = append(root.Children, n)
continue
}
parent.Children = append(parent.Children, n)
}
// Synthesize missing stage rows as children of root so the timeline
// always shows 5 segments. Status mirrors the synthesized root —
// pending while the pipeline is still running, done/failed for
// historical knowledge whose terminal state we know but whose
// per-stage timing was never recorded. Appended in AllStages order
// so the canonical stage layout is deterministic regardless of
// which rows are missing.
fix(knowledge): stop synthesizing never-run stages as failed Closes #3452. buildSpanTree fills every canonical stage that has no span row using a status inferred from knowledge.parse_status, so a failed parse painted all of them "failed". That status carries information it cannot know: it cannot tell "this stage ran and failed" from "this stage never ran". The frontend picks the focused stage with the first failed one in canonical order, so whenever the real failure left an earlier stage rowless, the UI named the earlier stage. On main today a text passage is chunked without ever opening a docreader stage, so an embedding failure reports 文档解析 / docreader as the broken step for content that has no document to parse, and four of five segments render as failures. Once a stage has actually recorded a failure its position is known, so missing stages are now resolved against it: - downstream of the failure, per StageDependencies or canonical order → cancelled, which is what the status is documented to mean - before it → skipped; the stage either did not apply or its row was never written, and neither of those is a failure With no failed row anywhere the parse_status fallback stands unchanged, which is the case it was written for: legacy knowledge parsed before span tracking existed still renders done/failed rather than five pending segments. Also maps parse_status "cancelled" to a cancelled placeholder; it fell through the switch to pending, so a cancelled document showed spinners on the stages it never reached. The DAG walk is redundant with canonical order for today's stage list, where every dependency points at an earlier stage. It is there so the answer stays right if the list is reordered or a stage gains an upstream that is not its predecessor. No frontend change: skipped and cancelled already render, with localized labels in every locale.
2026-09-20 06:10:52 +00:00
missingStageStatus := missingStageStatusFunc(stageRowByName, syntheticStatus)
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
for _, name := range types.AllStages {
if _, ok := stageRowByName[name]; ok {
continue
}
placeholder := types.KnowledgeProcessingSpan{
KnowledgeID: knowledgeID,
Attempt: attempt,
Name: name,
Kind: types.SpanKindStage,
fix(knowledge): stop synthesizing never-run stages as failed Closes #3452. buildSpanTree fills every canonical stage that has no span row using a status inferred from knowledge.parse_status, so a failed parse painted all of them "failed". That status carries information it cannot know: it cannot tell "this stage ran and failed" from "this stage never ran". The frontend picks the focused stage with the first failed one in canonical order, so whenever the real failure left an earlier stage rowless, the UI named the earlier stage. On main today a text passage is chunked without ever opening a docreader stage, so an embedding failure reports 文档解析 / docreader as the broken step for content that has no document to parse, and four of five segments render as failures. Once a stage has actually recorded a failure its position is known, so missing stages are now resolved against it: - downstream of the failure, per StageDependencies or canonical order → cancelled, which is what the status is documented to mean - before it → skipped; the stage either did not apply or its row was never written, and neither of those is a failure With no failed row anywhere the parse_status fallback stands unchanged, which is the case it was written for: legacy knowledge parsed before span tracking existed still renders done/failed rather than five pending segments. Also maps parse_status "cancelled" to a cancelled placeholder; it fell through the switch to pending, so a cancelled document showed spinners on the stages it never reached. The DAG walk is redundant with canonical order for today's stage list, where every dependency points at an earlier stage. It is there so the answer stays right if the list is reordered or a stage gains an upstream that is not its predecessor. No frontend change: skipped and cancelled already render, with localized labels in every locale.
2026-09-20 06:10:52 +00:00
Status: missingStageStatus(name),
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
CreatedAt: now,
UpdatedAt: now,
}
root.Children = append(root.Children, &types.SpanTreeNode{KnowledgeProcessingSpan: placeholder})
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
}
return root, currentStage, lastFailure
}
// ListKnowledge godoc
// @Summary 获取知识列表
// @Description 获取知识库下的知识列表,支持分页和筛选
// @Tags 知识管理
// @Accept json
// @Produce json
// @Param id path string true "知识库ID"
// @Param page query int false "页码"
// @Param page_size query int false "每页数量"
// @Param tag_ids query string false "标签ID筛选,逗号分隔(OR语义)"
feat(knowledge-base): document list filters and explicit batch-management UX Add three new optional filters to the document list under a knowledge base detail page — parse status, source/channel, and updated time range — and rework multi-select to no longer cause the card title to jitter on hover. Backend - Introduce types.KnowledgeListFilter to aggregate optional filter dimensions (tag, keyword, file_type, parse_status, source, updated_from/to) and switch ListPagedKnowledgeByKnowledgeBaseID (repository/service/interface) to accept it instead of a growing positional parameter list. - The ListKnowledge HTTP handler accepts new parse_status, source, start_time and end_time query params; time params accept RFC3339, "YYYY-MM-DD HH:MM:SS" and "YYYY-MM-DD". The repository routes source="manual"/"url" onto the type column to stay consistent with file_type semantics; other source values match the channel column. - Update the four other callers (agent_service, initialization) to pass an empty filter struct, preserving prior behavior. Frontend - Add three controls in the doc-filter-bar (status select, source select, date-range picker with future-date disabled) wired through getKnowled / listKnowledgeFiles into the new backend params. - Replace the hover-triggered card checkbox with an explicit "批量管理" mode (mirrors the session list UX): in card view the checkbox only renders while batch mode is on, entered via the per-card "..." menu; the list view keeps its leading checkbox column. Switching from list to grid auto-enables batch mode when something is already selected, so the selection stays visible. - DocumentBatchBar now stays open whenever batch mode or selection > 0, and its "取消选择" button both clears the selection and exits batch mode. API surface sync - Regenerate Swagger artifacts (docs/docs.go / swagger.json / swagger.yaml). - Update docs/api/knowledge.md with the new query parameters. - Add backward-compatible ListKnowledgeWithFilter + KnowledgeListFilter to the Go SDK; the existing ListKnowledge keeps its signature. i18n - New filter labels in zh-CN / en-US / ko-KR / ru-RU; reuse existing menu.batchManage / batchManage.cancel for the multi-select strings.
2026-05-12 10:16:34 +00:00
// @Param keyword query string false "关键词搜索"
// @Param file_type query string false "文件类型筛选"
// @Param parse_status query string false "解析状态筛选 (pending/processing/completed/failed)"
// @Param source query string false "来源/渠道筛选 (web/api/feishu/notion/yuque/wechat/...,或 manual/url 按 type 过滤)"
// @Param start_time query string false "更新时间起点,RFC3339 格式"
// @Param end_time query string false "更新时间终点,RFC3339 格式"
// @Param folder_path query string false "文件夹路径筛选,空字符串表示知识库根目录;不传该参数则不按文件夹过滤"
// @Param folder_recursive query bool false "为 true 时同时返回子文件夹内的文档"
// @Param sort_by query string false "排序字段: updated_at/created_at/file_name,默认 created_at"
// @Param sort_order query string false "排序方向: asc/desc,默认 desc"
// @Success 200 {object} map[string]interface{} "知识列表"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge-bases/{id}/knowledge [get]
2025-08-05 07:08:07 +00:00
func (h *KnowledgeHandler) ListKnowledge(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start retrieving knowledge list")
// Validate access to the knowledge base (read access - any permission level)
_, kbID, effectiveTenantID, _, err := h.validateKnowledgeBaseAccess(c)
if err != nil {
c.Error(err)
2025-08-05 07:08:07 +00:00
return
}
// Update context with effective tenant ID for shared KB access
ctx = types.WithExecutionTenant(c.Request.Context(), effectiveTenantID)
2025-08-05 07:08:07 +00:00
// Parse pagination parameters from query string
var pagination types.Pagination
if err := c.ShouldBindQuery(&pagination); err != nil {
logger.Error(ctx, "Failed to parse pagination parameters", err)
c.Error(errors.NewBadRequestError(err.Error()))
return
}
feat(knowledge-base): document list filters and explicit batch-management UX Add three new optional filters to the document list under a knowledge base detail page — parse status, source/channel, and updated time range — and rework multi-select to no longer cause the card title to jitter on hover. Backend - Introduce types.KnowledgeListFilter to aggregate optional filter dimensions (tag, keyword, file_type, parse_status, source, updated_from/to) and switch ListPagedKnowledgeByKnowledgeBaseID (repository/service/interface) to accept it instead of a growing positional parameter list. - The ListKnowledge HTTP handler accepts new parse_status, source, start_time and end_time query params; time params accept RFC3339, "YYYY-MM-DD HH:MM:SS" and "YYYY-MM-DD". The repository routes source="manual"/"url" onto the type column to stay consistent with file_type semantics; other source values match the channel column. - Update the four other callers (agent_service, initialization) to pass an empty filter struct, preserving prior behavior. Frontend - Add three controls in the doc-filter-bar (status select, source select, date-range picker with future-date disabled) wired through getKnowled / listKnowledgeFiles into the new backend params. - Replace the hover-triggered card checkbox with an explicit "批量管理" mode (mirrors the session list UX): in card view the checkbox only renders while batch mode is on, entered via the per-card "..." menu; the list view keeps its leading checkbox column. Switching from list to grid auto-enables batch mode when something is already selected, so the selection stays visible. - DocumentBatchBar now stays open whenever batch mode or selection > 0, and its "取消选择" button both clears the selection and exits batch mode. API surface sync - Regenerate Swagger artifacts (docs/docs.go / swagger.json / swagger.yaml). - Update docs/api/knowledge.md with the new query parameters. - Add backward-compatible ListKnowledgeWithFilter + KnowledgeListFilter to the Go SDK; the existing ListKnowledge keeps its signature. i18n - New filter labels in zh-CN / en-US / ko-KR / ru-RU; reuse existing menu.batchManage / batchManage.cancel for the multi-select strings.
2026-05-12 10:16:34 +00:00
filter := types.KnowledgeListFilter{
feat: support multi-tag for document knowledge (#1790) * feat: support multi-tag for document knowledge - Add knowledge_tag_relations join table for many-to-many tag-knowledge mapping - Migrate existing single tag_id data to the new table - Update Knowledge struct, filter, payload types (TagID -> Tags/TagIDs) - Rewrite repository layer: SetKnowledgeTags, GetKnowledgeTags, ListIDsByTagIDs - Update tag count references to query knowledge_tag_relations - Update service/handler layers for multi-tag create/list/batch-update - Frontend: multi-select tag sidebar, multi-tag chip display, tag toggle in popup - FAQ tags remain single-tag model (unchanged) * feat(knowledge): tag edit dialog with dynamic overflow and inline creation - Add TagEditDialog component with search, multi-select, and confirm - Replace inline t-popup tag selector with dialog-based editing - Tags overflow with +N badge, visible count adapts to container width via ResizeObserver - Date/card layout: fixed date width, tags flex to fill remaining space - Add persistent new-tag input bar in dialog (Enter to create, auto-select) - Tag creation emits callback to refresh parent tag list immediately - Apply same overflow + dialog trigger to both card view and list view - Add i18n keys: tagEditDialogTitle, tagEditSearch, tagSelectedCount, tagOverflowTip, tagNewPlaceholder * fix: exclude soft-deleted knowledge from tag reference counts CountReferences, BatchCountReferences, and DeleteUnusedTags now JOIN with knowledges table to filter out soft-deleted records when counting knowledge_tag_relations. Previously they queried knowledge_tag_relations directly without the deleted_at check, causing stale tag counts after knowledge deletion. * fix: refresh tag counts after async knowledge deletion completes Add a second delayed tag list refresh (2.5s) after tag deletion to capture updated reference counts for remaining tags. The original immediate refresh handles removing the deleted tag from the list, while this delayed refresh ensures other tags' counts are correct after the async deletion finishes. --------- Co-authored-by: lyingbug <xiayula2014@gmail.com>
2026-06-25 16:18:48 +00:00
TagIDs: parseCommaSeparatedTagIDs(c.Query("tag_ids")),
feat(knowledge-base): document list filters and explicit batch-management UX Add three new optional filters to the document list under a knowledge base detail page — parse status, source/channel, and updated time range — and rework multi-select to no longer cause the card title to jitter on hover. Backend - Introduce types.KnowledgeListFilter to aggregate optional filter dimensions (tag, keyword, file_type, parse_status, source, updated_from/to) and switch ListPagedKnowledgeByKnowledgeBaseID (repository/service/interface) to accept it instead of a growing positional parameter list. - The ListKnowledge HTTP handler accepts new parse_status, source, start_time and end_time query params; time params accept RFC3339, "YYYY-MM-DD HH:MM:SS" and "YYYY-MM-DD". The repository routes source="manual"/"url" onto the type column to stay consistent with file_type semantics; other source values match the channel column. - Update the four other callers (agent_service, initialization) to pass an empty filter struct, preserving prior behavior. Frontend - Add three controls in the doc-filter-bar (status select, source select, date-range picker with future-date disabled) wired through getKnowled / listKnowledgeFiles into the new backend params. - Replace the hover-triggered card checkbox with an explicit "批量管理" mode (mirrors the session list UX): in card view the checkbox only renders while batch mode is on, entered via the per-card "..." menu; the list view keeps its leading checkbox column. Switching from list to grid auto-enables batch mode when something is already selected, so the selection stays visible. - DocumentBatchBar now stays open whenever batch mode or selection > 0, and its "取消选择" button both clears the selection and exits batch mode. API surface sync - Regenerate Swagger artifacts (docs/docs.go / swagger.json / swagger.yaml). - Update docs/api/knowledge.md with the new query parameters. - Add backward-compatible ListKnowledgeWithFilter + KnowledgeListFilter to the Go SDK; the existing ListKnowledge keeps its signature. i18n - New filter labels in zh-CN / en-US / ko-KR / ru-RU; reuse existing menu.batchManage / batchManage.cancel for the multi-select strings.
2026-05-12 10:16:34 +00:00
Keyword: c.Query("keyword"),
FileType: c.Query("file_type"),
ParseStatus: c.Query("parse_status"),
Source: c.Query("source"),
SortBy: types.KnowledgeListSortField(
c.DefaultQuery("sort_by", string(types.KnowledgeListSortByCreatedAt)),
),
SortOrder: types.KnowledgeListSortOrder(
c.DefaultQuery("sort_order", string(types.KnowledgeListSortDescending)),
),
}
if !filter.SortBy.Valid() {
_ = c.Error(errors.NewBadRequestError("invalid sort_by: must be updated_at, created_at, or file_name"))
return
}
if !filter.SortOrder.Valid() {
_ = c.Error(errors.NewBadRequestError("invalid sort_order: must be asc or desc"))
return
feat(knowledge-base): document list filters and explicit batch-management UX Add three new optional filters to the document list under a knowledge base detail page — parse status, source/channel, and updated time range — and rework multi-select to no longer cause the card title to jitter on hover. Backend - Introduce types.KnowledgeListFilter to aggregate optional filter dimensions (tag, keyword, file_type, parse_status, source, updated_from/to) and switch ListPagedKnowledgeByKnowledgeBaseID (repository/service/interface) to accept it instead of a growing positional parameter list. - The ListKnowledge HTTP handler accepts new parse_status, source, start_time and end_time query params; time params accept RFC3339, "YYYY-MM-DD HH:MM:SS" and "YYYY-MM-DD". The repository routes source="manual"/"url" onto the type column to stay consistent with file_type semantics; other source values match the channel column. - Update the four other callers (agent_service, initialization) to pass an empty filter struct, preserving prior behavior. Frontend - Add three controls in the doc-filter-bar (status select, source select, date-range picker with future-date disabled) wired through getKnowled / listKnowledgeFiles into the new backend params. - Replace the hover-triggered card checkbox with an explicit "批量管理" mode (mirrors the session list UX): in card view the checkbox only renders while batch mode is on, entered via the per-card "..." menu; the list view keeps its leading checkbox column. Switching from list to grid auto-enables batch mode when something is already selected, so the selection stays visible. - DocumentBatchBar now stays open whenever batch mode or selection > 0, and its "取消选择" button both clears the selection and exits batch mode. API surface sync - Regenerate Swagger artifacts (docs/docs.go / swagger.json / swagger.yaml). - Update docs/api/knowledge.md with the new query parameters. - Add backward-compatible ListKnowledgeWithFilter + KnowledgeListFilter to the Go SDK; the existing ListKnowledge keeps its signature. i18n - New filter labels in zh-CN / en-US / ko-KR / ru-RU; reuse existing menu.batchManage / batchManage.cancel for the multi-select strings.
2026-05-12 10:16:34 +00:00
}
if raw := c.Query("start_time"); raw != "" {
t, err := parseFilterTime(raw)
if err != nil {
c.Error(errors.NewBadRequestError("invalid start_time: " + err.Error()))
return
}
filter.UpdatedFrom = t
}
if raw := c.Query("end_time"); raw != "" {
t, err := parseFilterTime(raw)
if err != nil {
c.Error(errors.NewBadRequestError("invalid end_time: " + err.Error()))
return
}
filter.UpdatedTo = t
}
// The folder dimension is opt-in by parameter *presence*: an empty
// folder_path is meaningful (the knowledge base root), so it cannot be
// distinguished from "no folder filter" by value alone.
if raw, ok := c.GetQuery("folder_path"); ok {
filter.FolderPath = types.NormalizeKnowledgeFolderPath(raw)
filter.FolderScope = types.FolderScopeExact
if recursive, err := strconv.ParseBool(c.DefaultQuery("folder_recursive", "false")); err == nil && recursive {
filter.FolderScope = types.FolderScopeSubtree
}
}
2025-11-17 10:15:02 +00:00
logger.Infof(
ctx,
"Retrieving knowledge list under knowledge base, kb_id=%s tag_ids=%s keyword=%s file_type=%s "+
"parse_status=%s source=%s start_time=%s end_time=%s folder_path=%s folder_scope=%s "+
"sort_by=%s sort_order=%s page=%d page_size=%d effectiveTenantID=%d",
secutils.SanitizeForLog(kbID),
feat: support multi-tag for document knowledge (#1790) * feat: support multi-tag for document knowledge - Add knowledge_tag_relations join table for many-to-many tag-knowledge mapping - Migrate existing single tag_id data to the new table - Update Knowledge struct, filter, payload types (TagID -> Tags/TagIDs) - Rewrite repository layer: SetKnowledgeTags, GetKnowledgeTags, ListIDsByTagIDs - Update tag count references to query knowledge_tag_relations - Update service/handler layers for multi-tag create/list/batch-update - Frontend: multi-select tag sidebar, multi-tag chip display, tag toggle in popup - FAQ tags remain single-tag model (unchanged) * feat(knowledge): tag edit dialog with dynamic overflow and inline creation - Add TagEditDialog component with search, multi-select, and confirm - Replace inline t-popup tag selector with dialog-based editing - Tags overflow with +N badge, visible count adapts to container width via ResizeObserver - Date/card layout: fixed date width, tags flex to fill remaining space - Add persistent new-tag input bar in dialog (Enter to create, auto-select) - Tag creation emits callback to refresh parent tag list immediately - Apply same overflow + dialog trigger to both card view and list view - Add i18n keys: tagEditDialogTitle, tagEditSearch, tagSelectedCount, tagOverflowTip, tagNewPlaceholder * fix: exclude soft-deleted knowledge from tag reference counts CountReferences, BatchCountReferences, and DeleteUnusedTags now JOIN with knowledges table to filter out soft-deleted records when counting knowledge_tag_relations. Previously they queried knowledge_tag_relations directly without the deleted_at check, causing stale tag counts after knowledge deletion. * fix: refresh tag counts after async knowledge deletion completes Add a second delayed tag list refresh (2.5s) after tag deletion to capture updated reference counts for remaining tags. The original immediate refresh handles removing the deleted tag from the list, while this delayed refresh ensures other tags' counts are correct after the async deletion finishes. --------- Co-authored-by: lyingbug <xiayula2014@gmail.com>
2026-06-25 16:18:48 +00:00
secutils.SanitizeForLog(strings.Join(filter.TagIDs, ",")),
feat(knowledge-base): document list filters and explicit batch-management UX Add three new optional filters to the document list under a knowledge base detail page — parse status, source/channel, and updated time range — and rework multi-select to no longer cause the card title to jitter on hover. Backend - Introduce types.KnowledgeListFilter to aggregate optional filter dimensions (tag, keyword, file_type, parse_status, source, updated_from/to) and switch ListPagedKnowledgeByKnowledgeBaseID (repository/service/interface) to accept it instead of a growing positional parameter list. - The ListKnowledge HTTP handler accepts new parse_status, source, start_time and end_time query params; time params accept RFC3339, "YYYY-MM-DD HH:MM:SS" and "YYYY-MM-DD". The repository routes source="manual"/"url" onto the type column to stay consistent with file_type semantics; other source values match the channel column. - Update the four other callers (agent_service, initialization) to pass an empty filter struct, preserving prior behavior. Frontend - Add three controls in the doc-filter-bar (status select, source select, date-range picker with future-date disabled) wired through getKnowled / listKnowledgeFiles into the new backend params. - Replace the hover-triggered card checkbox with an explicit "批量管理" mode (mirrors the session list UX): in card view the checkbox only renders while batch mode is on, entered via the per-card "..." menu; the list view keeps its leading checkbox column. Switching from list to grid auto-enables batch mode when something is already selected, so the selection stays visible. - DocumentBatchBar now stays open whenever batch mode or selection > 0, and its "取消选择" button both clears the selection and exits batch mode. API surface sync - Regenerate Swagger artifacts (docs/docs.go / swagger.json / swagger.yaml). - Update docs/api/knowledge.md with the new query parameters. - Add backward-compatible ListKnowledgeWithFilter + KnowledgeListFilter to the Go SDK; the existing ListKnowledge keeps its signature. i18n - New filter labels in zh-CN / en-US / ko-KR / ru-RU; reuse existing menu.batchManage / batchManage.cancel for the multi-select strings.
2026-05-12 10:16:34 +00:00
secutils.SanitizeForLog(filter.Keyword),
secutils.SanitizeForLog(filter.FileType),
secutils.SanitizeForLog(filter.ParseStatus),
secutils.SanitizeForLog(filter.Source),
secutils.SanitizeForLog(c.Query("start_time")),
secutils.SanitizeForLog(c.Query("end_time")),
secutils.SanitizeForLog(filter.FolderPath),
string(filter.FolderScope),
string(filter.SortBy),
string(filter.SortOrder),
pagination.Page,
pagination.PageSize,
effectiveTenantID,
)
2025-08-05 07:08:07 +00:00
// Retrieve paginated knowledge entries
feat(knowledge-base): document list filters and explicit batch-management UX Add three new optional filters to the document list under a knowledge base detail page — parse status, source/channel, and updated time range — and rework multi-select to no longer cause the card title to jitter on hover. Backend - Introduce types.KnowledgeListFilter to aggregate optional filter dimensions (tag, keyword, file_type, parse_status, source, updated_from/to) and switch ListPagedKnowledgeByKnowledgeBaseID (repository/service/interface) to accept it instead of a growing positional parameter list. - The ListKnowledge HTTP handler accepts new parse_status, source, start_time and end_time query params; time params accept RFC3339, "YYYY-MM-DD HH:MM:SS" and "YYYY-MM-DD". The repository routes source="manual"/"url" onto the type column to stay consistent with file_type semantics; other source values match the channel column. - Update the four other callers (agent_service, initialization) to pass an empty filter struct, preserving prior behavior. Frontend - Add three controls in the doc-filter-bar (status select, source select, date-range picker with future-date disabled) wired through getKnowled / listKnowledgeFiles into the new backend params. - Replace the hover-triggered card checkbox with an explicit "批量管理" mode (mirrors the session list UX): in card view the checkbox only renders while batch mode is on, entered via the per-card "..." menu; the list view keeps its leading checkbox column. Switching from list to grid auto-enables batch mode when something is already selected, so the selection stays visible. - DocumentBatchBar now stays open whenever batch mode or selection > 0, and its "取消选择" button both clears the selection and exits batch mode. API surface sync - Regenerate Swagger artifacts (docs/docs.go / swagger.json / swagger.yaml). - Update docs/api/knowledge.md with the new query parameters. - Add backward-compatible ListKnowledgeWithFilter + KnowledgeListFilter to the Go SDK; the existing ListKnowledge keeps its signature. i18n - New filter labels in zh-CN / en-US / ko-KR / ru-RU; reuse existing menu.batchManage / batchManage.cancel for the multi-select strings.
2026-05-12 10:16:34 +00:00
result, err := h.kgService.ListPagedKnowledgeByKnowledgeBaseID(ctx, kbID, &pagination, filter)
2025-08-05 07:08:07 +00:00
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
logger.Infof(
ctx,
"Knowledge list retrieved successfully, knowledge base ID: %s, total: %d",
secutils.SanitizeForLog(kbID),
result.Total,
)
2025-08-05 07:08:07 +00:00
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": result.Data,
"total": result.Total,
"page": result.Page,
"page_size": result.PageSize,
})
}
feat(gallery): add an image gallery tab with schema-driven filters (#3694) * feat(image): observe image attributes and let the policy decide OCR Describe each image with the VLM as before, but ask it to also observe two attributes about the image in the same round — how much body text it carries (contain.text) and whether it presents data visually (contain.data_visual) — then let a small pure function decide whether that image is worth a second, separate OCR round. Per-class OCR was the first shape of this idea; a class (chart / photo / logo) is only an indirect proxy for 'is there text worth reading here', and the class table has to grow whenever a new kind of image shows up. The decision actually needs the observed attributes, so it reads them directly, and the attribute set is a backend registry row rather than a new class. The observation and the caption share one VLM call; OCR stays a separate call (prompt isolation, see #3291). An attribute the model does not answer for is left absent rather than filled with a conservative default, so the trace never claims an observation that did not happen, and an incomplete observation falls back to the on_unobserved policy (OCR still runs). The registry also carries the panel's display text, so a new attribute needs no frontend change. Off by default: image_attrs_enabled=false keeps today's behaviour (one caption and one OCR per image). KB config: image_processing_config.image_attrs_enabled / image_actions; per-upload override via process_config. Registry: GET /api/v1/image-attrs/schema. * feat(gallery): add image gallery tab with schema-driven filters Adds a 4th knowledge-base tab parallel to Documents/Wiki/Graph that browses every image asset in a KB. Backend: - GET /api/v1/knowledge-bases/:id/images lists image assets projected from chunks.image_info, with keyword (caption/OCR), multi-value attribute (attr_<name>=<value>), is_enabled and sort filters applied in memory, plus pagination. - Resolves the source knowledge item title (SourceName) via a batched GetKnowledgeBatch so the viewer can show a human-readable source. Frontend: - ImageGallery.vue: thumbnail grid + search/sort + schema-driven filter panel (from GET /image-attrs/schema) + single-image viewer with prev/next, attributes/caption/OCR/source. - Wired as the gallery tab in KnowledgeBase.vue; i18n keys in all 5 locales. * feat(gallery): drive filters/search/sort from a configurable attribute contract The gallery UI is no longer hardcoded: it renders from a self-describing contract served by GET /knowledge-bases/:id/gallery-config (live attribute sources, every attribute's definition with usage flags merged across the config tiers, and the caller's search activation state). - Attribute sources form an open registry (types.RegisterGalleryAttrSource); a builtin source models caption/ocr_text/timestamps/enabled so the gallery has zero special cases. - Usage resolution: user > KB > system > source, field by field; the system tier lives in system_settings (gallery.policy, JSON, no rebuild), the KB tier slot is wired in the engine but not stored yet. - Search activation is the user's own record: mode (all|custom) plus per-field on/off in users.preferences.gallery; source declarations never set defaults (unrecorded = off in custom mode). - image_info is read through a gallery-local struct, removing the compile dependency on the attribute-pipeline types; the gallery builds and runs with or without that feature deployed. - ListImages validates search_in / sort_by / attr_filters against the contract; ineligible fields are dropped, not served. * fix(frontend): inline the shared graph-drawer stylesheet (@import instead of <style src>) plugin-vue 6.0.6 keys unscoped src-style descriptors by the imported file path, so AgentStreamDisplay.vue and WikiBrowser.vue — both importing components/css/wiki-graph-drawer.less — overwrite each other during the build and the second one crashes with "reading 'scoped'". Adding the gallery changed the module order enough to make the collision hit every time. Inlining the same stylesheet keeps the emitted CSS identical and removes the shared descriptor key. * feat(gallery): render attributes from short labels with descriptions in tooltips A source could only say one thing about a value, so the filter panel had to put a full sentence inside a checkbox. Attributes and their values now carry two pieces of text: a short label for the space-constrained controls (checkbox, search field, sort option) and a description for wherever there is room (tooltip, detail panel). The contract's value list becomes an array of {value, label, description}, and the display helpers resolve each field separately: the gallery stamps the short name on a control and moves the sentence into a tooltip. Translation overlays are looked up per field, so a source that ships no gallery-specific text still picks up the attribute pipeline's own wording. * fix(gallery): let locale text win over the contract's wording The filter panel read the backend's own label before asking the locale, so a translated value never got a chance: the contract ships its own default-language wording, and it shadowed the overlay for every locale. Built keys were also off by a segment — imageAttr.<name> has to be imageAttr.<name>.label, and the gallery's own keys live under knowledgeEditor.wikiBrowser.gallery.attr — so builtin and system attributes fell through to English on a Chinese UI. * feat(gallery): top bar layout, pinned panels and per-value verdicts The toolbar moves onto its own row above the grid, so the controls no longer eat into the space the images are there for: search box, the two scope switches, sort field and direction, and the result count all sit in one flex row. The settings behind them are no longer inline either — each opens as a popover under its control and can be pinned to a right-hand rail, where the two panels take turns as tabs instead of both claiming width at once. Filtering gains a third state per attribute value. Where a value could only be picked or not picked, it can now be "off" (hide those images), "on" (show them whatever else says) or neutral (leave them alone), which is what lets one attribute's rules talk about an image another attribute tried to hide without the pair of them cancelling each other out: a forced display outranks a forced hide, and anything no rule speaks about stays visible. The switch that used to only exist inside the panel now has a toolbar home as well. "筛选:全显示" genuinely drops the attribute constraint instead of imposing it against a panel the user cannot see. Filtering used to empty the list the moment it was switched on. Any image whose attribute was never observed — every image ingested before the attribute pipeline existed — read as a mismatch for every filter, which is not narrowing a list but losing it. Absence now stays silence: an attribute no image carries places no constraint on it, until the pipeline catches up and fills the value in. Co-authored-by: WorkBuddy * feat(gallery): expose the image attribute pipeline as a gallery source The gallery's contract resolved to a single source, so the filter panel could only offer "Enabled" while the attributes the observe-and-describe pipeline fills in — contain.text, contain.data_visual — never reached the UI. The registry is a gallery attribute source like any other: every attribute it declares is offered to the gallery, filterable by default, with the config tiers able to override the usage flags at runtime. The registration lives in the attribute pipeline's own commit; this branch carried an earlier, squapshot of that work which predated the split of an attribute value into a short label and a description, so the registry's value shape and this file have been brought in line with it. Both PRs now hold byte-identical copies of the source hook, which is what lets either one land first and the other merge cleanly afterwards. Co-authored-by: WorkBuddy * fix(gallery): viewer race, pin icon, panel anchoring and scope wording Opening the viewer rendered the img element with the previous or empty source while the proxy fetch was still producing a blob, and the error that empty source fired locked the viewer in its failure state even after the real image arrived. The resolved source now lands before the flag is consulted, and a token keeps a slow fetch of one image from overwriting a faster one that navigated past it. The pin button drew nothing: TDesign has no "pushpin" glyph, so the button rendered as an empty shell. It now uses pin / pin-filled, keeps its place beside the tab bar, and a pinned rail assigns its columns explicitly — the panel precedes the main section in the DOM, so leaving the grid to source order handed the wide column to the panel and squeezed the images into the rail. The floating panel no longer appears at a hardcoded offset: it anchors just below the arrow that summoned it, the arrow flips up while its panel is out, a second press retracts, and any click elsewhere in the toolbar closes it. When a rail is pinned the arrows turn to the requested tab instead of spawning a second surface. The scope words (全部 / 全显示 / 自定义) become plain status text rather than a second dropdown — they name the current mode, and only the arrow beside them opens the panel that changes it. Co-authored-by: WorkBuddy * fix(web): align the OCR-on-unobserved switch with the other setting rows The switch sat bare inside its setting-row while every other switch on the page is wrapped in setting-control, which is what reserves the right column and centers the control vertically. With the row laid out from the top, the bare switch hugged the row's upper edge and crowded the description text — visibly out of place next to its neighbors. Wrapping it in setting-control gives it the same right-aligned, centered slot as the rest. Co-authored-by: WorkBuddy * fix(web): move the OCR-on-unobserved row out of the vertical schema row The row lived inside setting-row-vertical, whose descendant rule stretches every setting-info and setting-control beneath it to 100% width. Two full-width flex children side by side cannot fit, so the control overflowed the container and the switch landed past the right edge — visibly further out than the switch on the row above. The row and its note now sit beside the vertical block instead of inside it, under their own condition, so the switch shares the ordinary row layout and its right edge lines up with the "image attribute observation" switch above. Co-authored-by: WorkBuddy * fix(gallery): applying a verdict now activates the filter scope Setting an off/on verdict while the panel's master switch was off silently ignored it: buildParams only attaches attr_rules in custom scope, and setVerdict never flipped the scope. A verdict the user just expressed now switches the scope to custom; clearing the last meaningful verdict returns to all, since custom with no rules constrains nothing. * fix(gallery): search checkboxes stay visible and idle panels read as dimmed The search panel hid its field checkboxes while the master switch was on, so the only way to reach them was to flip the switch first. They now sit next to the switch like the filter panel's verdicts do: dimmed in all-field mode (where they carry no weight) yet clickable, and touching one drops the mode to custom. The filter panel's verdict rows dim the same way while the filter switch is off. * fix(gallery): bulk verdict row, neutral default mark, panel polish The clear-filters button never matched what the panel is for, so it is now a bulk verdict row: one set of -/off/on buttons that applies the chosen position to every value of every value-typed attribute, with the default mark turned into a language-neutral dash. The panel head drops its second divider (the tab bar already draws one) and the tabs follow the toolbar's order: search left, filter right. * fix(gallery): drop the all-fields caption and center the order arrow The caption above the search checkboxes showed and hid with the master switch, shoving the checkboxes down on every flip; it said nothing the dimmed state doesn't, so it is gone. The order button's arrow is an inline svg, which sits on the text baseline and reads as riding high; it now centers against the label. * fix(gallery): center the order arrow for real vertical-align never applied: the icon is a flex item inside the button's inline-flex text wrapper, and the wrapper's default stretch pins the explicitly-sized 16px icon to the top of the 22px line box. align-items: center on the wrapper is what actually centers it. * fix(gallery): shorten panel tab labels in en and ru The two-word labels overflowed the 300px panel and forced the tab bar into scroll arrows; single-word labels fit in every locale that was affected. * docs: drop the image pipeline rewrite from this branch The rewritten 'Go 侧接手后' paragraph belongs to the image attribute observation work (#3635), which this branch carries as a prerequisite and which already documents the caption_ocr / observation_driven split. Keeping a competing rewrite of the same paragraph on the gallery branch makes it collide with upstream, which extended that paragraph with the custom_instructions and inline HTML table notes. Restoring the shared wording keeps the gallery branch free of this file so upstream's edits merge cleanly. * style: gofmt the gallery attribute types Struct field tags in the resolved gallery config were one column narrow, so gofmt rebroke the alignment block. Whitespace only. * style(gallery): use design tokens in the gallery styles The style guard ratchet fails on any new violation. ImageGallery.vue shipped with 47 TDesign token fallbacks, 21 literal font sizes, 4 literal radii and a 0.15s transition; all of them now read the --app-* / --td-* tokens, which is what the guard asks for and what dark mode depends on. * lint(gallery): fix the golangci-lint findings in the gallery code lll: the three over-long swagger @Param lines and one registry row were shortened. ineffassign: ctx was assigned before the access check and then reassigned, so the first value was dead; it is now declared once, after the check. errcheck: the three unchecked c.Error calls in ListImages. revive: the AttrSpec / AttrValue doc comment block was attached to the wrong type and split into one block each. staticcheck S1016: the gallery registration converts the registry value instead of restating its fields. * lint(gallery): wrap the image query select and check the last c.Error * style: reformat the wrapped image select in chunk.go * fix(gallery): address review findings on ordering, KB switch and blob lifetime - sortImageAssets: swap operands for desc instead of negating, keeping a strict weak ordering so ties page stably - ImageGallery: reload on knowledgeBaseId change, drop stale list responses, fetch thumbnails in parallel with one cached blob per URL, revoke blobs on unmount, default sort to builtin:created_at - KnowledgeBase: non-wiki KBs with a stale wiki/graph tab fall back to documents again - handler: move ListImages godoc out of ListKnowledgeFolders' block and document attr_filters / attr_rules - DecideOCR: a payload with no OCR conditions uses the built-in policy instead of silently skipping OCR * docs(parsing): describe the caption_ocr and observation_driven image pipelines Carried over from #3635, which this PR supersedes. * fix(gallery): load local:// and other storage handles through the KB file proxy The gallery's own scheme check only caught resource://, provider:// and storage://, so local:// (the default storage), minio://, cos:// and s3:// images went straight into <img src> and never rendered. Resolve through isProviderFileURL, the scheme list chat and wiki already use, and lock the routing with a test. * fix(kb-editor): keep API-customised OCR conditions on save and upload The KB editor always wrote the registry default into image_actions.ocr.on, so any unrelated edit replaced a knowledge base's custom OCR conditions with the default table; the upload dialog did the same for the per-document override. Keep a stored custom list and fall back to the registry default only when there is none, and show the conditions actually in effect instead of the default table in both panels. * perf(gallery): de-duplicate, filter, sort and page images in SQL Every gallery request used to read every image-bearing chunk of the KB, OCR text included, decode it in Go and page in memory. A single query now expands the image_info arrays, keeps one row per image URL, applies the keyword / attribute / verdict / enabled filters and the sort, and returns only the page with the filtered total. The expansion carries narrow scalars only; filters and JSON sort keys are evaluated on the winning entry of each image, and the page's JSON is read back for its rows alone. Postgres runs the query with JIT off, since the fixed 100-rows-per-call estimate of jsonb_array_elements otherwise prices it ~100x high and compilation dominates. On 20k images with 2 KB of OCR text each (40k chunks), a page drops from ~750 ms to ~100-200 ms on postgres and ~200 ms on sqlite; keyword search over OCR text stays a full scan (~400-600 ms) until the text is indexed. The filter semantics are pinned against both databases. * perf(gallery): serve the gallery from a trigger-maintained chunk_images table Reading images out of chunks.image_info meant parsing every image chunk of the knowledge base on each request, so a page still cost time in proportion to the KB. chunk_images (versioned/000113, sqlite/000032) keeps one row per image_info entry with caption, OCR text and attributes as columns; triggers on chunks keep it in step with every write path, and the migration backfills existing chunks. Copies of one image stay separate rows and the query lists the copy on the most recently updated chunk through an indexed anti-join, so writes decide nothing and concurrent writers need no locking. On postgres, caption and OCR text get pg_trgm indexes when the extension is available. On 20k images with 2 KB of OCR text each (40k chunks): postgres first page 10 ms, page 500 41 ms, keyword 2 ms, filters 23 ms sqlite first page 3 ms, page 500 39 ms, keyword 147 ms, filters 51 ms down from ~100-600 ms. Writing those 40k image chunks costs 7.0 s instead of 1.3 s on postgres (1.9 s instead of 1.0 s on sqlite), mostly the trigram indexes; status and enable-flag updates patch rows in place. --------- Co-authored-by: tayadwx <tayadwx@users.noreply.github.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-25 04:33:59 +00:00
// ListImages lists the image assets of a knowledge base for the gallery view.
//
// @Summary 列出知识库图片资产
// @Description 浏览某知识库内的全部图片资产,支持关键字搜索(caption/OCR 文本)、按图片属性筛选(attr_filters / attr_rules)与排序分页。
// @Tags knowledge
// @Accept json
// @Produce json
// @Param id path string true "知识库 ID"
// @Param page query int false "页码,默认 1"
// @Param page_size query int false "每页数量,默认 20,最大 1000"
// @Param keyword query string false "关键字,对 search_in 指定字段做不区分大小写的子串匹配"
// @Param search_in query string false "参与搜索的属性 ID(逗号分隔);须为 in_searchfield=true"
// @Param sort_by query string false "排序属性 ID;须为 in_sortfield=true,默认 created_at"
// @Param sort_order query string false "排序方向:asc / desc,默认 desc"
// @Param is_enabled query bool false "仅包含启用状态的图片"
// @Param attr_filters query string false "属性筛选 JSON,同一属性多值 OR、属性间 AND"
// @Param attr_rules query string false "属性逐值裁决 JSON(off 隐藏 / on 强制显示,on 优先)"
// @Success 200 {object} map[string]interface{} "图片资产分页列表"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge-bases/{id}/images [get]
func (h *KnowledgeHandler) ListImages(c *gin.Context) {
_, kbID, effectiveTenantID, _, err := h.validateKnowledgeBaseAccess(c)
if err != nil {
_ = c.Error(err)
return
}
ctx := types.WithExecutionTenant(c.Request.Context(), effectiveTenantID)
var pagination types.Pagination
if err := c.ShouldBindQuery(&pagination); err != nil {
logger.Error(ctx, "Failed to parse pagination parameters", err)
_ = c.Error(errors.NewBadRequestError(err.Error()))
return
}
filter := &types.ImageListFilter{
Keyword: strings.TrimSpace(c.Query("keyword")),
SortBy: strings.TrimSpace(c.Query("sort_by")),
SortOrder: c.DefaultQuery("sort_order", "desc"),
}
if v := c.Query("is_enabled"); v != "" {
enabled := v == "true"
filter.IsEnabled = &enabled
}
// Every gallery attribute reference is validated against the resolved
// contract: a client may only search / sort / filter on fields whose
// usage flags allow it, so stale or hand-rolled callers cannot smuggle
// in fields the configuration no longer serves.
resolved := h.resolveGalleryConfig(ctx, kbID)
filterable, searchable, sortable := galleryEligibility(resolved)
// Attribute filters arrive as one JSON object keyed by namespaced
// attribute id ({"system:contain.text":["block"]}); values within one
// attribute are OR-ed, attributes are AND-ed.
if raw := c.Query("attr_filters"); raw != "" {
var attrFilters map[string][]string
if err := json.Unmarshal([]byte(raw), &attrFilters); err == nil && len(attrFilters) > 0 {
kept := make(map[string][]string, len(attrFilters))
for id, values := range attrFilters {
if filterable[id] && len(values) > 0 {
kept[id] = values
}
}
if len(kept) > 0 {
filter.AttrFilters = kept
}
}
}
// Attribute rules arrive as one JSON object keyed by namespaced
// attribute id, each holding a verdict per value
// ({"system:contain.text":{"block":"on","none":"off"}}). Only values
// the image actually carries take part; see AttrRules for the
// precedence between "on" and "off".
if raw := c.Query("attr_rules"); raw != "" {
var attrRules map[string]map[string]string
if err := json.Unmarshal([]byte(raw), &attrRules); err == nil && len(attrRules) > 0 {
kept := make(map[string]map[string]string, len(attrRules))
for id, verdicts := range attrRules {
if !filterable[id] || len(verdicts) == 0 {
continue
}
clean := make(map[string]string, len(verdicts))
for value, verdict := range verdicts {
switch verdict {
case "off", "on":
clean[value] = verdict
}
}
if len(clean) > 0 {
kept[id] = clean
}
}
if len(kept) > 0 {
filter.AttrRules = kept
}
}
}
// search_in: comma-separated namespaced attribute ids; ineligible ids
// are dropped, and an empty remainder falls back to the service default
// (builtin caption + ocr_text).
if raw := strings.TrimSpace(c.Query("search_in")); raw != "" {
var searchIn []string
for _, id := range strings.Split(raw, ",") {
id = strings.TrimSpace(id)
if id != "" && searchable[id] {
searchIn = append(searchIn, id)
}
}
filter.SearchIn = searchIn
}
// sort_by must be sort-eligible; anything else falls back to the
// service default (builtin created_at, descending).
if filter.SortBy != "" && !sortable[filter.SortBy] {
filter.SortBy = ""
}
result, err := h.chunkService.ListImagesByKnowledgeBaseID(ctx, kbID, &pagination, filter)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{"kb_id": kbID})
_ = c.Error(errors.NewInternalServerError(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": result.Data,
"total": result.Total,
"page": result.Page,
"page_size": result.PageSize,
})
}
// galleryEligibility extracts the per-attribute usage sets that incoming
// query parameters are validated against, keyed by namespaced attribute id.
func galleryEligibility(resolved *types.GalleryResolvedConfig) (filterable, searchable, sortable map[string]bool) {
filterable = map[string]bool{}
searchable = map[string]bool{}
sortable = map[string]bool{}
if resolved == nil {
return
}
for _, attr := range resolved.Attributes {
if attr.Usage.InFilter {
filterable[attr.ID] = true
}
if attr.Usage.InSearchField {
searchable[attr.ID] = true
}
if attr.Usage.InSortField {
sortable[attr.ID] = true
}
}
return
}
// resolveGalleryConfig merges the gallery configuration tiers for one
// request: the system tier from system_settings ("gallery.policy"), the user
// tier from the caller's saved preferences. The KB tier slot is reserved for
// the per-KB config (not wired yet — the merge engine already accepts it).
// A missing or malformed tier degrades to "no overrides", never to an error:
// the gallery must render even on a half-configured deployment.
func (h *KnowledgeHandler) resolveGalleryConfig(ctx context.Context, kbID string) *types.GalleryResolvedConfig {
var systemTier *types.GalleryPolicyTier
if h.systemSettingSvc != nil {
if row, err := h.systemSettingSvc.Get(ctx, "gallery.policy"); err == nil && row != nil {
if raw, err := row.AsString(); err == nil && strings.TrimSpace(raw) != "" {
tier := &types.GalleryPolicyTier{}
if err := json.Unmarshal([]byte(raw), tier); err == nil {
systemTier = tier
} else {
logger.Warnf(ctx, "gallery.policy is not valid JSON; ignoring: %v", err)
}
}
}
}
var userTier *types.GalleryPolicyTier
if h.userSvc != nil {
if userID, ok := types.UserIDFromContext(ctx); ok && userID != "" {
if u, err := h.userSvc.GetUserByID(ctx, userID); err == nil && u != nil && u.Preferences.Gallery != nil {
g := u.Preferences.Gallery
userTier = &types.GalleryPolicyTier{Mode: g.Mode, Status: g.Status}
}
}
}
return types.ResolveGalleryConfig(kbID, systemTier, nil, userTier)
}
// GetGalleryConfig serves the gallery's self-describing contract: which
// attribute sources are live, every resolved attribute (definition + merged
// usage + which tier decided it), and the caller's search activation state
// (mode + per-field status). The frontend renders its filter panel, search
// field checkboxes and sort dropdown purely from this response — no gallery
// UI rule is hardcoded client-side.
func (h *KnowledgeHandler) GetGalleryConfig(c *gin.Context) {
ctx := c.Request.Context()
_, kbID, effectiveTenantID, _, err := h.validateKnowledgeBaseAccess(c)
if err != nil {
_ = c.Error(err)
return
}
ctx = types.WithExecutionTenant(ctx, effectiveTenantID)
resolved := h.resolveGalleryConfig(ctx, kbID)
status := resolved.Status
if status == nil {
status = map[string]string{}
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"attribute_sources": resolved.AttributeSources,
"attributes": resolved.Attributes,
"mode": resolved.Mode,
"status": status,
},
})
}
// ListKnowledgeFolders godoc
// @Summary 获取知识库文件夹目录树
// @Description 返回知识库内由文件夹上传形成的目录树,包含每个文件夹的直接文档数与含子目录的总数
// @Tags 知识管理
// @Accept json
// @Produce json
// @Param id path string true "知识库ID"
// @Success 200 {object} map[string]interface{} "目录树"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge-bases/{id}/knowledge/folders [get]
func (h *KnowledgeHandler) ListKnowledgeFolders(c *gin.Context) {
ctx := c.Request.Context()
// Read access mirrors ListKnowledge so the sidebar tree is available to
// every viewer of a shared knowledge base.
_, kbID, effectiveTenantID, _, err := h.validateKnowledgeBaseAccess(c)
if err != nil {
c.Error(err)
return
}
ctx = types.WithExecutionTenant(c.Request.Context(), effectiveTenantID)
tree, err := h.kgService.ListKnowledgeFolderTree(ctx, kbID)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
logger.Infof(ctx, "Knowledge folder tree retrieved, kb_id=%s folders=%d",
secutils.SanitizeForLog(kbID), len(tree.Folders))
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": tree,
})
}
// MoveKnowledgeToFolderRequest is the body schema for POST /knowledge/folder.
type MoveKnowledgeToFolderRequest struct {
KBID string `json:"kb_id" binding:"required"`
IDs []string `json:"knowledge_ids" binding:"required"`
// FolderPath is the destination folder; the empty string is the knowledge
// base top level. It is deliberately not `binding:"required"` so documents
// can be moved back out of every folder.
FolderPath string `json:"folder_path"`
}
// MoveKnowledgeToFolder godoc
// @Summary 移动知识到文件夹
// @Description 批量修改知识条目所属文件夹。文件夹由路径推导而来,因此目标路径不存在时会自动创建;空路径表示知识库顶层。仅调整归类,不会重新解析文档
// @Tags 知识管理
// @Accept json
// @Produce json
// @Param request body MoveKnowledgeToFolderRequest true "移动请求"
// @Success 200 {object} map[string]interface{} "移动成功"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 403 {object} errors.AppError "权限不足"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge/folder [post]
func (h *KnowledgeHandler) MoveKnowledgeToFolder(c *gin.Context) {
ctx := c.Request.Context()
var req MoveKnowledgeToFolderRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(errors.NewBadRequestError("Invalid request parameters: " + err.Error()))
return
}
ids := dedupeKnowledgeIDs(req.IDs)
if len(ids) == 0 {
c.Error(errors.NewBadRequestError("knowledge_ids cannot be empty"))
return
}
const maxBatch = 200
if len(ids) > maxBatch {
c.Error(errors.NewBadRequestError(fmt.Sprintf("too many ids (max %d per batch)", maxBatch)))
return
}
kbID, effectiveTenantID, err := h.requireKnowledgeWriteAccess(c, req.KBID)
if err != nil {
c.Error(err)
return
}
ctx = types.WithExecutionTenant(c.Request.Context(), effectiveTenantID)
// Guard against cross-KB moves: the service layer scopes by tenant, so the
// handler must confirm every entry belongs to the requested knowledge base.
if err := h.requireKnowledgeInKB(ctx, effectiveTenantID, kbID, ids); err != nil {
c.Error(err)
return
}
affected, err := h.kgService.MoveKnowledgeToFolder(ctx, kbID, ids, req.FolderPath)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
c.Error(appErr)
return
}
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"moved_count": affected,
"folder_path": types.NormalizeKnowledgeFolderPath(req.FolderPath),
},
})
}
// RenameKnowledgeFolderRequest is the body schema for
// PUT /knowledge-bases/:id/knowledge/folders.
type RenameKnowledgeFolderRequest struct {
From string `json:"from" binding:"required"`
To string `json:"to" binding:"required"`
}
// RenameKnowledgeFolder godoc
// @Summary 重命名或移动文件夹
// @Description 把一个文件夹及其所有子目录改到新路径。目标路径已存在时两个文件夹合并;不能移动到自身子目录下
// @Tags 知识管理
// @Accept json
// @Produce json
// @Param id path string true "知识库ID"
// @Param request body RenameKnowledgeFolderRequest true "重命名请求"
// @Success 200 {object} map[string]interface{} "重命名成功"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 403 {object} errors.AppError "权限不足"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge-bases/{id}/knowledge/folders [put]
func (h *KnowledgeHandler) RenameKnowledgeFolder(c *gin.Context) {
ctx := c.Request.Context()
var req RenameKnowledgeFolderRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(errors.NewBadRequestError("Invalid request parameters: " + err.Error()))
return
}
_, kbID, effectiveTenantID, permission, err := h.validateKnowledgeBaseWriteAccessWithKBID(c, c.Param("id"))
if err != nil {
c.Error(err)
return
}
if permission != types.OrgRoleAdmin && permission != types.OrgRoleEditor {
c.Error(errors.NewForbiddenError("No permission to modify knowledge"))
return
}
if err := h.requireKBOwnershipOrAdmin(c, kbID); err != nil {
c.Error(err)
return
}
ctx = types.WithExecutionTenant(c.Request.Context(), effectiveTenantID)
affected, err := h.kgService.RenameKnowledgeFolder(ctx, kbID, req.From, req.To)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
c.Error(appErr)
return
}
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"moved_count": affected,
"folder_path": types.NormalizeKnowledgeFolderPath(req.To),
},
})
}
// dedupeKnowledgeIDs trims, drops empty and de-duplicates a batch of IDs while
// preserving the caller's order.
func dedupeKnowledgeIDs(raw []string) []string {
seen := make(map[string]struct{}, len(raw))
ids := make([]string, 0, len(raw))
for _, item := range raw {
id := strings.TrimSpace(item)
if id == "" {
continue
}
if _, ok := seen[id]; ok {
continue
}
seen[id] = struct{}{}
ids = append(ids, id)
}
return ids
}
// requireKnowledgeWriteAccess resolves a knowledge base from a request body and
// enforces the editor-or-admin plus ownership gate shared by the batch routes.
func (h *KnowledgeHandler) requireKnowledgeWriteAccess(
c *gin.Context,
requestedKBID string,
) (string, uint64, error) {
_, kbID, effectiveTenantID, permission, err := h.validateKnowledgeBaseWriteAccessWithKBID(c, requestedKBID)
if err != nil {
return "", 0, err
}
if permission != types.OrgRoleAdmin && permission != types.OrgRoleEditor {
return "", 0, errors.NewForbiddenError("No permission to modify knowledge")
}
if err := h.requireKBOwnershipOrAdmin(c, kbID); err != nil {
return "", 0, err
}
return kbID, effectiveTenantID, nil
}
// requireKnowledgeInKB verifies every ID exists and belongs to the given
// knowledge base, so a batch operation cannot reach across knowledge bases.
func (h *KnowledgeHandler) requireKnowledgeInKB(
ctx context.Context,
tenantID uint64,
kbID string,
ids []string,
) error {
knowledgeList, err := h.kgService.GetKnowledgeBatch(ctx, tenantID, ids)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
return errors.NewInternalServerError(err.Error())
}
if len(knowledgeList) != len(ids) {
return errors.NewBadRequestError("One or more knowledge entries not found")
}
for _, k := range knowledgeList {
if k.KnowledgeBaseID != kbID {
return errors.NewBadRequestError(
fmt.Sprintf("Knowledge %s does not belong to knowledge base %s",
secutils.SanitizeForLog(k.ID), secutils.SanitizeForLog(kbID)))
}
}
return nil
}
// DeleteKnowledge godoc
// @Summary 删除知识
// @Description 根据ID异步删除知识条目。请求会被入队到与批量删除相同的异步管道(asynq);
// @Description 接口返回 200 仅表示任务已提交(响应 data.task_id 为任务 ID),实际删除由后台 worker 完成。
// @Tags 知识管理
// @Accept json
// @Produce json
// @Param id path string true "知识ID"
// @Success 200 {object} map[string]interface{} "任务已提交,返回 task_id"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge/{id} [delete]
2025-08-05 07:08:07 +00:00
func (h *KnowledgeHandler) DeleteKnowledge(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start deleting knowledge")
id := secutils.SanitizeForLog(c.Param("id"))
2025-08-05 07:08:07 +00:00
if id == "" {
logger.Error(ctx, "Knowledge ID is empty")
c.Error(errors.NewBadRequestError("Knowledge ID cannot be empty"))
return
}
knowledge, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, id, types.OrgRoleEditor)
if err != nil {
c.Error(err)
return
}
if err := access.RejectMovingKnowledge(knowledge); err != nil {
_ = c.Error(err)
return
}
// Reuse the batch async pipeline so single-item delete shares the same
// hardening (asynq retries, business-aware queue routing, marking-as-deleting
// inside the worker) as BatchDeleteKnowledge / ClearKnowledgeBaseContents.
effectiveTenantID, _ := effCtx.Value(types.TenantIDContextKey).(uint64)
if effectiveTenantID == 0 {
logger.Error(ctx, "Effective tenant ID missing after access validation")
c.Error(errors.NewInternalServerError("workspace context unavailable"))
return
}
logger.Infof(ctx, "Enqueuing knowledge delete, ID: %s", secutils.SanitizeForLog(id))
taskID, err := h.enqueueKnowledgeListDelete(effCtx, effectiveTenantID, knowledge.KnowledgeBaseID, []string{id})
2025-08-05 07:08:07 +00:00
if err != nil {
logger.Errorf(ctx, "Failed to enqueue knowledge delete task: %v", err)
c.Error(errors.NewInternalServerError("Failed to enqueue delete task"))
2025-08-05 07:08:07 +00:00
return
}
logger.Infof(ctx, "Knowledge delete task enqueued: %s, knowledge_id: %s", taskID, secutils.SanitizeForLog(id))
2025-08-05 07:08:07 +00:00
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "Delete task submitted",
"data": gin.H{
"task_id": taskID,
},
2025-08-05 07:08:07 +00:00
})
}
// BatchDeleteKnowledgeRequest is the body schema for POST /knowledge/batch-delete.
type BatchDeleteKnowledgeRequest struct {
KBID string `json:"kb_id" binding:"required"`
IDs []string `json:"ids" binding:"required"`
}
// BatchDeleteKnowledge godoc
// @Summary 批量删除知识
// @Description 按 ID 列表批量删除单个知识库下的多个知识条目
// @Tags 知识管理
// @Accept json
// @Produce json
// @Param request body BatchDeleteKnowledgeRequest true "批量删除请求"
// @Success 200 {object} map[string]interface{} "删除成功"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 403 {object} errors.AppError "权限不足"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge/batch-delete [post]
func (h *KnowledgeHandler) BatchDeleteKnowledge(c *gin.Context) {
ctx := c.Request.Context()
var req BatchDeleteKnowledgeRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(errors.NewBadRequestError("Invalid request parameters: " + err.Error()))
return
}
ids := dedupeKnowledgeIDs(req.IDs)
if len(ids) == 0 {
c.Error(errors.NewBadRequestError("ids cannot be empty"))
return
}
const maxBatch = 200
if len(ids) > maxBatch {
c.Error(errors.NewBadRequestError(fmt.Sprintf("too many ids (max %d per batch)", maxBatch)))
return
}
// Validate KB access (editor or admin) using the kb_id from body.
_, kbID, effectiveTenantID, permission, err := h.validateKnowledgeBaseWriteAccessWithKBID(c, req.KBID)
if err != nil {
c.Error(err)
return
}
if permission != types.OrgRoleAdmin && permission != types.OrgRoleEditor {
c.Error(errors.NewForbiddenError("No permission to delete knowledge"))
return
}
if err := h.requireKBOwnershipOrAdmin(c, kbID); err != nil {
c.Error(err)
return
}
ctx = types.WithExecutionTenant(c.Request.Context(), effectiveTenantID)
// Single batch fetch to validate that every id exists and belongs to the
// requested KB before admitting a task with that exact KB scope.
knowledgeList, err := h.kgService.GetKnowledgeBatch(ctx, effectiveTenantID, ids)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
if len(knowledgeList) != len(ids) {
c.Error(errors.NewBadRequestError("One or more knowledge entries not found"))
return
}
for _, k := range knowledgeList {
if err := access.RejectMovingKnowledge(k); err != nil {
_ = c.Error(err)
return
}
if k.KnowledgeBaseID != kbID {
c.Error(errors.NewBadRequestError(
fmt.Sprintf("Knowledge %s does not belong to knowledge base %s",
secutils.SanitizeForLog(k.ID), secutils.SanitizeForLog(kbID))))
return
}
}
taskID, err := h.enqueueKnowledgeListDelete(ctx, effectiveTenantID, kbID, ids)
if err != nil {
logger.Errorf(ctx, "Failed to enqueue batch knowledge delete task: %v", err)
c.Error(errors.NewInternalServerError("Failed to enqueue batch delete task"))
return
}
logger.Infof(ctx, "Batch knowledge delete task enqueued: %s, kb_id: %s, count: %d",
taskID, secutils.SanitizeForLog(kbID), len(ids))
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "Batch delete task submitted",
"data": gin.H{
"task_id": taskID,
"deleted_count": len(ids),
},
})
}
// ClearKnowledgeBaseContents godoc
// @Summary 清空知识库内容
// @Description 删除知识库下的所有知识条目(异步任务)。知识库本身保留,仅清空其中的内容
// @Tags 知识管理
// @Accept json
// @Produce json
// @Param id path string true "知识库ID"
// @Success 200 {object} map[string]interface{} "清空任务已提交"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 403 {object} errors.AppError "权限不足"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge-bases/{id}/knowledge [delete]
func (h *KnowledgeHandler) ClearKnowledgeBaseContents(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start clearing knowledge base contents")
kb, kbID, effectiveTenantID, permission, err := h.validateKnowledgeBaseWriteAccessWithKBID(c, c.Param("id"))
if err != nil {
c.Error(err)
return
}
// Only owner (admin with matching tenant) can clear knowledge base contents
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if kb.TenantID != tenantID || permission != types.OrgRoleAdmin {
c.Error(errors.NewForbiddenError("Only knowledge base owner can clear contents"))
return
}
ctx = types.WithExecutionTenant(c.Request.Context(), effectiveTenantID)
knowledgeList, err := h.kgService.ListKnowledgeByKnowledgeBaseID(ctx, kbID)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to list knowledge entries").WithDetails(err.Error()))
return
}
if len(knowledgeList) == 0 {
logger.Infof(ctx, "Knowledge base %s is already empty", secutils.SanitizeForLog(kbID))
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "Knowledge base is already empty",
"data": gin.H{"deleted_count": 0},
})
return
}
knowledgeIDs := make([]string, 0, len(knowledgeList))
for _, knowledge := range knowledgeList {
if err := access.RejectMovingKnowledge(knowledge); err != nil {
_ = c.Error(err)
return
}
knowledgeIDs = append(knowledgeIDs, knowledge.ID)
}
taskID, err := h.enqueueKnowledgeListDelete(ctx, effectiveTenantID, kbID, knowledgeIDs)
if err != nil {
logger.Errorf(ctx, "Failed to enqueue knowledge list delete task: %v", err)
c.Error(errors.NewInternalServerError("Failed to enqueue cleanup task"))
return
}
logger.Infof(ctx, "Knowledge base contents clear task enqueued: %s, kb_id: %s, count: %d",
taskID, secutils.SanitizeForLog(kbID), len(knowledgeIDs))
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "Knowledge base contents clear task submitted",
"data": gin.H{"deleted_count": len(knowledgeIDs)},
})
}
// DownloadKnowledgeFile godoc
// @Summary 下载知识文件
// @Description 下载知识条目关联的原始文件
// @Tags 知识管理
// @Accept json
// @Produce application/octet-stream
// @Param id path string true "知识ID"
// @Success 200 {file} file "文件内容"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge/{id}/download [get]
2025-08-05 07:08:07 +00:00
func (h *KnowledgeHandler) DownloadKnowledgeFile(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start downloading knowledge file")
id := secutils.SanitizeForLog(c.Param("id"))
2025-08-05 07:08:07 +00:00
if id == "" {
logger.Error(ctx, "Knowledge ID is empty")
c.Error(errors.NewBadRequestError("Knowledge ID cannot be empty"))
return
}
// Keep a handler-level Editor check in addition to the route guard. The
// original file is more sensitive than parsed-content reads and must not
// be downloadable through a read-only organization share.
_, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, id, types.OrgRoleEditor)
if err != nil {
c.Error(err)
return
}
logger.Infof(ctx, "Retrieving knowledge file, ID: %s", secutils.SanitizeForLog(id))
2025-08-05 07:08:07 +00:00
file, filename, err := h.kgService.GetKnowledgeFile(effCtx, id)
2025-08-05 07:08:07 +00:00
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to retrieve file").WithDetails(err.Error()))
return
}
c.Header("Content-Description", "File Transfer")
c.Header("Content-Transfer-Encoding", "binary")
c.Header("Expires", "0")
if err := filetransport.Serve(c.Writer, c.Request, file, filetransport.Options{
Filename: filename, Download: true, ContentType: "application/octet-stream", CacheControl: "private, no-store",
}); err != nil {
logger.Errorf(ctx, "Failed to send file: %v", err)
}
2025-08-05 07:08:07 +00:00
}
// PreviewKnowledgeFile godoc
// @Summary 预览知识文件
// @Description 返回知识条目关联的原始文件,Content-Type 根据文件类型设置,用于浏览器内嵌预览
// @Tags 知识管理
// @Accept json
// @Produce application/pdf,image/jpeg,image/png,text/plain
// @Param id path string true "知识ID"
// @Success 200 {file} file "文件内容"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge/{id}/preview [get]
func (h *KnowledgeHandler) PreviewKnowledgeFile(c *gin.Context) {
ctx := c.Request.Context()
id := secutils.SanitizeForLog(c.Param("id"))
if id == "" {
c.Error(errors.NewBadRequestError("Knowledge ID cannot be empty"))
return
}
_, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, id, types.OrgRoleViewer)
if err != nil {
c.Error(err)
return
}
file, filename, err := h.kgService.GetKnowledgeFile(effCtx, id)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to retrieve file").WithDetails(err.Error()))
return
}
if err := filetransport.Serve(c.Writer, c.Request, file, filetransport.Options{
Filename: filename, CacheControl: "private, no-store",
}); err != nil {
logger.Errorf(ctx, "Failed to stream preview: %v", err)
}
}
2025-08-05 07:08:07 +00:00
// GetKnowledgeBatchRequest defines parameters for batch knowledge retrieval
type GetKnowledgeBatchRequest struct {
IDs []string `form:"ids" binding:"required"` // List of knowledge IDs
KBID string `form:"kb_id"` // Optional: scope to this KB (validates access and uses effective tenant for shared KB)
AgentID string `form:"agent_id"` // Optional: when using a shared agent, use agent's tenant for retrieval (validates shared agent access)
AgentSourceTenantID uint64 `form:"agent_source_tenant_id"` // Optional source selector, verified against the share relation
2025-08-05 07:08:07 +00:00
}
// GetKnowledgeBatch godoc
// @Summary 批量获取知识
// @Description 根据ID列表批量获取知识条目。可选 kb_id:指定时按该知识库校验权限并用于共享知识库的空间解析;可选 agent_id:使用共享智能体时传此参数,后端按智能体所属空间查询(用于刷新后恢复共享知识库下的文件)
// @Tags 知识管理
// @Accept json
// @Produce json
// @Param ids query []string true "知识ID列表"
// @Param kb_id query string false "可选,知识库ID(用于共享知识库时指定范围)"
// @Param agent_id query string false "可选,共享智能体ID(用于按智能体空间批量拉取文件详情)"
// @Success 200 {object} map[string]interface{} "知识列表"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge/batch [get]
2025-08-05 07:08:07 +00:00
func (h *KnowledgeHandler) GetKnowledgeBatch(c *gin.Context) {
ctx := c.Request.Context()
effectiveTenantID := middleware.KBAccessRequest(c).Caller.TenantID
if effectiveTenantID == 0 {
2025-08-05 07:08:07 +00:00
c.Error(errors.NewUnauthorizedError("Unauthorized"))
return
}
var req GetKnowledgeBatchRequest
if err := c.ShouldBindQuery(&req); err != nil {
logger.Error(ctx, "Failed to parse request parameters", err)
c.Error(errors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
return
}
if _, parseErr := types.ParseAgentSourceTenantID(c.Query(types.AgentSourceTenantIDParam)); parseErr != nil {
c.Error(errors.NewBadRequestError(parseErr.Error()))
return
}
2025-08-05 07:08:07 +00:00
// A nil scope means no agent selector. Every resolved scope, including
// mode=all, binds results to the authorized agent's source tenant.
var agentScope *types.SharedAgentKBScope
if agentID := secutils.SanitizeForLog(req.AgentID); agentID != "" {
agent, err := resolveSharedAgentForRequest(c, agentID, h.agentShareService)
if err != nil {
_ = c.Error(err)
return
}
ctx = access.WithSharedAgent(ctx, agent)
scope := types.NewSharedAgentKBScope(agent)
agentScope = &scope
effectiveTenantID = agent.TenantID
if scope.IsEmpty() {
c.JSON(http.StatusOK, gin.H{"success": true, "data": []*types.Knowledge{}})
return
}
}
var knowledges []*types.Knowledge
var err error
// scopeKBID tracks the single KB the results must belong to (set by explicit kb_id).
var scopeKBID string
// Optional kb_id: validate KB access and use effective tenant for shared KB
if kbID := secutils.SanitizeForLog(req.KBID); kbID != "" {
_, _, effID, _, accessErr := h.validateKnowledgeBaseAccessWithKBID(c, kbID)
if accessErr != nil {
_ = c.Error(accessErr)
return
}
if agentScope != nil && !agentScope.Allows(kbID, effID) {
c.Error(errors.NewForbiddenError("Knowledge base not accessible through this agent"))
return
}
scopeKBID = kbID
effectiveTenantID = effID
ctx = types.WithExecutionTenant(c.Request.Context(), effectiveTenantID)
logger.Infof(ctx, "Batch retrieving knowledge with kb_id, effective tenant ID: %d, IDs count: %d",
effectiveTenantID, len(req.IDs))
knowledges, err = h.kgService.GetKnowledgeBatch(ctx, effectiveTenantID, req.IDs)
} else if agentScope != nil {
// Keep the authorized agent's read scope and the original caller.
ctx = types.WithExecutionTenant(ctx, effectiveTenantID)
knowledges, err = h.kgService.GetKnowledgeBatch(ctx, effectiveTenantID, req.IDs)
} else {
knowledges, err = h.kgService.GetKnowledgeBatchWithSharedAccess(ctx, effectiveTenantID, req.IDs)
}
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
_ = c.Error(errors.NewInternalServerError("Failed to retrieve knowledge list").WithDetails(err.Error()))
return
}
2025-08-05 07:08:07 +00:00
// Build the effective allowed-KB set from explicit kb_id, shared agent
// scope, and per-API-key KB restrictions.
var allowedKBSet map[string]bool
if scopeKBID != "" {
allowedKBSet = map[string]bool{scopeKBID: true}
}
if agentScope != nil {
knowledges = filterKnowledgeByAgentScope(knowledges, *agentScope)
}
if apiKeySet := tenantAPIKeyAllowedKBSet(ctx); apiKeySet != nil {
allowedKBSet = intersectKBAllowSet(allowedKBSet, apiKeySet)
}
if allowedKBSet != nil {
knowledges = filterKnowledgesByKBAllowSet(knowledges, allowedKBSet)
}
feat(knowledge): flag documents that stop making progress (#3557) * feat(knowledge): flag documents that stop making progress A document stuck in processing looked the same as one still working: a spinner that polled forever, no hint of where it stopped, and, hours later, a generic housekeeping failure. - The batch and spans endpoints return last_activity_at for in-flight rows: the later of updated_at and the newest span write. updated_at only moves at stage transitions; span writes keep moving while a long stage still works. - After 20 minutes with no progress, the list and card views show "may be stuck" with a tooltip. The timeline shows the stage it stopped at and a stop-parsing button, plus a "last progress" stat. Both pollers back off to 15s while everything in flight is stalled. - When housekeeping fails a row, the error names the stalled stage and the time of the last progress. It closes the row's open spans with TASK_STALLED (the running stage fails, the rest are cancelled), so the timeline shows where the run stopped instead of a spinner. * fix(knowledge): locate stalls in finalizing and tell backlog from stuck - Housekeeping reads the stall site from the latest attempt. It takes the running stages, or, when none runs (post-process closes its stage once enrichment is fanned out), the innermost running spans, mapped back to their stage. Those spans fail with TASK_STALLED and are named in the message; every stalled stage is listed in pipeline order. The other open spans are cancelled. Every closed span gets a duration, and the message leaves out the time when the heartbeat query failed. - The spans tree prefers a TASK_STALLED failure for last_error over a later subtask failure. current_stage falls back to the stage owning a running subspan. - Batch and spans responses flag rows quiet past the stall hint whose work is still queued (waiting_in_queue), using the sweep's own probes. At most 20 rows are probed per request, cached for a minute. The UI shows these as queued, with no stop button in the banner. * fix(knowledge): answer stall verdicts from one shared queue scan - Probing a quiet document for a backlog rescanned the whole queue once per document. When the document was absent, which is exactly the stuck case, the scan ran to the end, and it read a Redis error as "nothing queued". QueuedKnowledgeIDs now collects every referenced knowledge ID in one pass and returns list errors. HousekeepingService keeps that snapshot for a minute, shared across requests and single-flight. A failed scan is not cached. - With the per-request cap of 20 gone, every quiet row on a page gets a verdict. The response carries it as stall_state (queued or stalled), replacing waiting_in_queue. The UI marks a row as stuck only on a "stalled" verdict. A row with no verdict, because the probe failed, shows as ordinary processing instead of inviting a stop.
2026-09-22 13:34:08 +00:00
h.attachLastActivity(ctx, knowledges)
logger.Infof(ctx, "Batch knowledge retrieval successful, requested count: %d, returned count: %d",
len(req.IDs), len(knowledges))
2025-08-05 07:08:07 +00:00
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": knowledges,
})
}
feat(knowledge): flag documents that stop making progress (#3557) * feat(knowledge): flag documents that stop making progress A document stuck in processing looked the same as one still working: a spinner that polled forever, no hint of where it stopped, and, hours later, a generic housekeeping failure. - The batch and spans endpoints return last_activity_at for in-flight rows: the later of updated_at and the newest span write. updated_at only moves at stage transitions; span writes keep moving while a long stage still works. - After 20 minutes with no progress, the list and card views show "may be stuck" with a tooltip. The timeline shows the stage it stopped at and a stop-parsing button, plus a "last progress" stat. Both pollers back off to 15s while everything in flight is stalled. - When housekeeping fails a row, the error names the stalled stage and the time of the last progress. It closes the row's open spans with TASK_STALLED (the running stage fails, the rest are cancelled), so the timeline shows where the run stopped instead of a spinner. * fix(knowledge): locate stalls in finalizing and tell backlog from stuck - Housekeeping reads the stall site from the latest attempt. It takes the running stages, or, when none runs (post-process closes its stage once enrichment is fanned out), the innermost running spans, mapped back to their stage. Those spans fail with TASK_STALLED and are named in the message; every stalled stage is listed in pipeline order. The other open spans are cancelled. Every closed span gets a duration, and the message leaves out the time when the heartbeat query failed. - The spans tree prefers a TASK_STALLED failure for last_error over a later subtask failure. current_stage falls back to the stage owning a running subspan. - Batch and spans responses flag rows quiet past the stall hint whose work is still queued (waiting_in_queue), using the sweep's own probes. At most 20 rows are probed per request, cached for a minute. The UI shows these as queued, with no stop button in the banner. * fix(knowledge): answer stall verdicts from one shared queue scan - Probing a quiet document for a backlog rescanned the whole queue once per document. When the document was absent, which is exactly the stuck case, the scan ran to the end, and it read a Redis error as "nothing queued". QueuedKnowledgeIDs now collects every referenced knowledge ID in one pass and returns list errors. HousekeepingService keeps that snapshot for a minute, shared across requests and single-flight. A failed scan is not cached. - With the per-request cap of 20 gone, every quiet row on a page gets a verdict. The response carries it as stall_state (queued or stalled), replacing waiting_in_queue. The UI marks a row as stuck only on a "stalled" verdict. A row with no verdict, because the probe failed, shows as ordinary processing instead of inviting a stop.
2026-09-22 13:34:08 +00:00
func isStallFailure(span *types.KnowledgeProcessingSpan) bool {
return span.ErrorCode == errors.ErrCodeTaskStalled
}
// stageOfRunningSpan names the stage owning the newest running span, for the
// window where no stage span is running but its work still is: post-process
// closes its stage once summary / question / graph / wiki are fanned out.
func stageOfRunningSpan(rows []types.KnowledgeProcessingSpan) string {
bySpanID := make(map[string]*types.KnowledgeProcessingSpan, len(rows))
for i := range rows {
bySpanID[rows[i].SpanID] = &rows[i]
}
for i := len(rows) - 1; i >= 0; i-- {
if rows[i].Status != types.SpanStatusRunning || rows[i].Kind == types.SpanKindRoot {
continue
}
for span, depth := &rows[i], 0; span != nil && depth < 64; depth++ {
if span.Kind == types.SpanKindStage {
return span.Name
}
span = bySpanID[span.ParentSpanID]
}
}
return ""
}
// spansLastActivity is the latest of the row's updated_at and the listed
// spans' writes.
func spansLastActivity(updatedAt time.Time, rows []types.KnowledgeProcessingSpan) time.Time {
last := updatedAt
for _, row := range rows {
last = latestActivity(last, row.UpdatedAt)
}
return last
}
// attachLastActivity sets LastActivityAt on in-flight rows. updated_at only
// moves at stage transitions, so the latest span write is folded in: it
// advances with every subspan while a long stage is still working.
func (h *KnowledgeHandler) attachLastActivity(ctx context.Context, knowledges []*types.Knowledge) {
var ids []string
for _, k := range knowledges {
if k != nil && isParseInFlight(k.ParseStatus) {
ids = append(ids, k.ID)
}
}
if len(ids) == 0 {
return
}
var spanActivity map[string]time.Time
if h.spanRepo != nil {
var err error
if spanActivity, err = h.spanRepo.LastActivity(ctx, ids); err != nil {
logger.Warnf(ctx, "span last activity lookup failed: %v", err)
}
}
var quiet []*types.Knowledge
var quietIDs []string
for _, k := range knowledges {
if k == nil || !isParseInFlight(k.ParseStatus) {
continue
}
last := latestActivity(k.UpdatedAt, spanActivity[k.ID])
k.LastActivityAt = &last
if time.Since(last) >= stallHintAfter {
quiet = append(quiet, k)
quietIDs = append(quietIDs, k.ID)
}
}
verdicts := h.stallVerdicts(ctx, quietIDs)
for _, k := range quiet {
k.StallState = verdicts[k.ID]
}
}
func isParseInFlight(status string) bool {
switch status {
case types.ParseStatusPending, types.ParseStatusProcessing, types.ParseStatusFinalizing:
return true
}
return false
}
func latestActivity(times ...time.Time) time.Time {
var last time.Time
for _, t := range times {
if t.After(last) {
last = t
}
}
return last
}
// UpdateKnowledgeRequest defines the partial-update body for PUT /knowledge/:id.
// Omitted fields are left unchanged; an explicit empty description clears the summary.
type UpdateKnowledgeRequest struct {
Title *string `json:"title"`
Description *string `json:"description"`
CustomMetadata json.RawMessage `json:"custom_metadata"`
}
// UpdateKnowledge godoc
// @Summary 更新知识
// @Description 部分更新知识条目(标题/描述/自定义元数据);未传字段保持不变,显式传空 description 可清空摘要
// @Tags 知识管理
// @Accept json
// @Produce json
// @Param id path string true "知识ID"
// @Param request body UpdateKnowledgeRequest true "更新字段(均可选)"
// @Success 200 {object} map[string]interface{} "更新成功"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge/{id} [put]
2025-08-05 07:08:07 +00:00
func (h *KnowledgeHandler) UpdateKnowledge(c *gin.Context) {
ctx := c.Request.Context()
id := secutils.SanitizeForLog(c.Param("id"))
2025-08-05 07:08:07 +00:00
if id == "" {
logger.Error(ctx, "Knowledge ID is empty")
c.Error(errors.NewBadRequestError("Knowledge ID cannot be empty"))
return
}
_, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, id, types.OrgRoleEditor)
if err != nil {
c.Error(err)
return
}
var req UpdateKnowledgeRequest
if err := c.ShouldBindJSON(&req); err != nil {
2025-08-05 07:08:07 +00:00
logger.Error(ctx, "Failed to parse request parameters", err)
c.Error(errors.NewBadRequestError(err.Error()))
return
}
knowledge := types.Knowledge{ID: id, CustomMetadata: types.JSON(req.CustomMetadata)}
if req.Title != nil {
knowledge.Title = *req.Title
}
if req.Description != nil {
knowledge.Description = *req.Description
knowledge.DescriptionSpecified = true
}
2025-08-05 07:08:07 +00:00
if err := h.kgService.UpdateKnowledge(effCtx, &knowledge); err != nil {
2025-08-05 07:08:07 +00:00
logger.ErrorWithFields(ctx, err, nil)
var appErr *errors.AppError
if goerrors.As(err, &appErr) {
_ = c.Error(appErr)
} else {
_ = c.Error(errors.NewInternalServerError(err.Error()))
}
2025-08-05 07:08:07 +00:00
return
}
updated, getErr := h.kgService.GetKnowledgeByID(effCtx, id)
if getErr != nil {
logger.Warnf(ctx, "Knowledge updated but failed to reload status for %s: %v", id, getErr)
}
2025-08-05 07:08:07 +00:00
logger.Infof(ctx, "Knowledge updated successfully, knowledge ID: %s", id)
2025-08-05 07:08:07 +00:00
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "Knowledge updated successfully",
"data": updated,
2025-08-05 07:08:07 +00:00
})
}
// RegenerateKnowledgeSummary refreshes a stale summary after chunk or metadata edits.
func (h *KnowledgeHandler) RegenerateKnowledgeSummary(c *gin.Context) {
ctx := c.Request.Context()
id := secutils.SanitizeForLog(c.Param("id"))
if id == "" {
c.Error(errors.NewBadRequestError("Knowledge ID cannot be empty"))
return
}
_, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, id, types.OrgRoleEditor)
if err != nil {
c.Error(err)
return
}
knowledge, err := h.kgService.GetKnowledgeByID(effCtx, id)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
var appErr *errors.AppError
if goerrors.As(err, &appErr) {
_ = c.Error(appErr)
} else {
_ = c.Error(errors.NewInternalServerError(err.Error()))
}
return
}
if knowledge.SummaryStatus == "" || knowledge.SummaryStatus == types.SummaryStatusNone {
knowledge, err = h.kgService.RegenerateKnowledgeSummary(effCtx, id)
} else {
err = h.kgService.RequestKnowledgeSummaryRefresh(effCtx, id)
if err == nil {
knowledge, err = h.kgService.GetKnowledgeByID(effCtx, id)
}
}
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
var appErr *errors.AppError
if goerrors.As(err, &appErr) {
_ = c.Error(appErr)
} else {
_ = c.Error(errors.NewBadRequestError(err.Error()))
}
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": knowledge})
}
// UpdateManualKnowledge godoc
// @Summary 更新手工知识
// @Description 更新手工录入的Markdown知识内容
// @Tags 知识管理
// @Accept json
// @Produce json
// @Param id path string true "知识ID"
// @Param request body types.ManualKnowledgePayload true "手工知识内容"
// @Success 200 {object} map[string]interface{} "更新后的知识"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge/manual/{id} [put]
func (h *KnowledgeHandler) UpdateManualKnowledge(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start updating manual knowledge")
id := secutils.SanitizeForLog(c.Param("id"))
if id == "" {
logger.Error(ctx, "Knowledge ID is empty")
c.Error(errors.NewBadRequestError("Knowledge ID cannot be empty"))
return
}
_, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, id, types.OrgRoleEditor)
if err != nil {
c.Error(err)
return
}
var req types.ManualKnowledgePayload
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to parse manual knowledge update request", err)
c.Error(errors.NewBadRequestError(err.Error()))
return
}
knowledge, err := h.kgService.UpdateManualKnowledge(effCtx, id, &req)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
c.Error(appErr)
return
}
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"knowledge_id": id,
})
c.Error(errors.NewInternalServerError(err.Error()))
return
}
logger.Infof(ctx, "Manual knowledge updated successfully, knowledge ID: %s", id)
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": knowledge,
})
}
// ReparseKnowledge godoc
// @Summary 重新解析知识
// @Description 删除知识中现有的文档内容并重新解析,使用异步任务方式处理
// @Tags 知识管理
// @Accept json
// @Produce json
// @Param id path string true "知识ID"
// @Param body body object false "可选的处理配置覆盖:{\"process_config\": KnowledgeProcessOverrides}"
// @Success 200 {object} map[string]interface{} "重新解析任务已提交"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 403 {object} errors.AppError "权限不足"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge/{id}/reparse [post]
func (h *KnowledgeHandler) ReparseKnowledge(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start re-parsing knowledge")
id := secutils.SanitizeForLog(c.Param("id"))
if id == "" {
logger.Error(ctx, "Knowledge ID is empty")
c.Error(errors.NewBadRequestError("Knowledge ID cannot be empty"))
return
}
// Validate KB access with editor permission (reparse requires write access)
_, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, id, types.OrgRoleEditor)
if err != nil {
c.Error(err)
return
}
// Optional per-reparse parse config override. Empty body keeps the
// overrides stored at upload time.
var processOverrides *types.KnowledgeProcessOverrides
if c.Request.ContentLength != 0 {
var req struct {
ProcessConfig *types.KnowledgeProcessOverrides `json:"process_config"`
}
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to parse reparse request body", err)
c.Error(errors.NewBadRequestError("Invalid reparse request body").WithDetails(err.Error()))
return
}
processOverrides = req.ProcessConfig
}
// Call service to reparse knowledge
knowledge, err := h.kgService.ReparseKnowledge(effCtx, id, processOverrides)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
c.Error(appErr)
return
}
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"knowledge_id": id,
})
c.Error(errors.NewInternalServerError(err.Error()))
return
}
logger.Infof(ctx, "Knowledge reparse task submitted successfully, knowledge ID: %s", id)
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "Knowledge reparse task submitted",
"data": knowledge,
})
}
feat: add knowledge parse cancellation with finalizing post-process state Lets users stop an in-flight document parse to free up LLM / worker resources without losing the chunks and index already written. The core insight is that the previous parse_status=completed flipped as soon as primary chunks landed, while the most expensive subtasks (graph extract = N LLM calls per chunk, plus summary, question generation) were still running in the background — so "completed" wasn't actually terminal from a resource standpoint. State machine pending -> processing -> finalizing -> completed | +-> cancelled (any of the three in-flight states) +-> failed +-> deleting `finalizing` is the new post-process fan-out window. parse_status only promotes to `completed` once pending_subtasks_count (a new column tracking summary + question + per-chunk graph extract) drains to zero via atomic FinalizeSubtask. Wiki ingest is intentionally excluded from the counter — it's a KB-scoped debounced batch and would otherwise pin parse_status in `finalizing` for the wiki batch window. Backend - New ParseStatusFinalizing + pending_subtasks_count column with migration 000056. - knowledgeRepository.SetFinalizing transitions processing -> finalizing conditionally so a racing cancel cannot be clobbered. - knowledgeRepository.FinalizeSubtask atomically decrements the counter and self-promotes the row to completed when it hits zero. - KnowledgePostProcess restructured to compute expected subtask count up front, flip to finalizing (or completed when no enrichment is enabled), and only then fan out subtasks. Subtask handlers (summary, question, graph extract) defer-decrement on terminal exit using the existing isFinalAsynqAttempt convention. - New POST /api/v1/knowledge/{id}/cancel-parse handler accepting pending / processing / finalizing. Marks the row cancelled, zeroes the counter, best-effort dequeues asynq tasks via a new TaskInspector abstraction (asynq-mode walks pending/scheduled/ retry queues; Lite-mode noop), and scrubs wiki ingest pending op. - SpanTracker.AbortAttempt flat-sweeps every still-running span for the attempt via a new repo.CancelAllOpenSpans helper so the trace viewer's striped bars all flip to cancelled, even leaf generations whose parent stage already EndSpan'd (multimodal fan-out pattern). knowledge_post_process closes its postSpan via SkipSpan on the cancel/deleting entry guard so a worker that opens a span AFTER the cancel sweep doesn't leak it. - Housekeeping and resetPendingTasks sweep finalizing rows identically to processing so a crash/restart can't strand them. - DeleteKnowledge/DeleteKnowledgeList proactively dequeue downstream tasks via the same TaskInspector path. - ChunkExtractService gets a cancel entry guard so the most expensive enrichment (graph extract) bails immediately when the parent knowledge is aborted. Frontend - New cancelKnowledgeParse API client + "Stop parsing" entry in both list view and card view more menus, gated on pending/processing/finalizing. - Polling predicate refactored to a shared isParseInFlight helper that recognises `finalizing` (previously the doc list silently stopped polling once parse_status flipped from processing). - Knowledge processing timeline: isPolling includes finalizing, new isHardTerminal short-circuits LIVE for cancelled/failed/ completed so stranded child spans cannot pin LIVE on. - DocumentListView.computeStatus distinguishes finalizing ("增强中") from completed and shows the previous "生成摘要中" copy when summary_status is still pending under finalizing. Added cancelled badge as well. - i18n: statusFinalizing / statusCancelled / cancelParse* keys across zh-CN, en-US, ko-KR, ru-RU. Docs / SDK - docs/api/knowledge.md: documents the new finalizing state, cancel-parse semantics, and which statuses accept cancel. - client (Go SDK): CancelKnowledgeParse with docstring listing the cancellable statuses.
2026-05-28 10:26:56 +00:00
// CancelKnowledgeParse godoc
// @Summary 取消知识解析
// @Description 取消进行中的知识解析任务。当前已写入的 chunk / 索引保留,可通过 reparse 接口重新触发解析。已完成 / 已失败 / 删除中的知识不支持取消。
// @Tags 知识管理
// @Accept json
// @Produce json
// @Param id path string true "知识ID"
// @Success 200 {object} map[string]interface{} "取消已提交"
// @Failure 400 {object} errors.AppError "状态不支持取消"
// @Failure 403 {object} errors.AppError "权限不足"
// @Failure 404 {object} errors.AppError "知识不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge/{id}/cancel-parse [post]
func (h *KnowledgeHandler) CancelKnowledgeParse(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start cancelling knowledge parse")
id := secutils.SanitizeForLog(c.Param("id"))
if id == "" {
logger.Error(ctx, "Knowledge ID is empty")
c.Error(errors.NewBadRequestError("Knowledge ID cannot be empty"))
return
}
// Editor permission — same gate as ReparseKnowledge / DeleteKnowledge.
_, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, id, types.OrgRoleEditor)
if err != nil {
c.Error(err)
return
}
knowledge, err := h.kgService.CancelKnowledgeParse(effCtx, id)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
c.Error(appErr)
return
}
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"knowledge_id": id,
})
c.Error(errors.NewInternalServerError(err.Error()))
return
}
logger.Infof(ctx, "Knowledge parse cancelled successfully, knowledge ID: %s", id)
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "Knowledge parse cancelled",
"data": knowledge,
})
}
type knowledgeTagBatchRequest struct {
feat: support multi-tag for document knowledge (#1790) * feat: support multi-tag for document knowledge - Add knowledge_tag_relations join table for many-to-many tag-knowledge mapping - Migrate existing single tag_id data to the new table - Update Knowledge struct, filter, payload types (TagID -> Tags/TagIDs) - Rewrite repository layer: SetKnowledgeTags, GetKnowledgeTags, ListIDsByTagIDs - Update tag count references to query knowledge_tag_relations - Update service/handler layers for multi-tag create/list/batch-update - Frontend: multi-select tag sidebar, multi-tag chip display, tag toggle in popup - FAQ tags remain single-tag model (unchanged) * feat(knowledge): tag edit dialog with dynamic overflow and inline creation - Add TagEditDialog component with search, multi-select, and confirm - Replace inline t-popup tag selector with dialog-based editing - Tags overflow with +N badge, visible count adapts to container width via ResizeObserver - Date/card layout: fixed date width, tags flex to fill remaining space - Add persistent new-tag input bar in dialog (Enter to create, auto-select) - Tag creation emits callback to refresh parent tag list immediately - Apply same overflow + dialog trigger to both card view and list view - Add i18n keys: tagEditDialogTitle, tagEditSearch, tagSelectedCount, tagOverflowTip, tagNewPlaceholder * fix: exclude soft-deleted knowledge from tag reference counts CountReferences, BatchCountReferences, and DeleteUnusedTags now JOIN with knowledges table to filter out soft-deleted records when counting knowledge_tag_relations. Previously they queried knowledge_tag_relations directly without the deleted_at check, causing stale tag counts after knowledge deletion. * fix: refresh tag counts after async knowledge deletion completes Add a second delayed tag list refresh (2.5s) after tag deletion to capture updated reference counts for remaining tags. The original immediate refresh handles removing the deleted tag from the list, while this delayed refresh ensures other tags' counts are correct after the async deletion finishes. --------- Co-authored-by: lyingbug <xiayula2014@gmail.com>
2026-06-25 16:18:48 +00:00
Updates map[string][]string `json:"updates" binding:"required,min=1"`
KBID string `json:"kb_id"` // Optional: scope to this KB (validates editor access and uses effective tenant for shared KB)
}
// UpdateKnowledgeTagBatch godoc
// @Summary 批量更新知识标签
// @Description 批量更新知识条目的标签。可选 kb_id:指定时按该知识库校验编辑权限并用于共享知识库的空间解析
// @Tags 知识管理
// @Accept json
// @Produce json
// @Param request body object true "标签更新请求(updates 必填,kb_id 可选)"
// @Success 200 {object} map[string]interface{} "更新成功"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge/tags [put]
func (h *KnowledgeHandler) UpdateKnowledgeTagBatch(c *gin.Context) {
ctx := c.Request.Context()
// Ensure tenant ID is in context (service reads it; may be missing if request context was not set by auth)
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
c.Error(errors.NewUnauthorizedError("Unauthorized"))
return
}
ctx = types.WithExecutionTenant(ctx, tenantID)
var req knowledgeTagBatchRequest
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to parse knowledge tag batch request", err)
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
// Resolve effective tenant and the authorized KB scope.
var authorizedKBID string
if kbID := secutils.SanitizeForLog(req.KBID); kbID != "" {
_, _, effID, permission, err := h.validateKnowledgeBaseWriteAccessWithKBID(c, kbID)
if err != nil {
c.Error(err)
return
}
if permission != types.OrgRoleAdmin && permission != types.OrgRoleEditor {
c.Error(errors.NewForbiddenError("No permission to update knowledge tags"))
return
}
authorizedKBID = kbID
ctx = types.WithExecutionTenant(c.Request.Context(), effID)
} else if len(req.Updates) > 0 {
// No kb_id: infer from first knowledge ID so shared-KB updates work without client sending kb_id
var firstKnowledgeID string
for id := range req.Updates {
firstKnowledgeID = id
break
}
if firstKnowledgeID != "" {
knowledge, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, firstKnowledgeID, types.OrgRoleEditor)
if err != nil {
c.Error(err)
return
}
authorizedKBID = knowledge.KnowledgeBaseID
ctx = effCtx
}
}
if err := h.requireKBOwnershipOrAdmin(c, authorizedKBID); err != nil {
_ = c.Error(err)
return
}
if err := h.kgService.UpdateKnowledgeTagBatch(ctx, authorizedKBID, req.Updates); err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
})
}
// UpdateImageInfo godoc
// @Summary 更新图像信息
// @Description 更新知识分块的图像信息
// @Tags 知识管理
// @Accept json
// @Produce json
// @Param id path string true "知识ID"
// @Param chunk_id path string true "分块ID"
// @Param request body object{image_info=string} true "图像信息"
// @Success 200 {object} map[string]interface{} "更新成功"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge/image/{id}/{chunk_id} [put]
2025-08-05 07:08:07 +00:00
func (h *KnowledgeHandler) UpdateImageInfo(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start updating image info")
id := secutils.SanitizeForLog(c.Param("id"))
2025-08-05 07:08:07 +00:00
if id == "" {
logger.Error(ctx, "Knowledge ID is empty")
c.Error(errors.NewBadRequestError("Knowledge ID cannot be empty"))
return
}
chunkID := secutils.SanitizeForLog(c.Param("chunk_id"))
if chunkID == "" {
2025-08-05 07:08:07 +00:00
logger.Error(ctx, "Chunk ID is empty")
c.Error(errors.NewBadRequestError("Chunk ID cannot be empty"))
return
}
_, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, id, types.OrgRoleEditor)
if err != nil {
c.Error(err)
return
}
2025-08-05 07:08:07 +00:00
var request struct {
ImageInfo string `json:"image_info"`
}
if err := c.ShouldBindJSON(&request); err != nil {
logger.Error(ctx, "Failed to parse request parameters", err)
c.Error(errors.NewBadRequestError(err.Error()))
return
}
logger.Infof(ctx, "Updating knowledge chunk, knowledge ID: %s, chunk ID: %s", id, chunkID)
err = h.kgService.UpdateImageInfo(effCtx, id, chunkID, secutils.SanitizeForLog(request.ImageInfo))
2025-08-05 07:08:07 +00:00
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
var appErr *errors.AppError
if goerrors.As(err, &appErr) {
_ = c.Error(appErr)
} else {
_ = c.Error(errors.NewInternalServerError(err.Error()))
}
2025-08-05 07:08:07 +00:00
return
}
logger.Infof(ctx, "Knowledge chunk updated successfully, knowledge ID: %s, chunk ID: %s", id, chunkID)
2025-08-05 07:08:07 +00:00
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "Knowledge chunk image updated successfully",
})
}
// SearchKnowledge godoc
// @Summary Search knowledge
// @Description Search knowledge files by keyword. Pass recent=true without a keyword to browse recent files. When agent_id is set (shared agent), scope is the agent's configured knowledge bases.
// @Tags Knowledge
// @Accept json
// @Produce json
// @Param keyword query string false "Keyword to search"
// @Param offset query int false "Offset for pagination (minimum 0)" minimum(0)
// @Param limit query int false "Limit for pagination (default 20, maximum 100)" minimum(1) maximum(100)
// @Param file_types query string false "Comma-separated file extensions to filter (e.g., csv,xlsx)"
// @Param agent_id query string false "Shared agent ID (search within agent's KB scope)"
// @Param recent query bool false "Return recent files when keyword is empty"
// @Success 200 {object} map[string]interface{} "Search results"
// @Failure 400 {object} errors.AppError "Invalid request"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge/search [get]
func (h *KnowledgeHandler) SearchKnowledge(c *gin.Context) {
ctx := c.Request.Context()
if userID, ok := c.Get(types.UserIDContextKey.String()); ok {
ctx = context.WithValue(ctx, types.UserIDContextKey, userID)
}
fix(handler): /knowledge/search · accept ?query= and reject empty keyword Silent-failure footgun in SearchKnowledge handler: keyword := c.Query("keyword") // only "keyword" recognized // empty keyword → service falls back to default listing (created_at DESC) // → caller sees "all queries return the same N newest knowledges" This is exactly what happened to a downstream agent (Support GPT) — it was sending ?query=... (the parameter name every MCP / semantic-search tool uses) and getting a constant 5-card listing back regardless of input. The caller diagnosed it as "WeKnora embedding has degraded · vector channel returns constant rankings", but actually the parameter was never read, the search service got keyword="", and the SQL came back as a plain list-by-created_at. The handler stays a filename/title LIKE search (its real purpose is the document-management UI). Two tweaks: 1. Accept ?query= as an alias for ?keyword= · this is what MCP / agent integrations actually send. Cheap compatibility win, zero downside. 2. Empty keyword/query → 400 with a clear hint. Refusing the request is strictly better than silently returning a default listing that looks like "search results" but isn't query-driven. Separately worth noting: callers who actually want semantic recall should use POST /api/v1/knowledge-bases/{kb_id}/hybrid-search · which is the real vector + BM25 endpoint. This handler was never the right tool for RAG queries · the silent failure just made it look like one. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-05 00:01:02 +00:00
// Accept both ?keyword= (legacy / upstream name) and ?query= (what most
// MCP / agent integrations send). Empty input is only valid for an explicit
// recent-file browse request; ordinary callers still get a clear 400 instead
// of silently receiving the same newest cards for every missing query.
keyword := c.Query("keyword")
fix(handler): /knowledge/search · accept ?query= and reject empty keyword Silent-failure footgun in SearchKnowledge handler: keyword := c.Query("keyword") // only "keyword" recognized // empty keyword → service falls back to default listing (created_at DESC) // → caller sees "all queries return the same N newest knowledges" This is exactly what happened to a downstream agent (Support GPT) — it was sending ?query=... (the parameter name every MCP / semantic-search tool uses) and getting a constant 5-card listing back regardless of input. The caller diagnosed it as "WeKnora embedding has degraded · vector channel returns constant rankings", but actually the parameter was never read, the search service got keyword="", and the SQL came back as a plain list-by-created_at. The handler stays a filename/title LIKE search (its real purpose is the document-management UI). Two tweaks: 1. Accept ?query= as an alias for ?keyword= · this is what MCP / agent integrations actually send. Cheap compatibility win, zero downside. 2. Empty keyword/query → 400 with a clear hint. Refusing the request is strictly better than silently returning a default listing that looks like "search results" but isn't query-driven. Separately worth noting: callers who actually want semantic recall should use POST /api/v1/knowledge-bases/{kb_id}/hybrid-search · which is the real vector + BM25 endpoint. This handler was never the right tool for RAG queries · the silent failure just made it look like one. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-05 00:01:02 +00:00
if keyword == "" {
keyword = c.Query("query")
}
recent, _ := strconv.ParseBool(c.DefaultQuery("recent", "false"))
if strings.TrimSpace(keyword) == "" && !recent {
fix(handler): /knowledge/search · accept ?query= and reject empty keyword Silent-failure footgun in SearchKnowledge handler: keyword := c.Query("keyword") // only "keyword" recognized // empty keyword → service falls back to default listing (created_at DESC) // → caller sees "all queries return the same N newest knowledges" This is exactly what happened to a downstream agent (Support GPT) — it was sending ?query=... (the parameter name every MCP / semantic-search tool uses) and getting a constant 5-card listing back regardless of input. The caller diagnosed it as "WeKnora embedding has degraded · vector channel returns constant rankings", but actually the parameter was never read, the search service got keyword="", and the SQL came back as a plain list-by-created_at. The handler stays a filename/title LIKE search (its real purpose is the document-management UI). Two tweaks: 1. Accept ?query= as an alias for ?keyword= · this is what MCP / agent integrations actually send. Cheap compatibility win, zero downside. 2. Empty keyword/query → 400 with a clear hint. Refusing the request is strictly better than silently returning a default listing that looks like "search results" but isn't query-driven. Separately worth noting: callers who actually want semantic recall should use POST /api/v1/knowledge-bases/{kb_id}/hybrid-search · which is the real vector + BM25 endpoint. This handler was never the right tool for RAG queries · the silent failure just made it look like one. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-05 00:01:02 +00:00
c.Error(errors.NewBadRequestError("missing search keyword: pass ?keyword=... or ?query=..."))
return
}
keyword = strings.TrimSpace(keyword)
offset, limit, ok := parseOffsetPagination(c)
if !ok {
return
}
var fileTypes []string
if fileTypesStr := c.Query("file_types"); fileTypesStr != "" {
for _, ft := range strings.Split(fileTypesStr, ",") {
ft = strings.TrimSpace(ft)
if ft != "" {
fileTypes = append(fileTypes, ft)
}
}
}
agentID := c.Query("agent_id")
if agentID != "" {
agent, err := resolveSharedAgentForRequest(c, agentID, h.agentShareService)
if err != nil {
_ = c.Error(err)
return
}
sourceTenantID := agent.TenantID
ctx = access.WithSharedAgent(ctx, agent)
scope := types.NewSharedAgentKBScope(agent)
if scope.IsEmpty() {
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": []interface{}{},
"has_more": false,
"total": 0,
})
return
}
var scopes []types.KnowledgeSearchScope
if !scope.IsAll() {
for _, kbID := range scope.IDs() {
if kbID != "" {
scopes = append(scopes, types.KnowledgeSearchScope{TenantID: sourceTenantID, KBID: kbID})
}
}
}
if scope.IsAll() {
kbs, err := h.kbService.ListKnowledgeBasesByTenantID(ctx, sourceTenantID)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to list knowledge bases").WithDetails(err.Error()))
return
}
for _, kb := range filterKnowledgeBasesForSharedAgent(kbs, agent) {
if kb.Type == types.KnowledgeBaseTypeDocument {
scopes = append(scopes, types.KnowledgeSearchScope{TenantID: kb.TenantID, KBID: kb.ID})
}
}
}
scopes = filterKnowledgeSearchScopesForAPIKey(ctx, scopes)
if len(scopes) == 0 {
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": []interface{}{},
"has_more": false,
"total": 0,
})
return
}
knowledges, hasMore, total, err := h.kgService.SearchKnowledgeForScopes(ctx, scopes, keyword, offset, limit, fileTypes)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to search knowledge").WithDetails(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": knowledges,
"has_more": hasMore,
"total": total,
})
return
}
if scopes, restricted := tenantAPIKeySearchScopes(ctx); restricted {
if len(scopes) == 0 {
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": []interface{}{},
"has_more": false,
"total": 0,
})
return
}
knowledges, hasMore, total, err := h.kgService.SearchKnowledgeForScopes(ctx, scopes, keyword, offset, limit, fileTypes)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to search knowledge").WithDetails(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": knowledges,
"has_more": hasMore,
"total": total,
})
return
}
// Default: own + shared KBs
knowledges, hasMore, total, err := h.kgService.SearchKnowledge(ctx, keyword, offset, limit, fileTypes)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to search knowledge").WithDetails(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": knowledges,
"has_more": hasMore,
"total": total,
})
}
// MoveKnowledgeRequest defines the request for moving knowledge items
type MoveKnowledgeRequest struct {
KnowledgeIDs []string `json:"knowledge_ids" binding:"required,min=1"`
SourceKBID string `json:"source_kb_id" binding:"required"`
TargetKBID string `json:"target_kb_id" binding:"required"`
Mode string `json:"mode" binding:"required,oneof=reuse_vectors reparse"`
}
// MoveKnowledgeResponse defines the response for move knowledge
type MoveKnowledgeResponse struct {
TaskID string `json:"task_id"`
SourceKBID string `json:"source_kb_id"`
TargetKBID string `json:"target_kb_id"`
KnowledgeCount int `json:"knowledge_count"`
Message string `json:"message"`
}
// MoveKnowledge moves knowledge items from one knowledge base to another (async task).
docs(api): add and fix swag annotations on handlers 将 swag 注解覆盖率从 ~88% 提升到 100%,并修复审计中发现的若干既有 注解 bug。 新增注解(24 个): - im.go: 4 (UpdateIMChannel/DeleteIMChannel/ToggleIMChannel/IMCallback) 其中 IMCallback 同时注册 GET 和 POST,两个方法都加了 @Router 声明。 - web_search.go: 1 (GetProviders) - web_search_provider.go: 6 - wechat_qrcode.go: 2 - weknoracloud.go: 2 - knowledge.go: 2 (MoveKnowledge/GetKnowledgeMoveProgress) - knowledgebase.go: 1 (ListMoveTargets) - organization.go: 3 (ListSharedAgents/ListOrgAgentShares/RemoveAgentShare) - mcp_service.go: 2 (SetMCPToolApproval/ResolveToolApproval) - chunker_debug.go: 1 (PreviewChunking) 修复既有注解 bug(12 处): - initialization.go: 10 个 @Router 路径与真实路由不符 (e.g. /initialization/kb/{kbId}/config → /initialization/config/{kbId} /initialization/fabri/tag GET → /initialization/extract/fabri-tag POST) - session/stream.go: ContinueStream 路径 /sessions/{session_id}/continue → /sessions/continue-stream/{session_id} - mcp_service.go: ResolveToolApproval 请求体 {approve: bool} → {decision: "approve"|"reject", reason?, modified_args?} 收敛响应 schema 到已有命名 struct(之前用 map[string]interface{}): - knowledge.go MoveKnowledge → handler.MoveKnowledgeResponse - knowledge.go GetKnowledgeMoveProgress → types.KnowledgeMoveProgress - web_search_provider.go GetProvider/UpdateProvider → types.WebSearchProviderEntity - initialization.go InitializeByKB → handler.InitializationRequest - initialization.go 三个 model-test endpoint → handler.ModelTestRequest 修正 organization.go 中 errors.AppError 应使用 apperrors 别名(该文件 stdlib errors 未别名化)。 不补 /files 和 /api/v1/files/presigned 内联闭包路由(文件服务,非业务 REST)。 Refs #890 #1049 #1168
2026-05-11 09:37:14 +00:00
//
// MoveKnowledge godoc
// @Summary 移动知识到其他知识库
// @Description 将一条或多条知识从源知识库移动到目标知识库(异步),返回任务 ID 用于查询进度
// @Tags 知识
// @Accept json
// @Produce json
// @Param request body handler.MoveKnowledgeRequest true "{source_kb_id, target_kb_id, knowledge_ids}"
// @Success 200 {object} handler.MoveKnowledgeResponse "任务信息"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge/move [post]
func (h *KnowledgeHandler) MoveKnowledge(c *gin.Context) {
ctx := c.Request.Context()
var req MoveKnowledgeRequest
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "MoveKnowledge: failed to parse request", err)
c.Error(errors.NewBadRequestError("Invalid request parameters: " + err.Error()))
return
}
// Validate source != target
if req.SourceKBID == req.TargetKBID {
c.Error(errors.NewBadRequestError("Source and target knowledge base cannot be the same"))
return
}
tenantID, exists := c.Get(types.TenantIDContextKey.String())
if !exists {
c.Error(errors.NewUnauthorizedError("Unauthorized"))
return
}
if err := requireTenantAPIKeyKnowledgeBases(ctx, req.SourceKBID, req.TargetKBID); err != nil {
c.Error(err)
return
}
// Validate source KB
sourceKB, err := h.kbService.GetKnowledgeBaseByID(ctx, req.SourceKBID)
if err != nil {
if goerrors.Is(err, repository.ErrKnowledgeBaseNotFound) {
c.Error(errors.NewNotFoundError("Source knowledge base not found"))
return
}
c.Error(errors.NewInternalServerError(err.Error()))
return
}
if sourceKB.TenantID != tenantID.(uint64) {
c.Error(errors.NewForbiddenError("No permission to access source knowledge base"))
return
}
if err := h.requireKBOwnershipOrAdmin(c, req.SourceKBID); err != nil {
c.Error(err)
return
}
// Validate target KB
targetKB, err := h.kbService.GetKnowledgeBaseByID(ctx, req.TargetKBID)
if err != nil {
if goerrors.Is(err, repository.ErrKnowledgeBaseNotFound) {
c.Error(errors.NewNotFoundError("Target knowledge base not found"))
return
}
c.Error(errors.NewInternalServerError(err.Error()))
return
}
if targetKB.TenantID != tenantID.(uint64) {
c.Error(errors.NewForbiddenError("No permission to access target knowledge base"))
return
}
if err := h.requireKBOwnershipOrAdmin(c, req.TargetKBID); err != nil {
c.Error(err)
return
}
// Resolve explicit write grants independently for both body IDs.
if _, err := resolveHandlerKBAccessFor(c, req.SourceKBID, h.kbService, nil, nil, types.OrgRoleEditor); err != nil {
_ = c.Error(err)
return
}
if _, err := resolveHandlerKBAccessFor(c, req.TargetKBID, h.kbService, nil, nil, types.OrgRoleEditor); err != nil {
_ = c.Error(err)
return
}
taskID := utils.GenerateTaskID("kg_move", tenantID.(uint64), req.SourceKBID)
ctx, err = access.WithKBTransfer(c.Request.Context(), sourceKB, targetKB, access.KBTransferMove, taskID, false)
if err != nil {
_ = c.Error(kbAccessHTTPError(err))
return
}
tenant, _ := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
if err := access.ValidateKBTransferCompatibility(sourceKB,
targetKB,
access.KBTransferMove,
req.Mode,
tenant); err != nil {
_ = c.Error(errors.NewBadRequestError(err.Error()))
return
}
uniqueIDs := make([]string, 0, len(req.KnowledgeIDs))
seen := make(map[string]bool, len(req.KnowledgeIDs))
for _, id := range req.KnowledgeIDs {
if strings.TrimSpace(id) == "" {
_ = c.Error(errors.NewBadRequestError("Knowledge ID cannot be empty"))
return
}
if !seen[id] {
seen[id] = true
uniqueIDs = append(uniqueIDs, id)
}
}
req.KnowledgeIDs = uniqueIDs
// Validate all knowledge IDs belong to source KB and are in completed status
for _, kID := range req.KnowledgeIDs {
knowledge, err := h.kgService.GetKnowledgeByID(ctx, kID)
if err != nil {
c.Error(errors.NewBadRequestError(fmt.Sprintf("Knowledge item %s not found", kID)))
return
}
if knowledge == nil || knowledge.ID != kID || knowledge.TenantID != tenantID.(uint64) ||
knowledge.KnowledgeBaseID != req.SourceKBID {
_ = c.Error(
errors.NewBadRequestError(
fmt.Sprintf("Knowledge item %s does not belong to the source knowledge base", kID),
),
)
return
}
if knowledge.ParseStatus != types.ParseStatusCompleted {
c.Error(errors.NewBadRequestError(fmt.Sprintf("Knowledge item %s is not in completed status (current: %s)", kID, knowledge.ParseStatus)))
return
}
}
// Create move payload
payload := types.KnowledgeMovePayload{
TenantID: tenantID.(uint64),
TaskID: taskID,
KnowledgeIDs: req.KnowledgeIDs,
SourceKBID: req.SourceKBID,
TargetKBID: req.TargetKBID,
Mode: req.Mode,
Initiator: types.TaskInitiatorFromContext(ctx),
}
feat(observability): extend Langfuse tracing across asynq pipeline Previously the Langfuse integration only traced in-process HTTP requests (chat / search / eval), so file uploads and every downstream asynq task (document parse, chunk embedding, OCR/VLM, summary / question gen, wiki ingest, datasource sync, etc.) produced either disconnected shallow traces or no observation at all. This change threads one trace end-to-end: - tracer: add SPAN observation type and StartSpan; add ResumeTrace so a worker can attach to an upstream trace without emitting a duplicate trace-create; StartGeneration now auto-picks parentObservationId from ctx so nested trace -> span -> generation trees render correctly. - types.TracingContext + LangfuseTracingCarrier: embed on all 17 asynq payloads so trace_id / parent_obs_id / user_id / session_id serialise into every job. - langfuse.InjectTracing: injected at 28 enqueue sites before json.Marshal so the HTTP-layer trace survives the Redis hop. - langfuse.AsynqMiddleware: mux.Use hook that peeks the payload, either resumes the upstream trace or opens a standalone asynq.<type> trace for scheduled jobs, and wraps the handler in a SPAN with task metadata (id / queue / retry / payload_bytes) plus ERROR level on failure. - GinMiddleware.shouldTrace: whitelist ingestion / knowledge-mutation / FAQ / wiki / datasource endpoints so the root trace actually starts. - Tests: tracer_test.go covers span nesting, error status, and ResumeTrace no-trace-create guarantee; asynq_test.go covers InjectTracing round-trip, middleware resume path, and standalone trace fallback. - Docs: docs/Langfuse\u96c6\u6210.md now lists the covered task types and documents the cross-process propagation model. No behavioural change when Langfuse is disabled (all new code paths are no-ops and carriers serialise to empty strings with omitempty).
2026-04-24 04:23:30 +00:00
langfuse.InjectTracing(ctx, &payload)
payloadBytes, err := json.Marshal(payload)
if err != nil {
logger.Errorf(ctx, "MoveKnowledge: failed to marshal payload: %v", err)
c.Error(errors.NewInternalServerError("Failed to create task"))
return
}
// Enqueue move task
task := asynq.NewTask(types.TypeKnowledgeMove, payloadBytes,
asynq.TaskID(taskID), asynq.Queue(types.QueueMaintenance),
asynq.MaxRetry(3), asynq.Timeout(2*time.Hour))
info, err := h.asynqClient.Enqueue(task)
if err != nil {
logger.Errorf(ctx, "MoveKnowledge: failed to enqueue task: %v", err)
c.Error(errors.NewInternalServerError("Failed to enqueue task"))
return
}
logger.Infof(ctx, "MoveKnowledge: task enqueued: %s, asynq_id: %s, source: %s, target: %s, count: %d",
taskID, info.ID, secutils.SanitizeForLog(req.SourceKBID), secutils.SanitizeForLog(req.TargetKBID), len(req.KnowledgeIDs))
// Save initial progress
initialProgress := &types.KnowledgeMoveProgress{
TaskID: taskID,
SourceKBID: req.SourceKBID,
TargetKBID: req.TargetKBID,
Status: types.KBCloneStatusPending,
Total: len(req.KnowledgeIDs),
Progress: 0,
Message: "Task queued, waiting to start...",
CreatedAt: time.Now().Unix(),
UpdatedAt: time.Now().Unix(),
}
if err := h.kgService.SaveKnowledgeMoveProgress(ctx, initialProgress); err != nil {
logger.Warnf(ctx, "MoveKnowledge: failed to save initial progress: %v", err)
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": MoveKnowledgeResponse{
TaskID: taskID,
SourceKBID: req.SourceKBID,
TargetKBID: req.TargetKBID,
KnowledgeCount: len(req.KnowledgeIDs),
Message: "Knowledge move task started",
},
})
}
// GetKnowledgeMoveProgress retrieves the progress of a knowledge move task.
docs(api): add and fix swag annotations on handlers 将 swag 注解覆盖率从 ~88% 提升到 100%,并修复审计中发现的若干既有 注解 bug。 新增注解(24 个): - im.go: 4 (UpdateIMChannel/DeleteIMChannel/ToggleIMChannel/IMCallback) 其中 IMCallback 同时注册 GET 和 POST,两个方法都加了 @Router 声明。 - web_search.go: 1 (GetProviders) - web_search_provider.go: 6 - wechat_qrcode.go: 2 - weknoracloud.go: 2 - knowledge.go: 2 (MoveKnowledge/GetKnowledgeMoveProgress) - knowledgebase.go: 1 (ListMoveTargets) - organization.go: 3 (ListSharedAgents/ListOrgAgentShares/RemoveAgentShare) - mcp_service.go: 2 (SetMCPToolApproval/ResolveToolApproval) - chunker_debug.go: 1 (PreviewChunking) 修复既有注解 bug(12 处): - initialization.go: 10 个 @Router 路径与真实路由不符 (e.g. /initialization/kb/{kbId}/config → /initialization/config/{kbId} /initialization/fabri/tag GET → /initialization/extract/fabri-tag POST) - session/stream.go: ContinueStream 路径 /sessions/{session_id}/continue → /sessions/continue-stream/{session_id} - mcp_service.go: ResolveToolApproval 请求体 {approve: bool} → {decision: "approve"|"reject", reason?, modified_args?} 收敛响应 schema 到已有命名 struct(之前用 map[string]interface{}): - knowledge.go MoveKnowledge → handler.MoveKnowledgeResponse - knowledge.go GetKnowledgeMoveProgress → types.KnowledgeMoveProgress - web_search_provider.go GetProvider/UpdateProvider → types.WebSearchProviderEntity - initialization.go InitializeByKB → handler.InitializationRequest - initialization.go 三个 model-test endpoint → handler.ModelTestRequest 修正 organization.go 中 errors.AppError 应使用 apperrors 别名(该文件 stdlib errors 未别名化)。 不补 /files 和 /api/v1/files/presigned 内联闭包路由(文件服务,非业务 REST)。 Refs #890 #1049 #1168
2026-05-11 09:37:14 +00:00
//
// GetKnowledgeMoveProgress godoc
// @Summary 获取知识移动进度
// @Description 按任务 ID 查询移动进度
// @Tags 知识
// @Produce json
// @Param task_id path string true "移动任务 ID"
// @Success 200 {object} types.KnowledgeMoveProgress "进度信息"
// @Failure 404 {object} errors.AppError "任务不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge/move/progress/{task_id} [get]
func (h *KnowledgeHandler) GetKnowledgeMoveProgress(c *gin.Context) {
ctx := c.Request.Context()
taskID := c.Param("task_id")
if taskID == "" {
c.Error(errors.NewBadRequestError("Task ID cannot be empty"))
return
}
if err := requireTaskProgressTenant(ctx, taskID); err != nil {
c.Error(err)
return
}
progress, err := h.kgService.GetKnowledgeMoveProgress(ctx, taskID)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": progress,
})
}
feat: support multi-tag for document knowledge (#1790) * feat: support multi-tag for document knowledge - Add knowledge_tag_relations join table for many-to-many tag-knowledge mapping - Migrate existing single tag_id data to the new table - Update Knowledge struct, filter, payload types (TagID -> Tags/TagIDs) - Rewrite repository layer: SetKnowledgeTags, GetKnowledgeTags, ListIDsByTagIDs - Update tag count references to query knowledge_tag_relations - Update service/handler layers for multi-tag create/list/batch-update - Frontend: multi-select tag sidebar, multi-tag chip display, tag toggle in popup - FAQ tags remain single-tag model (unchanged) * feat(knowledge): tag edit dialog with dynamic overflow and inline creation - Add TagEditDialog component with search, multi-select, and confirm - Replace inline t-popup tag selector with dialog-based editing - Tags overflow with +N badge, visible count adapts to container width via ResizeObserver - Date/card layout: fixed date width, tags flex to fill remaining space - Add persistent new-tag input bar in dialog (Enter to create, auto-select) - Tag creation emits callback to refresh parent tag list immediately - Apply same overflow + dialog trigger to both card view and list view - Add i18n keys: tagEditDialogTitle, tagEditSearch, tagSelectedCount, tagOverflowTip, tagNewPlaceholder * fix: exclude soft-deleted knowledge from tag reference counts CountReferences, BatchCountReferences, and DeleteUnusedTags now JOIN with knowledges table to filter out soft-deleted records when counting knowledge_tag_relations. Previously they queried knowledge_tag_relations directly without the deleted_at check, causing stale tag counts after knowledge deletion. * fix: refresh tag counts after async knowledge deletion completes Add a second delayed tag list refresh (2.5s) after tag deletion to capture updated reference counts for remaining tags. The original immediate refresh handles removing the deleted tag from the list, while this delayed refresh ensures other tags' counts are correct after the async deletion finishes. --------- Co-authored-by: lyingbug <xiayula2014@gmail.com>
2026-06-25 16:18:48 +00:00
// parseCommaSeparatedTagIDs splits a comma-separated string of tag IDs and
// filters out empty strings and the "__untagged__" sentinel value.
func parseCommaSeparatedTagIDs(raw string) []string {
if raw == "" {
return nil
}
parts := strings.Split(raw, ",")
result := make([]string, 0, len(parts))
for _, p := range parts {
p = strings.TrimSpace(p)
if p == "" || p == "__untagged__" {
continue
}
result = append(result, p)
}
return result
}
feat(knowledge-base): document list filters and explicit batch-management UX Add three new optional filters to the document list under a knowledge base detail page — parse status, source/channel, and updated time range — and rework multi-select to no longer cause the card title to jitter on hover. Backend - Introduce types.KnowledgeListFilter to aggregate optional filter dimensions (tag, keyword, file_type, parse_status, source, updated_from/to) and switch ListPagedKnowledgeByKnowledgeBaseID (repository/service/interface) to accept it instead of a growing positional parameter list. - The ListKnowledge HTTP handler accepts new parse_status, source, start_time and end_time query params; time params accept RFC3339, "YYYY-MM-DD HH:MM:SS" and "YYYY-MM-DD". The repository routes source="manual"/"url" onto the type column to stay consistent with file_type semantics; other source values match the channel column. - Update the four other callers (agent_service, initialization) to pass an empty filter struct, preserving prior behavior. Frontend - Add three controls in the doc-filter-bar (status select, source select, date-range picker with future-date disabled) wired through getKnowled / listKnowledgeFiles into the new backend params. - Replace the hover-triggered card checkbox with an explicit "批量管理" mode (mirrors the session list UX): in card view the checkbox only renders while batch mode is on, entered via the per-card "..." menu; the list view keeps its leading checkbox column. Switching from list to grid auto-enables batch mode when something is already selected, so the selection stays visible. - DocumentBatchBar now stays open whenever batch mode or selection > 0, and its "取消选择" button both clears the selection and exits batch mode. API surface sync - Regenerate Swagger artifacts (docs/docs.go / swagger.json / swagger.yaml). - Update docs/api/knowledge.md with the new query parameters. - Add backward-compatible ListKnowledgeWithFilter + KnowledgeListFilter to the Go SDK; the existing ListKnowledge keeps its signature. i18n - New filter labels in zh-CN / en-US / ko-KR / ru-RU; reuse existing menu.batchManage / batchManage.cancel for the multi-select strings.
2026-05-12 10:16:34 +00:00
// parseFilterTime parses a query-string timestamp accepted by knowledge list
// filters. It supports RFC3339, RFC3339 with milliseconds, and the date-only
// "2006-01-02" form (interpreted at start of day in the local timezone).
func parseFilterTime(raw string) (time.Time, error) {
raw = strings.TrimSpace(raw)
if raw == "" {
return time.Time{}, nil
}
layouts := []string{time.RFC3339Nano, time.RFC3339, "2006-01-02 15:04:05", "2006-01-02"}
var lastErr error
for _, layout := range layouts {
if t, err := time.ParseInLocation(layout, raw, time.Local); err == nil {
return t, nil
} else {
lastErr = err
}
}
return time.Time{}, lastErr
}
type batchReparseKnowledgeRequest struct {
KBID string `json:"kb_id" binding:"required"`
IDs []string `json:"ids" binding:"required"`
ProcessConfig *types.KnowledgeProcessOverrides `json:"process_config,omitempty"`
}
// BatchReparseKnowledge godoc
// @Summary 批量重新解析知识
// @Description 按 ID 列表批量重新解析单个知识库下的多个知识条目
// @Tags 知识管理
// @Accept json
// @Produce json
// @Param request body batchReparseKnowledgeRequest true "批量重解析请求"
// @Success 200 {object} map[string]interface{} "任务已提交"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 403 {object} errors.AppError "权限不足"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge/batch-reparse [post]
func (h *KnowledgeHandler) BatchReparseKnowledge(c *gin.Context) {
ctx := c.Request.Context()
var req batchReparseKnowledgeRequest
if err := c.ShouldBindJSON(&req); err != nil {
logger.Errorf(ctx, "failed to parse batch reparse knowledge request: %v", err)
c.Error(errors.NewBadRequestError("invalid batch reparse knowledge request parameters"))
return
}
seen := make(map[string]struct{}, len(req.IDs))
ids := make([]string, 0, len(req.IDs))
for _, raw := range req.IDs {
id := strings.TrimSpace(raw)
if id == "" {
continue
}
if _, ok := seen[id]; ok {
continue
}
seen[id] = struct{}{}
ids = append(ids, id)
}
if len(ids) == 0 {
c.Error(errors.NewBadRequestError("no knowledge IDs provided for batch reparse"))
return
}
const maxBatch = 200
if len(ids) > maxBatch {
c.Error(errors.NewBadRequestError(fmt.Sprintf("too many ids (max %d per batch)", maxBatch)))
return
}
_, kbID, effectiveTenantID, permission, err := h.validateKnowledgeBaseWriteAccessWithKBID(c, req.KBID)
if err != nil {
c.Error(err)
return
}
if permission != types.OrgRoleAdmin && permission != types.OrgRoleEditor {
c.Error(errors.NewForbiddenError("no permission to reparse knowledge in this kb"))
return
}
if err := h.requireKBOwnershipOrAdmin(c, kbID); err != nil {
_ = c.Error(err)
return
}
ctx = types.WithExecutionTenant(c.Request.Context(), effectiveTenantID)
knowledgeList, err := h.kgService.GetKnowledgeBatch(ctx, effectiveTenantID, ids)
if err != nil {
logger.Errorf(ctx, "failed to get knowledge batch, kb_id: %s, size: %d, err: %v", kbID, len(ids), err)
c.Error(errors.NewInternalServerError("failed to get knowledge batch"))
return
}
if len(knowledgeList) != len(ids) {
c.Error(errors.NewBadRequestError("some knowledge entries were not found"))
return
}
for _, k := range knowledgeList {
if err := access.RejectMovingKnowledge(k); err != nil {
_ = c.Error(err)
return
}
if k.KnowledgeBaseID != kbID {
c.Error(errors.NewBadRequestError(
fmt.Sprintf("Knowledge %s does not belong to knowledge base %s",
secutils.SanitizeForLog(k.ID), secutils.SanitizeForLog(kbID))))
return
}
}
taskID, err := h.enqueueKnowledgeListReparse(ctx, effectiveTenantID, kbID, ids, req.ProcessConfig)
if err != nil {
logger.Errorf(ctx, "Failed to enqueue batch knowledge reparse task: %v", err)
c.Error(errors.NewInternalServerError("Failed to enqueue batch reparse task"))
return
}
logger.Infof(ctx, "Batch knowledge reparse task enqueued: %s, kb_id: %s, count: %d",
taskID, secutils.SanitizeForLog(kbID), len(ids))
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "Batch reparse task submitted",
"data": gin.H{
"task_id": taskID,
"reparse_count": len(ids),
},
})
}
func requireTenantAPIKeyKnowledgeBase(ctx context.Context, kbID string) error {
return requireTenantAPIKeyKnowledgeBases(ctx, kbID)
}
func requireTenantAPIKeyKnowledgeBases(ctx context.Context, kbIDs ...string) error {
return types.AuthorizeTenantAPIKeyKnowledgeBases(ctx, kbIDs...)
}
func tenantAPIKeyAllowedKBSet(ctx context.Context) map[string]bool {
scope, ok := types.TenantAPIKeyScopeFromContext(ctx)
if !ok || !scope.IsKnowledgeBaseRestricted() {
return nil
}
allowed := make(map[string]bool, len(scope.KnowledgeBaseIDs))
for _, id := range scope.KnowledgeBaseIDs {
allowed[id] = true
}
return allowed
}
func intersectKBAllowSet(base, restrict map[string]bool) map[string]bool {
if restrict == nil {
return base
}
if base == nil {
return restrict
}
out := make(map[string]bool)
for id := range base {
if restrict[id] {
out[id] = true
}
}
return out
}
func filterKnowledgesByKBAllowSet(knowledges []*types.Knowledge, allowed map[string]bool) []*types.Knowledge {
if allowed == nil {
return knowledges
}
filtered := make([]*types.Knowledge, 0, len(knowledges))
for _, k := range knowledges {
if k != nil && allowed[k.KnowledgeBaseID] {
filtered = append(filtered, k)
}
}
return filtered
}
func filterKnowledgeSearchScopesForAPIKey(ctx context.Context, scopes []types.KnowledgeSearchScope) []types.KnowledgeSearchScope {
allowed := tenantAPIKeyAllowedKBSet(ctx)
if allowed == nil {
return scopes
}
filtered := make([]types.KnowledgeSearchScope, 0, len(scopes))
for _, scope := range scopes {
if allowed[scope.KBID] {
filtered = append(filtered, scope)
}
}
return filtered
}
func tenantAPIKeySearchScopes(ctx context.Context) ([]types.KnowledgeSearchScope, bool) {
scope, ok := types.TenantAPIKeyScopeFromContext(ctx)
if !ok || !scope.IsKnowledgeBaseRestricted() {
return nil, false
}
tenantID, ok := types.TenantIDFromContext(ctx)
if !ok || tenantID == 0 {
return nil, true
}
scopes := make([]types.KnowledgeSearchScope, 0, len(scope.KnowledgeBaseIDs))
for _, kbID := range scope.KnowledgeBaseIDs {
scopes = append(scopes, types.KnowledgeSearchScope{TenantID: tenantID, KBID: kbID})
}
return scopes, true
}