* refactor(sandbox): move workspace layout and path rules into a leaf package
internal/sandbox/workspace owns the remote layout (root, input, output,
GitDir, skills root) and the lexical path rules. The sandbox root package
re-exports them through aliases, so callers keep their imports. No
behaviour change.
* feat(sandbox): add the allocation domain model
Pure types for placing a session: session/user mode, the user-mode
admission whitelist (web account or API external user only, with a fixed
fallback reason otherwise), the shared-machine identity and its digest,
the empty-retention bounds and the deployment gate.
* feat(sandbox): add machine and session admission leases
Registry of in-flight operations per shared machine and per session, with
Redis and in-memory implementations. Leases renew only while still live,
report loss at a local deadline measured from the request send time, and
Bind cancels a context when any held lease or barrier is lost. Holding or
renewing only ever extends the scope key's lifetime.
* feat(sandbox): add allocation_mode and empty retention to sandbox configs
Configs gain allocation_mode (session|user, default session) and
user_sandbox_empty_retention_days (0 = default 7, up to 90). Updates that
omit them keep the stored values. Switching a config to user requires the
deployment gate (WEKNORA_SANDBOX_USER_ALLOCATION plus Redis), exposed as
the settings.sandbox.user_allocation capability.
The gate stays closed in this build regardless of the env var: the session
manager does not place sessions by their assignment yet, so a user-mode
placement would be recorded for a session that still runs on its own
machine.
* feat(session): record the server-verified owner auth source
sessions.owner_auth_source records how user_id was authenticated when the
session was created or its owner first bound: web, API direct header or
signed token, API key, MCP endpoint, embed, IM, internal. The auth
middleware puts the source on the context, CreateSession stamps it and
ignores client input, owner binding (MCP ask, embed backfill) records the
entry's own source, and a fork inherits it. Rows from before the column
stay empty, which means unknown.
Per-user sandbox allocation reads it to tell a verified person from a
shared entry; the owner's kind follows from the source and user_id, so it
is not stored separately.
* feat(sandbox): persist session placements and shared-machine registry
session_sandbox_assignments records each session's placement once: its
config pair, the shared machine digest ('' for a machine of its own),
when it was released and when its directory cleanup is due. Mode and
layout follow from the digest. sandbox_user_machines holds the identity
behind each digest and the empty-retention clock.
ClaimPlacement writes the assignment and projects the session pin in one
transaction that locks the session row, then the machine row, before
inserting. RetireSessions releases assignments under the same locks and
writes a tombstone for a session that was never placed, so no placement
lands after a deletion began. The repository is also exercised on the
schema the shipped SQLite migrations create.
* feat(sandbox): place sessions through the allocation service
sandboxalloc decides a session's placement on first remote use and records
it with the pin: sessions that already used a per-session sandbox stay on
it, maintenance sessions are always dedicated, and only an eligible owner
on a user-mode config with the gate open shares a machine. A placed
session resolves straight from its assignment; a released one is refused.
Skill maintenance sessions record a maintenance placement and are removed
if that fails.
* fix(sandbox): retry placement when the sandbox config cannot be read
A failed config load was stored as session mode, so the session could never join a shared machine after the error cleared.
* fix(sandbox): satisfy golangci-lint on the allocation foundations
Wrap lines past 120 characters, comment exported names, and clear the two staticcheck findings so the pull request lint job can pass.
---------
Co-authored-by: hailongzhao <hailongzhao@tencent.com>
* feat(automation): scheduled agent runs with in-app notifications
Automations let a user have an agent run a task on a schedule as them.
The scheduler is database driven: every instance claims due rows with a
version CAS, so Lite and multi-instance deployments share one path.
Runs execute in deferred mode, suspend on approvals and notify the
owner; an answered prompt resumes the run from its snapshot. Standing
grants are promoted from approvals past runs asked for, bound to the
agent configuration and the owner's role.
Adds the automation, run and notification APIs, the automation.*
assistant operations, and regenerates the Swagger document.
* feat(frontend): automations page and notification bell
Adds an Automations page to the sidebar: a list with schedule, agent,
next run and last status; an editor with schedule presets, a custom
cron field, timezone and a live preview of the next runs; and a detail
drawer with run history, links into each run's conversation and the
standing approvals the owner can grant from past approval requests.
The top-right bell now merges pending invitations with in-app
notifications and polls for new ones.
* fix(automation): let the assistant schedule tasks and match the settings UI
The assistant never searched for automation operations, one-time times failed unless they were RFC3339, and the create, detail, and notification surfaces did not match the rest of the app.
* refactor(agent): route approval decisions through a single policy
Operations, assistant write tools, MCP tool approval, delegated-child
approval and the child tool guard each compared access levels on their
own. They now ask policy.Decide, which maps an action's risk and the
run's rules to allow or ask. Behaviour is unchanged: MCP tools still
follow only the workspace per-tool flag and delegation, and a write that
reaches a read-only run still asks.
Add design docs for the agent permission model and scheduled automation.
* refactor(agent): replace interactive flags with a run mode
Runs are attended, deferred or unattended. Unattended runs refuse every
approval, including MCP approvals that used to wait out the timeout;
deferred runs suspend at once.
* feat(agent): apply access levels to MCP tools and every agent
MCP tools get a risk: the workspace's explicit setting, else the service's
readOnlyHint, never lower than a risk the service declared before. The
run's access level now decides MCP calls as it does operations; read-only
runs neither see nor run tools that change data. Ordinary agents get a
configurable ceiling that defaults to auto_write, and delegated children
take the lower of their parent's level and their own ceiling instead of
asking for every MCP call.
* feat(agent): persist approval grants with session/automation scopes
Remembered "allow for this conversation" approvals move from prompt history
into an agent_grants table keyed by root session (or automation binding), so
delegated children share the root grant and unattended runs honour it.
MCP write tools now offer the grant, keyed by service, tool and input schema.
Users can list and revoke their grants from the chat header.
* feat(agent): acting-via identity, decision logs and grant lapse reasons
Principal gains ActingVia so work done on a user's behalf (automations) is
told apart in audit details and policy decision logs. Every non-read policy
decision is logged with its action, risk, level, mode and verdict.
Automation grants bind to a hash of the agent setup, owner role and access
ceiling; a grant that no longer applies asks again and the card says why.
* docs(agent): record permission model implementation status
* chore(handler): check c.Error in agent grant handlers
* chore(handler): check c.Error in MCP tool policy handler
* fix(agent): raise MCP observed risk atomically and scope worker access
- Compare observed_risk inside the upsert so a stale lower observation
cannot overwrite a higher one recorded concurrently.
- Delegated workers use the same conditional level as attach: the
assistant ceiling applies only under an assistant parent.
- Mock @/api/assistant in useModalShell tests; gofmt internal/mcp/client.go.
* docs(agent): allow destructive pre-grants only in automation scope
Decide against a level that skips every prompt: Always stays
unwaivable and destructive actions may only be pre-approved per resource
when an automation is set up. Note that automation runs must look up
both automation and session grants.
* feat(agent): standing grant scope and risk-bounded grants
Grants record the risk they were approved for and never cover a riskier
call. Destructive calls are now named for matching, so an automation's
standing grant can cover one, but the card still offers to remember only
writes. The gate looks up the run's own scope and then its standing
scope; approvals during a run are written only to the run's scope.
* fix(agent): let open_page finish the turn with the answer above it
Split page navigation into a separate view_page tool, keep the answer
written before an open_page button as the final reply, and tidy the
grouped progress updates in the timeline.
* style(assistant): align child agent rows, tabs and task brief with the timeline
Child task rows become single-line timeline steps with a light sweep while
running, tabs pulse and shimmer for running children, collaboration tools
share the agent mark, and the task brief card is lighter and renamed.
* fix(agent): deliver child agent messages as tagged user input
Child results were injected as assistant turns, so the parent read the
envelope as its own words and imitated it in visible replies. Deliver them
in <agent_message> blocks in the user position, escape spoofed closing tags,
and tell the parent never to reproduce the envelope.
* fix(ci): wrap the page button test fixture within the line limit
* feat(assistant): add persistent multi-agent collaboration and live task views
* fix(ci): wrap runtime notice message append
* fix(agent): preserve collaboration results and prevent duplicate execution
* fix(agent): fence panic followups and preserve approval timelines
* test(frontend): stub connector labels in assistant refresh fixture
* fix(migrations): avoid collaboration migration collision with main
* fix(assistant): preserve child continuations and artifact access
* fix(frontend): align artifact and icon checks with updated UI
* fix: enforce child approvals and finalize interrupted collaboration runs
* feat: support inherited temporary agent workers
* docs: clarify inherited worker scope and lifecycle
* fix: harden assistant retrieval and final delivery
* fix(agent): keep closed child prompts continuable and renew active deadlines
Expired child approvals were looked up by the child session, so the parent group stayed open and the run became needs_attention. Active collaborations also expired one hour after creation.
* fix(lint): clear golangci-lint findings on the collaboration PR
The previous CI run failed on line length, gofumpt, unchecked closes, and an unused dial parameter.
* fix(ci): use the public npm registry for frontend dependencies
* fix(agent): address collaboration review findings
- keep ordinary fallbacks when a turn delegated no work
- throttle lease/deadline heartbeats and drop duplicated child answers
- force-close or compact aggregates that exceed the size limit
- clamp completion budget to the model output limit
- honor prompt_suspend for non-collaboration tools
- clean up collaborations and child sessions on session delete, prune old rows
- bound concurrent child executions globally
- retry prompt classification and tolerate transient heartbeat errors
- scope prompt history to listed messages, reject nil tenants
* feat(assistant): let the assistant find skills and MCP services on the web
Enable web_search/web_fetch for the WeKnora assistant so it can locate a
skill source or MCP endpoint from a description, with prompt guidance on
sources, injected page text, console-only credentials and a missing search
provider. mcp_service.create now always asks the user.
Agent trials no longer stall on prompts nobody can answer: tool approvals
are refused at once and OAuth falls back to the non-interactive notice.
* fix(ci): wrap the unattended approval test constructor
golangci-lint rejects the NewGate call at 127 characters.
* fix(assistant): polish interaction cards and stabilize composer context
Localize operation labels across all six UI languages and expose answer copying in the assistant panel. Refine question and page-link cards with a single open/return action, and keep the current-page context row at a stable height.
* feat(assistant): add common data source, chunk and knowledge base operations
* feat(assistant): support parsing configuration and batch FAQ updates
* feat(assistant): add MCP tool directory query and sync operations
* feat(assistant): manage web search providers and data source sync settings
* feat(assistant): add model configuration copy operation
* feat(assistant): add workspace profile members and system information operations
* feat(assistant): add system administrator queries and runtime diagnostics
* fix(frontend): polish assistant and resource card UI
Refine assistant composer layout, context controls and reply actions, including narrow-window alignment. Unify knowledge base, agent and shared-space cards with consistent icons, hover feedback, favorites, menus and compact localized statistics.
* fix(assistant): preserve concurrent settings and exclude upstream error secrets
* fix(knowledge): leave the root span open while a retry is left
FailSpan closed the attempt root as failed on any main-stage failure, but
asynq retries reuse the payload and record onto the same attempt. Once the
root is terminal FinalizeAttempt returns on its guard, so a retry that
succeeds leaves the root failed while every child span and the document
itself report completed.
Defer the root's terminal status until the runner has no retry left, using
the same counters ProcessDocument already computes isLastRetry from.
* fix(knowledge): distinguish terminal span failures from retryable errors
---------
Co-authored-by: wizardchen <wizardchen@tencent.com>
* feat(assistant): let the assistant check MCP services and retrieval
Add a probe risk for operations that change nothing but do real work
(connecting to a service, running a retrieval). Probes use POST, run
without approval at every access level, and are capped per run.
Open three operations on top of it:
- mcp_service.test: connect with the saved settings and report why not
- mcp_service.list_tools: list what a service offers before binding it
- knowledge_base.search: raw hybrid recall with thresholds, to explain
why a document is or is not found
x-agent can now name one method when a handler documents several, and
catalog parameters accept numbers.
* feat(assistant): let the assistant try an agent it set up
Add try_agent: the assistant asks an agent one question the way a user
would and gets back its answer, the tools it called and the documents it
cited, so it can check a setup before calling it done.
- The trial runs as the signed-in user in a new agent_trial session kind,
which ordinary listings already exclude and the API cannot create, and
the session is removed afterwards. Runs are non-interactive, so tools
that would ask the user are refused. Long-term memory is untouched: it
is written only by the HTTP handler.
- The assistant itself, the Wiki fixer and the skill installer cannot be
tried, nor any agent granted the operation catalog.
- A trial spends model calls and runs the agent's own tools, so it is a
write for the access level: confirm asks, auto_write runs, read_only
does not offer it. The confirmation card names the agent and question;
ConfirmedTool now lets a wrapped tool supply that text.
- At most 3 trials per turn, 4 minutes each; the tool timeout is raised
above that. Answers, tool errors and references are capped.
- The runner is bound to the session service after the container builds
it, since the session service depends on the agent service.
* feat(assistant): let the user allow similar changes for the conversation
The confirmation card for a recoverable change now offers "allow this for
the rest of the conversation". Once chosen, later calls of the same kind
in the same session run without asking, so a batch tidy-up no longer
needs a click per item.
- What a grant covers is derived on the server, never taken from the
model: the same catalog operation on the same knowledge bases (a
document's knowledge base comes from the target read) or the same
agent; the same Wiki tool on the run's Wiki knowledge bases; trials of
the same agent. Deletions and operations without such a scope, such as
creating a knowledge base, always ask.
- No new storage: the gate looks for an earlier approved prompt in the
session with the same grant and allow_in_session set, for the same
tenant and user. Grants therefore survive suspend/resume and replicas,
and end with the conversation. A failed lookup asks again.
- The response validator accepts allow_in_session only on approval and
only when the prompt offered a grant, so a client cannot widen it.
- The card shows the scope in the user's language. The model is told
such calls may run without a card and that deletions always ask.
- describeTarget now returns its target read so the grant reuses it
instead of reading again.
* feat(assistant): tell the assistant about settings pages and chat answers
Pages now report which page is open and, for the agent editor, which
section. The model and MCP settings name the model or service open for
editing, and chat answers gain an "ask the assistant" button that
attaches that answer. The backend resolves these for the assistant only:
models and MCP services in the caller's tenant without endpoints or
credentials, and messages through the caller's session read access, with
the question, an answer excerpt and cited sources quoted as data.
* feat(assistant): link the user to pages and filled-in forms
The assistant gains open_page, which shows a button to a knowledge base
or document, a Wiki page, an agent's editor at a tab, a model or MCP
service to edit, or a new model or MCP service with its form filled in.
Targets are read through the operation catalog as the user, so a link
never points at something they cannot open. Drafts take no credentials
and only http(s) endpoints without user info; the card shows the
endpoint, and the user enters keys and saves the form themselves.
* feat(assistant): manage MCP services, model names and skills
* fix(assistant): prefill model drafts on initial navigation
* feat(assistant): document tags, model catalog reads, clearer cards, live page refresh
- Operations project lists of objects; knowledge.get/list report tags.
- model.get shows provider, endpoint and capabilities; new
model.list_providers and model.get_provider read the model catalog,
including vendors an admin added.
- open_page and ask_user guidance: offer page buttons whenever the next
step is the user's, word choices for the user.
- Chat cards: redesigned open-page card pinned under the final answer,
ask-user inputs in the dock style, approval card with aligned fields,
translated labels and a question built from the operation summary.
- Open pages reload after assistant changes: deletes and moves wait for
the background task, Wiki edits now report their changes, KB list
counts, tags and chat model selectors refresh.
- The assistant panel stays open across reloads within the tab.
* fix(ci): format assistant operation code and wrap long lines
* feat(assistant): let the assistant see, fill and open the page beside it
- read_page / fill_page tools answered by the browser over a page_action prompt,
with refs, redaction, in-place text edits, undo card and a page-access switch
- composer shows the open page, dialog and selection; a selection bubble and an
editor toolbar entry ask the assistant about the selected text
- edits scroll into view with a highlight and an inline undo bar
- open_page reaches any settings section, toolbox tool and list page, and can
navigate there itself to read it, keeping the button when edits are unsaved
* feat(assistant): let the assistant open the tab it needs
A visible tab can be selected and re-read, and system settings can open straight to user management, so the next step is no longer blocked on the wrong tab.
* feat(assistant): expose read-only conversation operations
Add session.list, message.list, message.search and
message.chat_history_stats to the operation catalog, restrict the
sessions and messages areas to non-mutating operations, and search
messages with the raw query instead of the log-sanitized one.
* style(chat): restyle open-page and page-edit cards
* fix(ci): comply with assistant card styles and Go line limits
* ci(build): add manual docker build workflow
Co-Authored-By: Claude <noreply@anthropic.com>
* feat(datasource): deep-adapt Feishu/Lark sync with folder mirror, block parsing and embedded objects
- folder mirror: wiki/drive connectors emit path-qualified FileName so
knowledge lands in KB folders mirroring the Feishu tree; shortcut
subtrees deduped; sanitized directory names; legacy datasources
converge via one-shot resync marker (incremental sync upgrades to
full once, then clears)
- parse mode: replace FEISHU_DOCX_PARSE_MODE env with per-datasource
settings.parse_mode (blocks default, export escape hatch); frontend
selector + 5 locales; zero-migration read-time fallback
- block-level GFM: extend docx block coverage (callout/grid/iframe/
board/mindnote/agenda/synced blocks), rich text elements (links,
inline code, KaTeX equations, mentions), real ordered-list numbering,
code language mapping, merged-cell fill, truncation note
- embedded objects: images (gated off multimodal toggle) and boards
(download_as_image, 403-degraded) stored as knowledge with
weknora-img://<n> markers resolved in the document-processing
pipeline via knowledge FilePath; document attachments whitelisted
(pdf/md/xls(x)/csv/doc(x)/ppt(x)) as standalone knowledge in the
parent folder with bidirectional parent/child metadata and filename
list in the body; videos skipped with placeholder + source link
- golden baseline explicitly re-recorded; docs (.env.example,
docker-compose, docs/*, website-docs) synced
* fix(datasource): address Feishu deep-adaptation smoke-test findings
- folder mapping: drop the space/root-folder name prefix — the selected
sync root maps to the knowledge-base root, subdirectories stay relative
- docx blocks: render view(33) blocks silently as containers (children
only), removing the stray '[飞书块: 视图]' placeholder before file lists
- sheet inline tables: fetch merge ranges via sheets/v3 sheets/query and
fill the top-left value across the merged region (closed-interval
interpretation, flagged for real-environment verification)
- knowledge list: hide embedded image/board rows (metadata
embedded_image=true) from the document list and folder-tree counts;
rows remain for VLM indexing and marker resolution; search untouched
- frontend: hydrate protected images (resource:// etc.) in the document
preview so embedded Feishu images/boards actually render
* fix(datasource): resolve embedded image markers at ingest time
The weknora-img://<n> markers were only resolved during document
processing, so chunks carried real resource:// URLs while the stored
markdown file and source_content kept raw markers — file preview
showed blank images. Resolve them in ingestItem before
CreateKnowledgeFromFile (children are emitted first, so image rows
with FilePath already exist); markers with missing children are kept
for the ProcessDocument fallback to degrade. Stored file,
source_content and chunks now agree. Existing datasources converge on
the next full re-sync (update=delete+recreate).
* feat(datasource): resolve Feishu mention users to real names at ingest
docx mention_user elements only carry an open_id, so they rendered as
a generic '@成员'. Resolve the display name via
GET /contact/v3/users/:id (user_id_type=open_id) while generating the
markdown during FetchDocxWithBlocks — before storage, per user
decision; the frontend performs no lookups. A per-sync closure caches
positive and negative lookups; permission errors and empty names
silently degrade to '@成员' (debug log only, ingest never blocked).
Requires one of the contact read scopes (e.g.
contact:user.base:readonly) on the Feishu app.
* refactor(datasource): polish round — defect fixes and structural cleanup
- attachment placeholder patching now targets the unique
'- weknora-att://<token>' marker line rendered per attachment instead of
matching by display name, so an identical earlier bullet is never
replaced by mistake (regression-tested)
- markdown link targets with spaces or parens are percent-escaped
(iframe / mention_doc / inline links), keeping them parseable
- drive folder-tree walking consolidated into core.WalkDriveTree,
deleting the 174-line copy in drive/paths.go
- parse mode threading made explicit: DocxFetchInput.ParseMode replaces
the private client field (connector entry resolves via
ParseFeishuConfig and passes it through ops)
- maxFeishuDownloadBytes restored to a const; the oversize-degrade test
now declares an over-cap Content-Length and downloadRawBytes rejects
early on the header
* refactor(datasource): align Feishu image handling with the platform image pipeline
Replace the image-as-separate-knowledge-row channel with the platform's
orthodox flow: the connector downloads image/board bytes at fetch time and
embeds them in the parent markdown as base64 data URIs; the document
processing image resolver (image_resolver.ResolveAndStore, the same stage
used for parsed PDFs/Word) stores them on the tenant file service, swaps in
persistent provider:// URLs and produces OCR/caption child chunks when a VLM
is configured.
Removed with the marker pipeline:
- weknora-img:// ingest resolution in ingestItem
- the ProcessDocument Step-1.9 marker hook
- the document-list/folder-tree filter for embedded_image rows
- the feishu-specific runtime parse_mode backfill; legacy data sources are
now stamped by migration 000096 (sqlite 000017) which writes the one-shot
resync_required marker — the generic full-upgrade + clear consumption stays
Attachment (PDF/Word/md) sub-items are unchanged.
* style: gofmt test files
* fix(datasource): resolve Drive sub-selection kind from the root listing
A single-file Drive selection (rootFolderToken:fileToken) was probed with
folder APIs before falling back: folder meta returned 91202 and the folder
list 1061002 on every sync, logging API errors for a working configuration.
listDriveFilesForResource now walks the root subtree first and reads the
selected node's kind off the listing: a file filters straight out of the
already-fetched results (zero error calls), a sub-folder still gets its
dedicated walk, and only a token missing from the listing (partial listing /
permission edge) keeps the legacy probe + fallback.
Also pins sub-folder selection semantics with a dedicated test.
* fix(datasource): address review findings across the Feishu deep-adaptation branch
Four parallel reviewer slices audited the branch; this applies the accepted
findings.
Content fidelity (blocks rendering):
- todo blocks parse style.done — completed items render "- [x]" instead of
always unchecked
- code fences size past the longest backtick run in the content, so a line
of ``` inside code can no longer close the fence early
- ordered-list "auto" numbering only resets on a sibling of the last item;
child blocks rendered flat between items no longer renumber the run
Image pipeline:
- inline base64 images are capped at the document-processing resolver's
10 MB budget; larger images degrade to a placeholder instead of leaving a
permanent raw-base64 blob in stored markdown
- image markers carry a per-document nonce so user-typed look-alike text
can never be patched in place of a real marker
- attachment marker patching anchors on the token's line end, closing the
token-prefix collision
- SupportedImageExt recovers image/svg+xml (board exports), which the
platform resolver already stores natively
Sync correctness:
- clearResyncMarker re-reads the row before writing: a long upgraded sync
no longer risks reverting concurrent user edits with a stale full-row
update
- wiki EditTime keys on max(obj_edit_time, node_edit_time): pure
moves/renames re-file the document on the next incremental sync
- file-typed wiki/drive base names are sanitised; a "/" in a title can no
longer fake an extra folder level
Docs/tests/comments:
- datasources docs rewritten to the v3 image contract (no image rows,
no image_map, no parse_mode backfill claim)
- DataSourceEditorDialog drops settings.parse_mode when backtracking to a
non-Feishu connector type
- stale comments corrected (types.go parse-mode transport, repository
folder-counts, wiki List partial-error branch, test headers); regression
tests added for todo done, fence sizing, ordered numbering, svg sniff
* fix(datasource): repair markdown conversion defects found in live smoke test
Live re-sync of the all-block-type Feishu test document surfaced three
converter defects:
- Code blocks: the closing fence reused the opening fence string, so a
tagged block ended with ```java — CommonMark requires a bare closing
fence, and every renderer left the block unterminated. The closing
fence is now backticks only.
- Feishu heading7-9 emitted 7-9 hash marks; GFM stops at H6, so those
lines rendered as literal '#######' text. They now degrade to bold.
- The docx API percent-encodes link targets (http%3A%2F%2F...); escapeURL
now reverses that encoding before markdown-escaping, so stored links
point at real URLs instead of percent-encoded strings.
Verified against the live document via a throwaway API probe: the
'i|g|k' table cells questioned during review are the document's own
content (the sheets copy says i|j|k; the two docx tables genuinely
contain 'g'), not a converter bug.
* fix(frontend): render GFM task lists in document preview
Task list items (- [x] / - [ ]) rendered as plain bullets: marked emits
<input type="checkbox"> for them, but the preview DOMPurify config's
ALLOWED_TAGS allowlist has no 'input', so the element was stripped whole.
The preview renderer now overrides checkbox to emit a styled
task-checkbox span (class/attr both allowlisted) and the preview styles
draw the box with a check mark, hiding the list bullet via :has().
Same gap exists in the chat markdown surface; left untouched there.
* fix(datasource): crop blank canvas borders from whiteboard exports
The board download_as_image API renders the WHOLE board canvas, not the
content bounding box — editors routinely leave the canvas far larger than
the drawing, so board/mindnote/diagram exports surfaced with large blank
areas below the content. The API has no crop parameter, so the connector
now trims near-uniform blank borders after download (bottom-right pixel
seeds the background color, 14/255 per-channel tolerance absorbs JPEG
noise, 8px margin kept). PNG and JPEG are re-encoded; anything
undecodable, fully blank, or already tight passes through unchanged, and
oversized images (>64MP) skip the scan to bound memory.
* fix(datasource): require corner majority before trimming board exports
The blank-border trim seeded the background color from the bottom-right
pixel alone. A large solid shape reaching that corner would seed the
background with its own fill color, and fully-filled rows could then be
trimmed as blank — cutting real content. The background color is now the
majority of the four corner pixels (>=3 must agree); on a split vote
content reaches the corners and the image passes through untrimmed.
Content visible against the background is untouched either way: a row or
column survives if even one pixel differs from the background by more
than the 14/255 JPEG-noise tolerance.
* fix(datasource): widen board trim margin and lower JPEG quality to 80
The 8px margin read as a tight crop — a 32px white frame now visually
bounds the content region. JPEG re-encode quality drops 90 -> 80 to keep
the re-encoded size closer to the original export.
* feat(datasource): timeline widget Markdown degradation + table column alignment
Two content-fidelity gaps from the live smoke test:
- 文档小组件 (add_ons, block_type 40) carry their full data inline in
record; there is no server-side render to download. The timeline
component (component_type_id blk_6358a421bca0001c...) now degrades to
a Markdown list (- **time · title**:text), honoring contentShow and
omitting empty segments; unknown component types and malformed records
keep the previous placeholder note.
- docx text blocks carry style.align (1 left / 2 center / 3 right,
absent unless the author set it). Native-table rendering now collects
per-column alignment from the first explicit cell and emits GFM colon
separators (:---: / ---:). Embedded sheets/bitable keep the plain
separator — their value APIs expose no alignment.
* feat(datasource): show document titles for 云文档 mention links
The docx renderer emitted mention_doc references as [url](url) because
the payload carries no title. Feishu doc URLs now emit a
[weknora-docname://token](url) placeholder and FetchDocxWithBlocks
resolves the titles in one drive metadata batch call
(POST /drive/v1/metas/batch_query, docx/doc/sheet/bitable/wiki/...),
patching the link text to [文档名](url). Refs whose metadata cannot be
fetched — no permission (970003), deleted/mismatched (970005), API
absent — degrade to the previous URL-as-text form with a warn log.
This is display-only: referenced docs are not pulled as sub-documents
(deferred design lives in the task PRD).
* docs(datasource): document mention rendering enhancement and drive rename limitation
- Add optional mention scopes (contact:user.base:readonly,
drive:drive.metadata:readonly, board:whiteboard:node:read) with
degrade behavior to the Feishu permission tables
- Describe mention_user real-name lookup, mention_doc title backfill
and timeline widget placeholders in the blocks rendering flow
- Document the Drive known limitation: folder renames / file moves do
not bump modified_time, so incremental sync keeps the old KB folder
structure until a full sync; Wiki sources are unaffected
- Clarify the directory-mapping wording in website-docs to distinguish
Wiki (rename-aware) from Drive (rename-blind) sources
* docs(datasource): add blocks vs export tradeoff summary to website-docs
* docs(datasource): document docx block-type coverage for blocks mode
- Add a full block-type support table (block_type 1-52 grouped) to the
datasource dev doc: text/heading/list/task/quote structures, code
fences with language aliases, containers (callout/quote/grid/view),
native tables with merged-cell splitting (top-left value fill) and
column alignment, embedded sheet/bitable converted to in-document
Markdown tables, image/board inline pipeline, attachment whitelist,
iframe links, timeline add-on degradation and the placeholder set
- Summarize the same coverage in the drive user guide, the wiki
quick-start doc and website-docs; fix the stale claim that board
blocks degrade to placeholders (they ride the image pipeline now)
* style: resolve diff-scoped lint findings across feishu packages
- Wrap over-length signatures and calls (lll, max 120)
- Add doc comments to exported Block* payload types (revive)
- Rename unused closure parameters to _ (revive)
- Check w.Write / resp.Body.Close error returns (errcheck)
- Apply De Morgan rewrite in docname token validation (staticcheck)
- gofumpt-format touched files
golangci-lint run --new-from-rev=main ./... now reports 0 issues.
* ci: drop fork-only docker-build workflow
The manual docker-build workflow lives on the fork's main and is not
part of the upstream contribution; it entered the branch through the
fork-main merge.
* fix(migrations): renumber feishu resync migrations to avoid version collision with upstream
Upstream added 000017_dingtalk_stream_only (sqlite) and 000096_dingtalk_stream_only
(versioned) before our merge, colliding with our 000017/000096 feishu resync
migrations. golang-migrate rejects duplicate versions. Renumber to the next free
slots (sqlite 000027, versioned 000108) and update comments + test constant.
* fix(migrations): renumber feishu resync migrations ahead of upstream 000027/000108
Upstream main now also claims sqlite 000027 and versioned 000108
(session_sandbox_config_tenant), colliding with our just-renumbered
resync migrations. Move to 000028 / 000109.
* fix(feishu): address review — deprecated env fallback and upgrade notes
- Keep FEISHU_DOCX_PARSE_MODE as a one-release deprecated fallback when a
data source has no per-source parse_mode (deprecation warning logged);
annotate it in .env.example / docker-compose.yml instead of removing.
- Point stale migration-number comments at the final numbers
(versioned 000110 / sqlite 000030) in datasource_service.go and tests.
- website-docs: add Feishu upgrade notes (env deprecation, default mode
flip to blocks, one-shot full resync with embedding/VLM recompute);
refresh 24-feishu-drive.md parse-mode section to the per-source
setting and new blocks semantics.
* docs(feishu): document necessary and optional connector permissions
Restore the permission matrix lost with the docs/ removal: necessary
scopes (wiki/drive/export/docx) with missing-permission symptoms and
optional enhancement scopes (embedded sheets/bitable, board export,
mention user/doc rendering) with their degrade behavior, in
10-datasource.md's Feishu section; make 24-feishu-drive.md list the
three necessary drive scopes and link to the full table.
* Revert "docs(feishu): document necessary and optional connector permissions"
This reverts commit 3be19cb1b656b3596f2cb6afb2cda8c2a1d12be1.
* docs(feishu): permission matrix by connector, parse mode and necessity
Necessary-scope tables split by connector (feishu/lark wiki vs
feishu_drive/lark_drive) with blocks/export applicability columns and
missing-permission symptoms; optional enhancement scopes with their
degrade behavior; scope names cross-checked against the Feishu open
platform API docs (files/folder list, medias download, export tasks,
metas batch_query). Full matrix lives in 10-datasource.md; the drive
guide mirrors its own table and links back.
* test(feishu): adapt mention_user_test to upstream retryTestServer signature
* feat(feishu): mirror the sync root (wiki space / drive folder) as a top-level KB folder
So a knowledge base linking several feishu sources can tell them apart at a
glance: syncing folder 测试1 yields 测试1/... and syncing wiki space
飞书知识库同步测试 yields 飞书知识库同步测试/.... Root-name resolution
failure falls back to the previous root-less behaviour without failing the
sync; existing sources converge through the one-shot resync marker.
* refactor(feishu): cache wiki space folder prefix per run, refresh stale comments
Review follow-ups for d012e593f: cache the sanitized space prefix per spaceID
for the whole sync run (K selected spaces now cost one ListWikiSpaces paging
pass instead of K), fix the misleading warn wording, and realign the
WalkDriveTree / driveFolderName doc comments with root-mirror semantics.
* docs(feishu): drop stale and duplicated comments from the deep-adaptation
- board.go: trimBoardImage no longer claims a bottom-right seed (the code
votes the background over the four corners)
- shared.go: rewrite the FetchDocxWithBlocks note (images/boards inline via
base64 now; removes a stale-marker splice artefact)
- markdown.go: drop an internal task-number leftover
- datasource_service.go: collapse the ProcessSync/processSyncStreaming notes
duplicated verbatim from resyncRequired's doc comment, keep the call-site
why (marker cleared only on success)
- datasource_resync_test.go: drop the obsolete 'backfill' wording
* feat(i18n): 添加解析模式及其提示信息到繁體中文語言包
* fix(frontend): use radius token for task checkbox; fix simplified chars in zh-TW parse mode
CI guard fixes: the PR-added task-checkbox style pushed the radius-literal
count to 161 (> baseline 160); the new zh-TW keys missed the locale parity
audit (user's dc6fdcff9) — also normalise the simplified 文档 leftovers.
* fix(feishu): preserve sync scope, nested content, and legacy settings
Cover shortcut selection, ancestor path changes, nested containers and table boards with regression tests. Avoid redundant Drive traversal, repair resync migrations for legacy settings, and preserve inherited parse modes. Bound board image dimensions before decoding.
* docs(feishu): clarify shortcut scope and incremental path tracking
* Fix Feishu sync reconciliation and embedded media regressions
* Bound Feishu table rendering by actual cell data
---------
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
* feat(image): configurable image pipelines, rebuilt on current main
Rebuilds the image-pipeline work on top of the current main, carrying
only the pipeline and request-side changes:
- The hard-coded image flow becomes registry-driven pipelines (default /
smartocr), selectable per knowledge base, with a frontend panel and
per-action thinking switches addressed as action-level keys
(caption.thinking / ocr.thinking) declared once and carried into every
pipeline.
- Request-side support: VLM.PredictWithOptions carries a per-call
thinking switch through every implementation and decorator, including
the background concurrency wrapper.
- OCR failure handling follows main's #4132 semantics: invalid output is
rejected and recorded (ocr_status / ocr_error_code / .ocr subspan)
without retrying the whole image; caption/observation failures get
symmetric subspans instead of leaving the image span green.
- Permanent VLM failures skip the asynq retry budget; a run that
produced nothing fails honestly instead of passing as skipped.
- UI and locale fixes travel with the panel.
Concurrency, rate limiting and circuit breaking are NOT part of this
branch: they stay with the existing system limiter.
* fix(image): address pipeline configuration and execution regressions
* fix(image): align pipeline overrides and validation semantics
* style(image): keep the new pipeline code inside the lll and gofumpt gates
---------
Co-authored-by: tayadwx <tayadwx@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
* feat(assistant): let the assistant manage knowledge bases
Create, update, and delete knowledge bases, tags, and manual Markdown,
and show those confirmations as labeled rows with model names.
* fix(assistant): satisfy lint on knowledge base operations
Check new error returns, wrap lines past 120 characters, and document the exported tag request types.
* fix(assistant): enforce knowledge base settings permissions and preserve patch fields
* feat(assistant): let the assistant manage agents
Expose custom agents to the operation catalog (list, get, create, copy,
update, delete) plus read-only model and MCP service lookups, so the
assistant can set up agents end to end.
- Add PATCH /api/v1/agents/:id. PUT replaces the whole config, so a
one-field change from the assistant would wipe the rest; PATCH only
overlays the fields it carries and reuses the PUT validation path.
- Add x-agent-detail so long fields such as the system prompt are only
projected for single-object reads, not lists.
- Add label_param so a create without a target is labelled by its name.
- The approval card lists agent setting changes and resolves model,
knowledge base and MCP IDs to names.
- Deny sharing, publishing channels, credentials and OAuth routes; model
and MCP endpoints, headers and secrets are never projected.
- Update the assistant prompt, starters, API docs and Go SDK.
* feat(assistant): list skills and configure agent skill scope
- Expose usable skill names for an agent sandbox without exposing skill
administration or connection settings to the model.
- Validate PATCH selections against the workspace sandbox usable set so
invented names and missing sandbox selections cannot be saved.
- Show skill changes in approvals and align the assistant prompt, API
documentation, and Go SDK with focused refusal and projection tests.
* feat(assistant): isolate conversation history
- Keep assistant conversations out of ordinary session lists, search, artifacts and delete-all cleanup.
- Add private, paginated assistant history with session switching, confirmed deletion and stale-session recovery.
- Backfill session kinds safely on Postgres and SQLite, preserve kinds on forks, and align API docs and SDK coverage.
* feat(assistant): refresh pages after successful data changes
- Carry decoded mutation targets through live tool-result events without
exposing refresh metadata to the model or persisted chat history.
- Coalesce page and selector refreshes, update document drawers, and warn
about changed agents while preserving open editor drafts.
- Cover mutation, approval, stream, lifecycle and cache behavior with Go
and Node tests using the existing frontend runner and component fixtures.
* feat(assistant): add agent page context and resource scope limits
- Attach verified agent context and persist personal scope across turns and approvals.
- Enforce resource boundaries before operation and Wiki approvals, including edited arguments.
- Add scope controls, translations, API and SDK support, and regression coverage.
* refactor(assistant): remove the scope limit
The scope picker confused users and duplicated what RBAC and the access
level already enforce. Keep the agent page context: the agent editor
still publishes agent_id and the backend still verifies it.
* feat(assistant): render operation and product-doc results
Show find/run operations and WeKnora docs as structured cards instead of raw JSON.
* feat(assistant): default new agents to smart-reasoning
Quick-answer cannot call MCP, and agent.update could not change the mode. New agents now start in smart-reasoning, and a patch can switch agent_mode.
* fix: resolve assistant management CI failures
* fix(agent): let the WeKnora assistant search without its own rerank model
Every assistant run with a knowledge base in scope failed with "rerank
model is not configured: please set rerank_model_id on the agent". The
assistant lists search_knowledge, and agents with that tool must name a
rerank model; but the assistant is hidden from agent management, so no
one can set one.
Internal built-in agents now take the workspace's rerank model: its
default active one, else its first active one. With none, search_knowledge
keeps retrieval order, as it already does when reranking fails.
User-configured agents still have to name their rerank model.
UsesFallbackChatModel becomes UsesWorkspaceModelFallback, since it now
covers both models.
* fix(ci): wrap assistant rerank fallback log calls
* feat(agent): let the WeKnora assistant read the bundled documentation
Embeds the website-docs pages (01-07) into the server and adds
search_weknora_docs / read_weknora_doc for the built-in assistant, so it
answers how WeKnora works from the docs of the running version.
- pages split into sections with the site's VitePress anchors; Mermaid
dropped, screenshots reduced to captions, links rewritten to public URLs
- in-memory BM25 over sections, with Han character pairs and whole
identifiers such as OLLAMA_BASE_URL or v0.8.3
- granted to the built-in assistant by ID, like the operation tools; the
docs are public, so no signed-in user is required
- tests check every embedded page parses and every internal link resolves
* fix(agent): read long doc sections to the end and keep docs on a broken page
- read_weknora_doc takes an offset: a section too long for one read is cut
at a line break and returns next_offset, so leaf sections such as the
model field reference are readable to the end instead of losing the tail.
- Reads follow the registry's output budget (capped at 8000 runes).
- Percent-encoded anchors, as a browser copies them, and http:// doc URLs
resolve.
- productdocs.Load leaves out a page it cannot parse and reports it, so one
broken page no longer withholds the documentation tools.
- App CI runs on changes to the embedded doc pages and the sidebar config,
where the parse and link tests now apply.
* feat(agent): add the built-in WeKnora assistant with an operation catalog
Adds builtin-weknora-assistant, which inspects and manages WeKnora with the
signed-in user's permissions:
- find_operations / run_operation over an allow-listed API operation catalog,
dispatched in-process through the real router as the user
- builtin approval for write/destructive operations, refused when
non-interactive
- agent attribution in knowledge base activity, including async tasks
- page_context request field, narrowed to the turn's search targets and
rendered into runtime_context with model handles
* refactor(agent): compile the operation catalog from x-agent Swagger annotations
The catalog was a hand-written copy of what the swag annotations already
describe: routes, parameters, enums and response shapes. It now compiles
from the Swagger document embedded in the binary. Handlers opt in with
// @x-agent {"id":"knowledge.delete","risk":"destructive",...}
// @x-agent-hint "Cannot be undone."
// @Param id path string true "知识ID" extensions(x-agent=knowledge_id)
and response types mark the fields the model may see with an
extensions:"x-agent" struct tag. Exposure stays opt-in at every level:
unmarked operations, parameters and fields are not reachable, so a new
field on Knowledge or a new query parameter never reaches the model by
accident. NewCatalog still enforces the safety rules (forbidden areas,
risk versus method, approval targets), and a test fails when the
annotations and docs/swagger.json disagree.
The twelve operations compile to the same routes, parameters and
results as before; document results now share one field set, and the
parse_status filter accepts deleting, which the API supports.
* fix(agent): enforce resume and wiki context scopes
* feat(agent): persist human-in-the-loop prompts with a shared broker
Tool approvals and MCP OAuth prompts are now rows in agent_prompts,
awaited through hitl.Broker (lease, DB polling, Redis wake-up, per-kind
answer validation). Resolve is bound to session and kind. This is P1 of
the suspend/resume design; runs still block as before.
* feat(agent): suspend runs whose prompt outlives a short in-memory wait
Behind agent.prompt_suspend_enabled (off by default). A run raised from the
HTTP stream saves its state when a tool approval is raised; after the hot
wait the prompt moves to suspended and the assistant message is saved as
awaiting_input instead of blocking. A reaper takes over prompts whose
waiting replica stopped renewing its lease. Resume comes in a later change.
* feat(agent): resume suspended runs once their prompt is answered
The replica that records the answer resumes the run in process under the
prompt's lease. Superseded, expired and abandoned runs are closed with a
result for every tool call, and approved tools are never replayed.
* feat(agent): let users answer suspended tool approvals and follow the resumed run
* feat(agent): ask_user tool and generic prompt answer endpoint
- ask_user built-in tool: options, short forms or free text; validated
answers, decline, suspend/resume like tool approval; non-interactive
callers (IM, API keys) are told to ask in the reply instead
- POST /agent/prompts/{prompt_id} (and embed variant) answers ask_user
and tool_approval prompts, returns resumed; SDK ResolveAgentPrompt
- agent_prompt_required/resolved events; AskUserCard sharing the
countdown with ToolApprovalCard; answered questions rebuilt as cards
from history
- awaiting-input messages keep their steps expanded so the pending card
stays visible; prompt cards keyed by their own id
- i18n for all locales; design doc updated
* fix(agent): keep prompt answers that race a suspending or vanished owner
- Resolve suspends a pending prompt whose owner's lease lapsed, as the
reaper would, so the answer resumes the run instead of waking nobody.
- Resuming waits for the suspending run to persist its message and clear
its live-run marker; a marker left by a vanished owner is cleared.
- A resumed run that suspends again on a new prompt no longer has its
message closed from the old state.
- tool_approval answers are decoded strictly and require "approved";
fix the SDK doc that showed {"decision": "approve"}.
- API-key runs block instead of suspending, since they cannot answer.
- A run state that cannot be saved falls back to an in-memory wait, and
NUL escapes are stripped from snapshots for jsonb.
* style(chat): align the ask_user card with the other interaction cards
Question and answer use the timeline's step text styles instead of
primary-colored and monospace text; options and form controls use the
compact step size, the number input spans the row, and the free-text
character counter is hidden.
* feat(chat): dock pending agent prompts above the composer
Tool approvals, ask_user questions and MCP OAuth prompts were answered
inline in the agent timeline, where a long answer or scrolling back
pushes them out of view. Open prompts of a streaming or suspended run
now gather in a dock above the composer (main chat and embed), one at a
time with a pager, lettered options and Enter to submit. The timeline
keeps a one-line record with a link back to the dock and the outcome
once answered. Views without a dock still answer inline.
* fix(agent): fence prompt ownership and preserve resumed turn context
* fix(agent): keep runs through consume errors and file prompts under the caller
Consume reported a store error as a lost claim, so an answer consumed
during a database hiccup detached its run: the message was never
persisted, the live-run marker stayed, and the reaper skipped the row
because the waiter had already dropped the snapshot. Consume now retries,
then decides from the row, and gives a run up only when the prompt is
known to have moved on.
Tool approvals and OAuth prompts of a shared agent were filed under the
agent's workspace, so the user's answer failed the tenant check and the
prompt timed out. Like ask_user, they now use the caller's workspace;
policy and token lookups stay in the agent's.
Enter on a picked option submits it instead of toggling it off, and
resume errors no longer report a nil cause.
* fix(agent): validate prompt choices and require durable approval claims
Reject malformed serialized option lists so the model can retry with valid arguments. Distinguish prompt consumption failures from lost ownership without authorizing side effects, and preserve native Enter selection for unselected choices.
* fix(agent): resolve prompt workflow lint errors
* fix(skill): do not fail installs on non-blocking observations
A working skill was rejected when the installer recorded a docs mismatch
as a blocker. Keep real setup failures in blockers and surface harmless
observations as notes.
* style(skill): wrap the install-report validation error
* feat(frontend): compact skill cards and install progress
Show each sandbox install on the card and collapse installer prompts, so
the skills page stays readable when a skill is installed in more than one place.
* fix(chat): include shared KBs in starter questions and stop composer jitter
Agents using all knowledge bases now draw starters from KBs shared into
the tenant, matching chat retrieval. The new-chat page skips refetches
whose scope did not change and only shows the skeleton on first load.
* fix(mcp): keep OAuth token expiry independent of the process time zone
mcp_oauth_tokens.expires_at is a naive TIMESTAMP column. The token store
computes the expiry from the process clock, the column drops its offset,
and the driver reads the stored wall clock back as UTC. When the
application runs outside UTC, every stored expiry is therefore shifted
by the process offset: with TZ=Asia/Shanghai, the docker compose default,
a token is reported as expiring eight hours after it really does.
WeKnora trusts that value. The OAuth status endpoint reports a token as
authorized for those extra hours, and the runtime neither refreshes it
ahead of time nor asks for authorization again. It sends the expired
access token to the MCP server and only recovers after the server
rejects it.
Promote the token and client timestamps to TIMESTAMP WITH TIME ZONE, as
migration 000072 did for API keys and resource grants, and normalize the
values the repository writes to UTC, so new rows are right even before
the migration is applied. The status endpoint keeps reporting the expiry
in UTC as before: the driver returns timestamptz values in the process
time zone, and the response would otherwise vary by deployment.
The migration cannot repair existing rows, because the time zone of the
process that wrote them is unknown. Like 000072, it reads them as UTC,
so they keep their shifted value until the token is authorized or
refreshed again.
* fix(migrations): renumber MCP OAuth timestamptz migration to 000118
000117 is now taken on main by messages_attachment_lookup.
---------
Co-authored-by: wizardchen <wizardchen@tencent.com>
The knowledge base description call hardcoded MaxTokens=800, sized for a
short JSON reply. Reasoning-style models can spend that budget on thinking
even when thinking is disabled, returning an empty completion that fails
generation with 'no gist' (issue #4221), and deployments had no way to
raise it.
Raise the default to 2048 and let operators override it with the
KNOWLEDGE_BASE_PROFILE_MAX_TOKENS environment variable (invalid or
non-positive values fall back to the default). Documented in .env.example.
Co-authored-by: LuckVd <LuckVd@users.noreply.github.com>
WeKnora runs behind other applications: they sign their users in and
call WeKnora with a tenant API key and X-External-User-ID, and WeKnora
keeps sessions and MCP OAuth tokens per external user. When an agent
uses an OAuth-protected MCP service, the only way to get that user's
token is the browser authorization code flow, and in this deployment
the user never sees WeKnora, so there is no browser to complete it.
Independently, an OAuth MCP service can only get its client through
dynamic client registration (RFC 7591), so authorization servers
without a registration endpoint cannot be used at all ("server does not
support dynamic client registration"), and servers that allow a grant
only to clients an administrator registered refuse a dynamic one.
JWT bearer grant. The application in front already knows who the user
is. POST /api/v1/mcp-services/:id/oauth/assertion lets it present a
signed assertion of that identity, such as the Identity Assertion JWT
Authorization Grant (ID-JAG) used by MCP's Enterprise-Managed
Authorization extension. WeKnora sends it to the service's
authorization server with the JWT bearer grant (RFC 7523) and stores
the token exactly like the callback does, so status, revoke, runtime
connections and, when the response carries a refresh token, refresh
use it unchanged. The assertion is forwarded unread; validating it is
up to the authorization server. The request reuses the principal from
authorize-url, the SSRF-safe HTTP client and the callback's connection
recycling, and the client the service already has. It does not run
dynamic client registration, which describes a redirect-based client;
without a client it answers 400. The token request outlives the caller,
so a token issued for an assertion that can only be used once is not
lost. A 4xx response other than 408 and 429, or a 2xx response carrying
an OAuth error, answers 400 with the OAuth error code and is logged; a
5xx, 408 or 429 response or a network failure answers 500. Request
logging masks the assertion field.
Pre-registered client. auth_config.client_id names a client registered
with the authorization server in advance, and client_secret is its
secret for a confidential client. When client_id is set it takes the
place of dynamic registration everywhere a client is read: the
authorization URL, the code exchange, the assertion grant and runtime
connections with their token refreshes. The values live on the service
rather than in mcp_oauth_clients, because a refresh rejected with
invalid_client deletes that row so the next authorization registers
again; an administrator's client would silently disappear. client_id is
non-secret: it is set through the main PUT, where an empty value clears
it, and returned in auth_config. client_secret follows api_key and
token: encrypted at rest, never returned, accepted in the create body,
and changed afterwards through the credentials subresource. Changing
client_id rebuilds the service's connections, and a connection built
with a pre-registered client is not treated as holding a replaced
registration when an authorization recycles connections. The MCP
service dialog adds optional Client ID and Client Secret fields to the
OAuth section, in all six locales.
Nothing changes for existing services: with client_id empty every
existing path reads the stored registration and registers dynamically
as before, and the authorization code flow, its state, the callback and
the dynamic registration request are untouched. The authorization
server HTTP client is moved into a function that both paths call.
* feat(agent): read chat attachments on demand
Agent turns pasted query-selected attachment excerpts into the prompt before the model could act. List stored files as a manifest so the agent can page and search them through read_attachment.
* fix(agent): preserve attachment access and image reads
* fix(agent): bound attachment cleanup and image processing
* Remove standalone read_attachment tool
* Read attachments and images through read_file
Merge read_attachment into read_file (attachment:// paths, numbered
document images, staged-copy aliasing, query search), return sandbox
images as images, describe images for non-vision models inside the
tool call with bounded concurrency and model-chosen detail/focus,
render image reads in the UI, and record image metadata in Langfuse.
* fix(agent): make attachment pagination complete and bound image reads
* refactor(agent): separate attachment reads and cache image observations
* fix(attachment): read image batches concurrently and harden description cache
- ReadImages authorizes once and describes images in parallel
- start VLM deadlines after a slot is held; longer timeout for full reads
- detach shared description calls from the first caller's context
- skip rewriting unchanged sandbox projections
- strip the description cache from temporary document API responses
- render upload text before calling the vision model
* fix(attachment): number images in document order and polish attachment UI
- return resolved images in document order instead of reverse
- show attachment file names instead of attachment:// IDs in tool titles
- use the shared file icon and a lighter card for chat attachments
* fix(ci): renumber attachment migrations and satisfy lint
Main already took sqlite 000035 and versioned 000116, so the attachment
lookup indexes move to the next free numbers. Also wrap the ReadImages
signature and drop an unused test parameter.
* fix(ci): expect sqlite migrations to reach version 36
The tools a smart-reasoning agent may use were defined in three places
that never checked each other: the agent editor's checkboxes, the stored
allowed_tools, and what registerTools registers. The editor drew from a
hard-coded list that had drifted (search_conversations, a default tool,
had no checkbox), hid stored entries outside that list, and could not
untick a tool whose knowledge base capability was missing. The save API
stored any name. And an empty list could not mean "no tools": three
places treated it as "use the default tools", so clearing every checkbox
gave an agent without a knowledge base search_conversations, while the
editor's preview said it had none.
One source for the tool list: GET /api/v1/agents/tools serves the tools
of AvailableToolDefinitions with their group, danger flag and knowledge
base requirement, the default tools, and the tools other agent settings
register whatever the list says. The editor renders from it, falling
back to the catalog's label for a tool it has no translation for.
Stored values stay visible: a missing capability only blocks ticking a
tool, and stored names the catalog does not offer are shown ticked in
their own section and can be removed.
An empty list now means no built-in tools; only a list that was never
set selects the defaults. tools.EffectiveAllowedTools makes that
decision for tool registration, the session config and the rerank
requirement. Migration 000116 (SQLite 000035) writes the default tools
into the empty list of every existing smart-reasoning agent, so they
keep the tools they ran with. The knowledge base filter follows the
stored list, so such an agent with an "all" scope now gets the same
scope as one that ticked the defaults: bases search_knowledge cannot use
leave it. The editor writes the defaults into an unset list it loads,
so saving does not silently turn the defaults into no tools.
Saving validates the list: retired names are rewritten, switch-managed
and retired skill tools are dropped, names the request adds that no
tool answers to are rejected with a 400 that lists them, and unknown
names already stored are kept so an existing agent can still be saved.
The response reports what was kept or dropped.
* feat(gallery): filter images by source document
Add a gallery toolbar button that opens a paginated, keyword-searchable
document picker; confirming restricts the listing to images owned by
the selected documents. The backend gallery endpoint accepts a
knowledge_ids query param (capped at 50) narrowing chunk_images by the
owning document before de-duplication, so the count query stays index
served.
* feat(gallery): lift knowledge_ids cap via POST body, sortable doc picker
Add POST /knowledge-bases/:id/images accepting the gallery filter as a
JSON body so knowledge_ids escapes the URL-length cap (50 -> 1000, an
abuse guard rather than a transport limit); the GET variant keeps its
cap and both share the contract-constrain logic. The source picker
gains sortable column headers (file name / upload time, newest first
by default), a header select-all that unions and removes whole hit
lists across keyword searches, overflow guards capping the no-keyword
view at the 500 most recent documents, and a wider dialog.
* style(gallery): replace td-token fallbacks and font-size literals with design tokens
styleGuard.test.mjs enforces ratchets: --td-* vars must not carry
fallbacks (theme.css guarantees them) and font sizes must use
--app-text-* tokens. GallerySourcePicker.vue added 4 of each,
pushing the ratchets over baseline.
* fix(gallery): keep shared images in source filter and align picker UI
- Scope the de-duplication probe to the selected documents, so an image
whose newer copy lives in an unselected document is no longer hidden.
- Reset the source filter when the gallery switches knowledge bases.
- Accept an empty POST /images body; drop pruned attribute maps to nil.
- Keep the source filter out of the filter panel's count and clear action;
the empty state's clear still resets it.
- Rework the picker dialog to the BatchTagDialog shell: heading with
subtitle, footer with selection count, clickable rows, debounced search,
select-all toggling against every hit, stale select-all responses dropped.
- Remove the unreachable GET knowledge_ids branch in the API client.
---------
Co-authored-by: tayadwx <tayadwx@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
* fix(deploy): bump paradedb image to v0.25.11-pg17
Batch-importing large knowledge bases on the pinned
paradedb/paradedb:v0.22.6-pg17 image drives PostgreSQL into a
PANIC/crash-recovery loop (corrupted page pointers in shared buffers,
amcheck clean, no OOM), taking every ingest task down with it.
Three independent fixes upstream cover this exact write path, and the
pinned image predates all of them:
- pgvector 0.8.2 fixed a buffer overflow in parallel HNSW index
builds, 0.8.3 fixed possible index corruption during HNSW vacuuming,
and 0.8.4 fixed inserts during HNSW vacuuming; the image ships
pgvector 0.8.1, and the embeddings table maintains three HNSW
halfvec indexes on import.
- pg_search gained WAL-based crash recovery in 0.24.0 (paradedb#4901):
without it, any backend crash corrupts BM25 segment metadata and
turns a single crash into a recovery loop (paradedb#4935).
- PostgreSQL core moved 17.9 -> 17.11; its release notes contain no
fix matching this failure signature, ruling the core out.
Bump the compose image tags to v0.25.11-pg17 (postgres and
langfuse-db-init, prod and dev) and update the docs that pin the old
tag. Fresh installs are covered by the existing schema SQL (verified
against 0.25.11: extensions, BM25 index and HNSW halfvec indexes all
create cleanly). Existing data volumes keep working across the image
swap without any action (keyword and vector queries byte-identical in
testing); ALTER EXTENSION pg_search/vector UPDATE aligns the SQL
catalog afterwards, and migration 000099 is a no-op for 0.25.x by
design. The Helm chart pins a different image line and is left alone.
Fixes#4077
* fix(migrations): upgrade pg_search catalog to 0.25.11 with the image
Swapping in the v0.25.11 image leaves the extension catalog at 0.22.x.
Calling extension functions such as paradedb.version_info() against the
mismatched catalog segfaults the backend and sends the whole server into
crash recovery, so the catalog upgrade is required rather than optional.
- Add migration 000115 to update pg_search 0.22.0-0.25.10 to 0.25.11 and
pgvector 0.8.0-0.8.3 to 0.8.4 when the server ships those versions.
- Skip 000099 on newer images instead of advising UPDATE TO '0.22.6',
which leaves the catalog behind the shared library and crashes.
- Rewrite the upgrade guide as one 0.22.x -> 0.25.11 path with a required
ALTER EXTENSION UPDATE and a note that rollback needs a backup.
- Extend scripts/test_paradedb_upgrade.py to verify 0.22.2 -> 0.25.11 by
default (--to 0.22.6 keeps the old path) and run CONCURRENTLY
migrations outside a transaction like golang-migrate does.
---------
Co-authored-by: LuckVd <LuckVd@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
* feat(system): platform user management — list, enable/disable, reset password, role toggle
Adds a SystemAdmin-only user management panel under platform settings
(System global -> Access). The backend already had repository primitives
and promote/revoke endpoints; this wires the missing service/handler/route
for listing and account-status changes and adds the UI.
Backend
- New GET /system/admin/users: paginated, cross-tenant user list
(offset/limit, limit capped at 200), serialised via ToUserInfo so password
hashes are never exposed; has_more derived with a limit+1 fetch (no COUNT).
- New POST /system/admin/users/status: enable/disable an account.
Disabling revokes all of the user's tokens immediately. Service guards
reject self-disable and disabling the last active system administrator.
- ValidateToken now re-checks is_active on every request, so a disabled
account cannot keep using a previously issued access token.
Frontend
- UserListDialog: table with status/role tags, pagination, in-page
username/email filter, enable/disable and reset-password actions, and
one-click system-admin promote/revoke (reuses existing endpoints) with
confirmation prompts. Reset-password dialog is a sibling (not nested)
dialog so close/cancel/overlay all work.
- All new strings are i18n keys under system.globalSettings.userList in
all six locales (en-US, zh-CN, zh-TW, ja-JP, ko-KR, ru-RU).
Tests: handler unit tests for list pagination/redaction/limit-cap and for
status-change success/guard/404 paths; existing handler/service/router
suites pass.
Co-authored-by: MOSS Agent <noreply@example.com>
* fix(system): make account status changes atomic and validate requests
* refactor(system): streamline settings and add dedicated user management tab
* fix(system): resolve user management CI lint findings
* fix(system): preserve account status during ordinary user updates
---------
Co-authored-by: desksk <26273255+desksk@users.noreply.github.com>
Co-authored-by: MOSS Agent <noreply@example.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
* feat(wiki): improve graph layout and exploration
* feat(wiki): name graph themes and connect pages to their document summary
- Rewrite selectGraphAnchors on deterministic Louvain communities with
coverage, redundancy and readability rules; clean file-name captions.
- Add group focus bar with switch menu, Esc/background exit, caption pills.
- Count distinct neighbors for link_count from both link directions, and
let ego BFS use the same adjacency so stale in_links do not hide pages.
- Connect each page to its source document summary and leave the index
page out of the graph; return edges as [] for an isolated ego center.
- Keep graph search and type filters available after an empty render.
* fix(wiki): use theme tokens in graph styles and satisfy Go lint
* feat(wiki): label the page shared by a multi-document graph group
fuseWithRRF reads each list's ranks through bestRanks, which ranks every
list on its own by score. Retrievers run concurrently and their results are
appended in goroutine completion order, so neither the order of the lists nor
the order of the hits inside a list may change a chunk's rank.
These tests fail on the pre-#3687 concatenation-order ranking and pass on
main. Refs #3796.
Count distinct coverage across long repetitive runs and preserve HTML-wrapped no-text replies through normalization. Add sanitizer and image-persistence regressions for both cases.
Distinguish vector and keyword result pools, initial and refill phases, and diagnostic decisions from actual retrieval and model calls. Clarify that aggregate counts cover all candidates while detailed samples focus on image vectors, and document the new trace names.
* feat(mcp): support modern and legacy protocol connections
* fix(mcp): preserve annotated headers on modern tool calls
* fix(mcp): load parameter header schemas before tool calls
* fix(mcp): keep a working legacy session when discovery retry fails
Modern method-level 404s stay connected, while an expired SSE session still disconnects. A transient discover failure retries once, and a failed retry keeps the handshake that already succeeded.
* fix(mcp): wrap protocol negotiation lines for the linter
golangci-lint rejects lines longer than 120 characters.
* fix(mcp): retry protocol discovery without dropping the live session
A second initialize on the same transport clears a stateful legacy session when discover returns 404. Probe on a separate connection, and drop cached parameter headers after another client refreshes the directory.
---------
Co-authored-by: wizardchen <wizardchen@tencent.com>
* fix(chat): keep custom metadata on knowledge-chat references
Redis round-trips and graph or analysis result builders dropped knowledge custom metadata, so chat citations lost fields such as course and lesson URLs.
* test(chat): wrap metadata fixtures to satisfy line length lint
---------
Co-authored-by: wizardchen <wizardchen@tencent.com>
* fix(models): align configuration defaults and multimodal workflows
* feat(image): enhance image retrieval diagnostics and filtering
- Implemented `retrieveObservedImagePool` to observe engine calls and record image recall decisions without altering results.
- Added detailed diagnostics in `summarizeImagePool` and `summarizeImageCandidateCut` to track image filtering decisions and scores.
- Introduced tests for image pool diagnostics to ensure accurate filtering and decision recording.
- Updated existing functions to utilize new retrieval and summarization methods for improved observability and accuracy in image handling.
* feat(embeddings): enhance image handling with new formats and message support
- Introduced `EmbeddingImageFormat` to manage image input formats, allowing for both object and messages formats.
- Updated `EmbeddingsSettings` to include new fields for `ImageFormat`, `ImagePrompt`, and `TextAsMessages` to support multimodal embedding workflows.
- Enhanced `Client` methods to build request bodies for images in both formats, ensuring compatibility with vLLM's requirements.
- Added tests to validate the new image message handling and ensure correct request formatting for different scenarios.
- Updated documentation to reflect changes in image input handling and configuration options.
* feat(similarity): add embedding similarity mode for enhanced document scoring
- Introduced a new `similarity` option in `ModelDebugOptions` to score documents and an optional image against a query.
- Updated `ModelDebugDrawer.vue` to support a new input mode for similarity, allowing users to select similarity as an input type.
- Enhanced the UI to display similarity results, including ranked candidates based on cosine similarity.
- Added tests to validate the functionality of the new similarity mode in embedding models.
- Updated localization files to include new strings related to similarity mode in multiple languages.
* feat(embeddings): add Qwen3-VL-Embedding support for multimodal input
- Introduced Qwen3-VL-Embedding model with support for both text and image inputs.
- Updated model configuration files to include compatibility settings for the new embedding type.
- Enhanced tests to validate the functionality of Qwen3-VL-Embedding, ensuring correct handling of inputs and outputs.
- Updated documentation to reflect the new model's capabilities and usage instructions.
* test(models): wrap embedding assertions to satisfy lint
* test(opensearch): isolate HTTP transports between parallel tests
* feat(models): expose embedding input modalities
Whether an embedding model maps images into the same space as text is
what will decide if a knowledge base can store image vectors. The
catalog already had the field, but most multimodal embedding models
were missing it and embedding rows never reported it.
- Catalog: declare input modalities for the Doubao and Tongyi vision
embeddings, the Aliyun multimodal / qwen-vl embedding families and
jina-embeddings-v4, as listed in each vendor's documentation. The
migration baseline changes for exactly these nine entries.
- Model responses resolve capabilities for embedding rows too, so
capabilities.input reflects the catalog merged with spec.input.
- Model editor: an "Image input" switch for embedding models. It follows
the catalog and writes spec.input only when the row differs from it;
picking another catalog model or switching vendor drops the
declaration. Model cards show the image badge for such models.
* feat(embedding): embed images with multimodal embedding models
Adds the image side of an embedder, for models that map images into the
same space as their text vectors so a text query can find an image.
- api: EmbedImage (bytes + MIME type, sent inline as base64 because the
object store is usually unreachable from the vendor) and an
ImageEmbedder implemented by all four protocols, each in the image
shape its reference documents: Ark image_url, DashScope contents[].image,
Gemini inlineData parts, and on the OpenAI shape an object keyed by the
vendor's image_field (Jina: "image"). A plain OpenAI-compatible
endpoint names no image field and takes no images.
- Settings: image_field, max_image_batch_size (default one per request),
max_image_bytes and image_mime_types, filled from vendor docs for the
DashScope multimodal models, gemini-embedding-2 and Jina.
- embedding: an optional ImageEmbedder interface reached through
AsImageEmbedder, so existing Embedder implementations and fakes are
untouched. An embedder takes images only when the catalog (or the
row's spec.input) lists image AND the endpoint can carry one. Images
are checked against the documented limits before any request, then
split at the documented images per request. The concurrency, debug
and Langfuse decorators forward it; logs and traces carry the MIME
type and size, never the bytes.
The migration baseline changes only for the entries whose resolved
embedding settings now carry image limits.
* feat(knowledge): index images by their own vector and recall them
When the knowledge base's embedding model embeds images, each image now
gets a vector of its own next to its caption and OCR chunks, so a query
can find an image by what it shows even where the caption left it out.
Ingestion
- After the caption/OCR chunks are indexed, the multimodal task embeds
the image (embedding.PrepareImage converts and shrinks it to the
vendor's documented limits) and stores it as a new image_vector chunk:
Content is the caption (OCR text when there is none) for reranking and
the answer context; its index row carries the image's vector with
SourceType ImageSourceType. Scanned PDF pages are skipped, their OCR
text serves better. A failure here is logged and never fails the task.
- The image vector gets its own chunk rather than a second index row on
the caption chunk: OpenSearch and Weaviate key documents by ChunkID,
so a second row would overwrite the caption's text vector, and copy,
move and enable/disable all follow chunk IDs.
- CompositeRetrieveEngine.BatchIndexVectors writes precomputed vectors
through each engine's normal BatchIndex, keeping row order (the
composite's de-duplication does not).
- Paths that rebuild vectors from text leave image_vector alone:
syncChunkIndex only syncs its enabled flag, updateChunkVector skips
it, and a caption edit updates its Content only.
- The multimodal task's caption/OCR index rows now set IsEnabled; only
backends with a column default were storing them as enabled.
Retrieval
- A text query scores lower against an image than against text, so when
the model embeds images the document vector search is widened by half
(capped at 500) and run at min(VectorThreshold, 0.1); each store
group's hits are then held to their own threshold before score
normalization: text at VectorThreshold, images at min(VectorThreshold,
0.1). Keyword hits on image rows are dropped, their Content being the
already-indexed caption.
- image_vector hits are searchable and merge like caption hits: parent
context is attached, and the caption is not repeated from ImageInfo.
Adds golang.org/x/image for scaling and WebP/BMP decoding.
* fix(models): report no thinking levels for embedding, rerank and ASR models
Embedding rows now carry capabilities, and the end-to-end run showed them
listing off/auto/minimal/low/medium/high: these references resolve no chat
protocol, and an empty level map reads as "every level supported". A model
without a chat protocol does not think, so its capabilities say so.
* fix(compaction): never read a cancelled turn's stream as a summary
streamSummary selects on the turn's context and the provider stream at
once. When the turn is already cancelled both are ready (providers close
the stream once their context ends), and select picks at random, so a
stopped turn could come back as a completed, partial summary with a nil
error. TestSummarizationIsNotRetriedOnceTheTurnIsCancelled caught it
intermittently in CI and reproduces under -race with several -cpu values.
Check the context before each receive and again when the stream closes.
* feat(rerank): score images with multimodal rerank models
Rerank models that read images can now be sent an image document and
score it against a text query on the same scale as text, which is what a
recall made by an image's own vector needs: a text reranker only sees the
caption, and rejects an image for what the caption left out.
- api: ImageReranker, implemented by the Cohere and NIM shapes. Image
documents go in requests of their own, so text requests keep their
exact shape. NIM sends image-only passages without text, as base64 data
URLs (its VLM reranking reference requires both). The Cohere shape sends
{"<image_field>": data URI} documents and asks for no echo of them.
- The image settings embeddings already had (image_field,
max_image_batch_size, max_image_bytes, image_mime_types) move into a
shared ImageInput embedded in both settings; resolved embedding settings
serialize exactly as before.
- Catalog: jina-reranker-m0 and nvidia/llama-nemotron-rerank-vl-1b-v2 take
text and image. Jina names "image" documents; its base64 form is not
shown in any reranker example, so the data URI its embeddings reference
documents is used and marked unverified. NVIDIA lists its six formats
and 512 passages per request.
- rerank: an optional ImageReranker reached through AsImageReranker, gated
on the model's catalog input and the endpoint; images are checked against
the documented limits before any request, scores are normalized like
text, and the debug and Langfuse decorators forward it without logging
image bytes.
- Image preparation (format conversion, shrink to fit) moves from the
embedding package to internal/models/imageprep, since rerank needs it
too.
* feat(retrieval): keep a vector hit's own similarity through fusion
Hybrid fusion replaces a hit's Score with a rank-based RRF score. That is
right for ordering, but it erases the evidence reranking needs to judge an
image found by its own vector: how close the vector actually was. Record
the engine's similarity on each vector hit (IndexWithScore.VectorScore)
before normalization and fusion rewrite Score, and carry it onto the
search result (SearchResult.VectorScore, not serialized).
* feat(reranking): judge image hits by their image, not only their caption
An image found by its own vector was reranked on its caption and OCR text,
so a text reranker rejected it for exactly what the caption left out.
- With a reranker that reads images and a LoadImage callback, image_vector
hits are scored by their image (prepared to the model's limits) on the
same scale as text, and pass or fail the same threshold. A hit whose
image cannot be read, prepared or scored falls back to its text.
- With a text reranker, its verdict stands for images that are mostly
text (OCR of 200 characters or more). A pictorial hit it rejects is kept
when its vector similarity (VectorScore) reaches Options.ImageKeepScore:
at most two, strongest vector first, appended after the ranked results
and marked kept_by=image_vector. This also returns an image when no text
passes at all.
- Diagnostics report images_scored and images_kept.
* feat(rerank): read image hits' images in every rerank path
The chat pipeline, the agent search_knowledge tool and the hybrid-search
API now pass the rerank stage a way to read an image hit's image and an
image keep score, so a multimodal reranker scores images by what they show
and a text reranker can no longer drop a pictorial image its caption
undersells.
- KnowledgeBaseService.ReadChunkImage reads the first image of a result's
image_info from the storage of its knowledge base (the knowledge base's
tenant, so shared knowledge bases read from their owner's storage),
capped at 32 MB. Plain http(s) images go through the SSRF-safe
downloader.
- The backend resolution the image multimodal task used moves into a
shared knowledgeImageReader, so ingestion and reranking find an image in
the same place.
- reranking.ImageKeepScoreFor: an image is kept over a text reranker only
when its vector was at least as close as a text hit had to be, and never
below 0.25 (empirical).
* feat(chat): show a vision model the images its answer rests on
An image recalled by its own vector reached the answer as its caption only,
so a vision model could not answer from what the caption left out.
- Knowledge QA: INTO_CHAT_MESSAGE reads, for a model that supports vision,
the images of the contexts that rest on an image vector match (at most
three distinct ones, prepared to what every vision API takes: PNG, JPEG,
WebP or GIF within 5 MB), attaches them after the user's own images, and
names the contexts they belong to.
- Agent: search_knowledge attaches the same images when the agent's model
supports vision (the agent describes tool images to models that cannot
see them, and these already carry captions). Stored history drops them;
they are read again from storage.
- An image hit and its caption hit read the same once merged, and
de-duplication keeps either. The kept copy now inherits the image
(image_vector_match), in the pipeline's exact and partial-overlap
de-duplication and in the agent tool's.
- Results the rerank stage kept outside its top-k (kept_by) no longer fall
to the later top-k cuts: the pipeline's FilterTopK and the agent tool's
MMR and limit let them ride along after the ranked results.
* docs(website): describe how image hits are reranked and shown to vision models
* Fix image evidence preservation and model source mapping
* fix(knowledge): claim cloned and released document images in the catalog
#3493 binds images at parse time (bindStoredImages), which covers ingestion
but not the two paths that move image ownership:
Clone. A copied image is written as a new object, yet nothing claimed it for
the destination knowledge, so the KB file proxy answered 403 and cloned
documents rendered without images. The copy now goes through SaveBytes into
the servable exports/ namespace (CopyFile wrote to the knowledge-scoped
upload layout the proxy rejects), is claimed by the destination knowledge,
and CloneChunk / FAQ clone bind the handles left in chunk content and
image_info.
Delete. Release only looked at multimodal ImageInfo, which stays empty for
documents whose images live in markdown alone, so those objects outlived the
knowledge that owned them. The release set is now the union of ImageInfo URLs
and the bindings recorded for the knowledge being removed, with source_file
excluded so reparse and cleanup keep the original document.
The parse-path claim from the earlier attempt is dropped: ProcessDocument
already gets it from bindStoredImages, and the removed test only string
matched that call in the source. Every claim path stays best-effort,
including the clone path, which used to fail the whole clone and delete the
fresh copy when a single Bind errored.
* fix(knowledge): keep markdown-only images out of the pre-reindex cleanup
cleanupKnowledgeResources runs before a knowledge is re-indexed -- a manual
update, a reparse, a move with reparse -- not before it is removed. Unioning
in the catalog bindings there released a solely owned markdown-only
attachment, deleteExtractedImages deleted the file, and the catalog file
service marked the resource deleted. The re-claim that runs after the cleanup
resolves through a state=active lookup, so it could never bind that handle
again: the republished body was left pointing at a deleted image.
Cleanup collects ImageInfo URLs alone again. The paths that do remove a
knowledge entry (executeKnowledgeDelete, ProcessKBDelete) keep the union, which
is what lets markdown-only images be released when the knowledge actually goes
away.
Reported by @lyingbug in review on #3752.
---------
Co-authored-by: tayadwx <tayadwx@users.noreply.github.com>