* 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
* 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
* fix(chat): persist failed quick-answer turns so errors survive refresh
A KnowledgeQA (fast-answer/RAG) turn that failed left the assistant row
empty and incomplete forever. The pipeline error was already surfaced
live as an SSE error event (bubble text + toast), but nothing ever
completed the turn: no content was saved, is_completed stayed false, and
the SSE stream never published its completion event, so a refresh
rendered a blank bubble and the connection polled until the client hung
up (issue #4145).
Register an EventError handler for the quick-answer mode that completes
the turn through the same path as a streamed answer:
- persist the error text on the assistant message (appending to a
partial answer instead of replacing it), falling back to a fixed
explanation when the error carries no message
- mark the row completed, release the turn lease and publish the SSE
completion so the stream closes cleanly
- skip chat-history indexing, follow-up suggestions and memory writes
for the failed turn by completing with an empty query
A late error after a fallback already completed the turn is ignored via
the shared completion guard.
* test: wrap over-length fixture error string to satisfy lll
* 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
* feat(agent): let the assistant manage FAQ entries
New operations: faq.list_entries, faq.get_entry, faq.create_entry,
faq.update_entry, faq.add_similar_questions and faq.delete_entries
(up to 20, each question named on the approval).
The catalog learns what FAQ needs:
- integer path parameters (entry_id) and integer lists (entry_ids);
approval items resolve integer IDs too;
- x-agent-required, which makes the model send a field the API treats
as optional. The FAQ update replaces the whole entry, so a left-out
answer list, tag or answer strategy would be cleared;
- a body on DELETE, which the FAQ batch delete uses.
The FAQ list documents its page of FAQEntry instead of an untyped page,
and the delete body is a named type. FAQ tags are referenced by seq id,
so knowledge_base.list_tags also returns tag_seq_id.
* fix(agent): resolve FAQ operation lint failures
* fix(agent): preserve complete FAQ content during updates
* feat(agent): let the assistant delete and move documents in batches
A batch target can now resolve each item: x-agent "items" names the list
parameter and a read run once per item, and the approval lists every
title under the knowledge base name. The list must be capped at
MaxApprovalItems (20) by x-agent-maximum, which now also bounds string
lists, so nothing approved goes unnamed. One item the user cannot read
blocks the whole batch before any prompt.
New operations: knowledge.batch_delete, knowledge.move (to another
knowledge base, destination named on the card),
knowledge.get_move_progress and knowledge_base.list_move_targets.
The move and move-progress Swagger responses now show their data
envelope.
The approval card keeps line breaks in its description and renders
trailing "- " lines as a scrollable list.
* fix(agent): reconcile batch approvals with workspace operation updates
* fix(agent): keep every batch approval item visible
* feat(agent): open more workspace operations to the WeKnora assistant
Reads: knowledge_base.list / list_shared / list_tags, knowledge.list_folders,
chunk.list, wiki.get_page / list_folders / list_revisions; knowledge.list
also takes tag_ids, folder_path and folder_recursive.
Recoverable writes: knowledge.update (title, summary), batch_reparse,
move_to_folder, rename_folder, create_manual, create_from_url,
knowledge_base.generate_profile, wiki.create_folder / move_page / revert.
x-agent gains catch_all for routes registered as *slug, which Swagger
cannot express. run_operation decodes knowledge_ids handles. The shared
knowledge base list, the tag page and the URL import body get concrete
Swagger types instead of free-form objects.
* fix(agent): show the assistant the change it is about to make
Manual documents can reach the API length limit, unpaginated lists cover
a tenant, and tag pages report their total. wiki.list_revisions can
return one stored revision before revert, and the confirmation card
names the URL, folder, version and documents.
* fix(agent): align catalog tests with the knowledge API allowlist
Catch-all assertions follow the knowledge routes, and the nested tag
page fixture stays inside an area the catalog accepts. The rune-limit
error also fits the line-length check.
* 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
* docs(swagger): add shared response envelope types
* docs(swagger): type knowledge base responses
* docs(swagger): add concrete response body types
* docs(swagger): type chunk list responses
* docs(swagger): type knowledge mutation responses
* docs(swagger): type wiki search and autofix responses
* docs(swagger): type FAQ responses
* docs(swagger): type tag responses
* docs(swagger): type message responses and SSE schemas
* docs(swagger): type agent responses
* docs(swagger): type remaining handler responses
* docs(swagger): regenerate OpenAPI spec
* docs(swagger): type knowledge, activity and wiki maintenance endpoints
Covers the endpoints left out of the earlier passes: knowledge base
detail, document list/detail/spans/reparse/cancel/delete, knowledge
base activity and the Wiki stats, issues, lint and rebuild-links
endpoints. The spans handler now writes the documented structs instead
of gin.H, so the schema cannot drift from the body; the JSON is
unchanged. List filters gain their real enums and bounds, including
the finalizing, cancelled and deleting parse states.
* docs(swagger): document JSON-valued fields as JSON, not byte arrays
types.JSON and json.RawMessage are byte slices, so swag rendered every
metadata, details and config field as an array of integers. A swag
overrides file documents them as objects; the four fields that hold
arrays (relation chunk ids, allowed origins, image refs) say so with a
swaggertype tag.
* chore(lint): exempt swag annotation lines from the line-length limit
swag reads each @Param, @Success and @Failure as a single line, so an
enum list or a composed response type cannot be wrapped to fit.
* chore(lint): exempt struct tags carrying swag attributes from the line limit
Struct tags cannot wrap either; a field documented with swaggertype or
extensions keeps its tags on the declaration line.
* 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
The agent completion event carries the turn's aggregated token usage
but not the chat model that produced it. A relay or gateway that meters
agent chat cannot price that usage: unit prices, and the discounts for
cache reads, cache writes and uncached input, differ per model, and
changing an agent's model blends the old and the new numbers in one
total.
The completion event's data now carries model_id, taken from the
engine's chat model. The turn's usage is aggregated only from calls
made through that model (each round and the final answer), so it names
the model the usage belongs to. A consumer resolves the model's name
and settings through the model API with its own credentials. The
message row's model_id keeps the requested binding and can differ when
a request override is invalid and the turn falls back to the agent's
model; the event names the model that actually ran. The key is omitted
when no model is known. The quick-answer path is not changed.
The model name is left out on purpose. The completion event reaches
everyone who chats with the agent, including shared-agent users and
embed visitors, and an operator may not want to reveal which model
serves an agent; the provider-facing string can also be a deployment
override that the model API hides from non-admin callers. The message
history already returns the same ID to these users.
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>
An OAuth MCP service keeps one cached connection per user. After a
successful OAuth callback, after a token is revoked, and when an agent
resumes from an in-conversation authorization, the service's connections
were recycled with CloseClient, which disconnects every user's
connection and cancels connection attempts still in flight. Closing a
Streamable HTTP connection cancels the requests it has in flight, so one
user authorizing again cancelled other users' running tool calls on the
same server process. The agent retries a failed call once on a fresh
connection, but a long call fails, and a non-idempotent tool can run
twice.
A connection is not affected when another user's token changes: each
one reads its own user's token from the store on every request. Add
MCPManager.CloseClientForPrincipal, which closes only that user's
connection, and use it when a token is revoked.
After an authorization, the callback and the in-conversation retry call
CloseClientsAfterAuthorization instead. It closes the authorizing user's
connection, since the new authorization may be for another account of
the upstream service, and every connection of the service in the tenant
that was built with an OAuth client ID other than the registration
stored now. The registration is shared by all users of the service and
can be replaced by any replica. A connection still holding the old
client ID can fail its next refresh with invalid_client, and handling
that failure deletes the stored registration, by then the replacement.
If the registration cannot be read, the whole service is closed as
before, unless the caller's context has ended, in which case only the
authorizing user's connection is closed. The callback bounds this
cleanup with its own timeout.
This runs in the process that handles the callback and, for an
in-conversation authorization, in the process where the agent waits.
Connections cached by other replicas are not examined, as before, and
neither are other users' connection attempts still in flight.
CompleteAuthorization now returns the tenant, service and principal of
the attempt, and connections report the client ID they were built with.
Disconnecting happens after the manager lock is released, because
closing a transport can wait on the server.
* 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>
* 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
* 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(knowledge): put image vectors behind a knowledge-base switch, off by default
Image vector indexing and recall used to turn on whenever the knowledge
base's embedding model declared image input. A model that takes images is
often chosen for text alone, so an upgrade would have added an embedding
call per image, widened vector recall 1.5x and lowered the image threshold
to 0.1 for those knowledge bases without anyone asking.
ImageProcessingConfig gains image_vector_enabled (default false; stored
JSON without the key reads as off, so existing knowledge bases stay off
with no migration). Both sides now need the switch and the model:
- indexImageVector returns before touching the model unless the KB opted
in (KnowledgeBase.IsImageVectorEnabled, which also needs vector indexing).
- applyImageRecall resolves the embedding model only when some KB in the
search opted in, and records the opted-in KBs per store group
(storeGroup.ImageKBIDs). Only those groups widen the pool and lower the
threshold; image hits of any other KB, including ones indexed before the
switch was turned off, are dropped.
The KB editor shows the switch in the image processing section, with a
warning when the selected embedding model does not declare image input;
docs describe the switch, its cost and what turning it off does.
* fix(knowledge): leave image vectors behind when cloning into a KB that is off
CloneChunk copied every chunk of the source document and then CopyIndices
for all of them, so copying a document from a knowledge base with image
vectors on into one with the switch off (same model and store) still
created image_vector chunks and their index rows, bypassing the switch
that indexImageVector honours.
Image vector chunks are now dropped from the copy when the target has not
opted in. Every engine's CopyIndices copies only the rows of chunks in the
mapping, so their index rows stay behind too.
* fix(search): refill the vector pool past stale image vectors
Image hits of a knowledge base whose switch is off were dropped only after
the engine had ranked and cut its results at TopK. Image vectors indexed
before the switch was turned off could fill that pool and push out valid
text hits: with MatchCount 5 the pool is 50, and 50 stale image rows
ranked above the text left the search empty.
No engine can filter rows by source type (Postgres and SQLite do not even
take ExcludeChunkIDs), so the exclusion cannot move into the query. When
the document vector pool comes back full and holds stale image rows, that
search alone runs again on a pool twice as large, until it holds TopK rows
that are not stale, the index runs out, or the pool reaches
maxRetrievalPoolSize (at most four extra calls from a pool of 50). The pool
is then cut back to TopK such rows, matching an engine-side exclusion
unless more than maxRetrievalPoolSize-TopK stale rows rank above the text.
* feat(i18n): translate the image vector switch and image input keys into zh-TW
The zh-TW locale arrived from main after this branch added five keys: the
knowledge base's image vector switch (label, description, unsupported-model
warning) and the embedding model's image input flag (label, description).
* fix(knowledge): leave image vectors behind when moving into a KB that is off
A reuse_vectors move relocates a document's chunks and index rows in place:
MoveKnowledgeIndices rebinds the rows by document ID and
MoveChunksByKnowledgeID rebinds the chunks. Moving a document from a
knowledge base with image vectors on into one with the switch off therefore
carried its image_vector chunks and their vectors along, the same bypass the
clone path had.
When the target has not opted in, the image_vector chunks are now deleted
during the move, their index rows first and then the chunks, so a retry
finds the chunks again rather than leaving orphaned rows. A target that
opted in still receives them unchanged.
* fix(retriever): keep image vectors out of keyword-only engines
BatchIndexVectors handed image rows to every engine of the composite,
including one that serves keyword retrieval alone (Elasticsearch v7 next to
a vector store). There the row holds nothing but the image's caption, which
the caption's own chunk already indexes, and retrieval discards every
keyword hit on it.
Image rows now go only to engines that serve vector retrieval. An engine
that serves both keeps one row for both kinds, so its keyword search still
meets them; the search side handles that.
* fix(search): refill the keyword pool past image rows
Every engine that serves both kinds of retrieval stores one row per index
entry and runs its keyword search over that row's content, so an image
vector row, whose content is its caption, is a keyword hit wherever the
caption's own chunk is. filterImageHits drops all of them, but only after
the engine has cut its ranking at TopK, so they crowded out text and caption
hits; a keyword ranking that put the image rows first came back empty.
The keyword pool is now refilled the way the vector pool is refilled past
stale image vectors: when it came back full and held image rows, the
keyword search runs again on a pool twice as large, up to
maxRetrievalPoolSize, and is cut back to TopK hits that are kept.
Leaving the rows out of the keyword index instead would mean writing them
without searchable content (Milvus and Tencent VectorDB derive a BM25
sparse vector from it, and how they take an empty one is unverified) or a
source-type filter in every engine's keyword query (ten engines, and
filterable fields that existing collections lack).
* revert: let image vectors move with the document into a KB that is off
This reverts commit e259977fe915f7d0bc30c4b02bc7af04da1c8dd4.
Deleting the image vector index rows by chunk ID before the move is not
reliable: the Weaviate and Elasticsearch v8 delete wrappers ignore partial
failures, and OpenSearch rejects more than 1000 IDs with ErrBatchTooLarge.
A partial delete followed by the chunk delete leaves index rows whose chunks
are gone, which nothing ever cleans up.
Without it, the image_vector chunks and their index rows move together
with the document. While the target's switch is off they are filtered at
query time (the pool refill keeps them from crowding out text), they are
removed with the document on delete, reparse or knowledge base delete, both
chunks and index rows by knowledge ID, and they become active again if the
target turns the switch on. The clone path keeps dropping them, since there
the rows are copied rather than moved.
* fix(search): keep the image row refill from losing hits it already had
refillPool replaced a pool with the answer to each larger search. A refill
that answered only in part (RetrieveResult.Error, swallowed into a warning
by retainPartialResults, as when some collections of the store did not
answer) could hold fewer text rows than the complete smaller pool, or none:
40 stale image rows above 10 text came back from a partial refill as the
40 image rows alone, and the search lost all 10 text hits. A refill that
failed outright failed the whole store group, discarding a first round that
had succeeded.
A refill is now best effort. A failed or incomplete refill search stops
the refill and leaves the last complete pool in place, cut back to TopK
kept rows as before, so a refill can no longer leave a search worse off
than it was without it. Merging the partial answer into the pool was not
done: its rows would need deduplicating and its ranking is cut at a
different TopK over a different set of collections, while keeping the
previous pool is exact.
* docs(knowledge): say what happens to image vectors in a KB that is off and what the refill costs
The image vector section now says that with the switch off, image vectors
that were indexed before it was turned off, or that came along when the
document was moved in from a KB that has it on, are kept but filtered at
query time, are removed when the document is deleted or reparsed or the
KB is deleted, and are recalled again once the switch is turned on; a copy
into such a KB leaves them behind.
It also states the cost of keeping dropped image rows from crowding text
out of the pools: the vector and keyword pools are searched again with
TopK doubled up to the 500 candidate cap, which adds queries for store
groups that hold such rows, and text can still be missed when more than
about 500 candidates are image rows. A failed or partial refill keeps the
previous complete pool.
* fix(search): log unexpected refill result sets, and describe the refill stop condition precisely
* fix(datasource): omit last_sync_cursor from the data source list response
The settings page polls GET /datasource every few seconds during a sync,
and connector cursors can grow to megabytes. No list consumer reads the
cursor, so NewDataSourceResponses now blanks it; detail, create and
update responses still return it through NewDataSourceResponse.
* feat(datasource): add Seafile connector with fingerprint-based incremental sync
Sync folders and files from one Seafile library per data source. The
connector walks the selected scope one directory level at a time,
downloads files through the link + fileserver flow without credentials,
and reconciles deletions against a per-file oid/mtime/size fingerprint
cursor that is checkpointed every 50 mutations.
- resource ids are "<repo_id>:<path>"; ancestors collapse, one library
- per-file failures become coded error items and keep the path pending
- directory failures and Retry-After > 60s abort without deletions
- forced full runs keep the old cursor as a deletion baseline
- API token never reaches cursors, metadata, logs or error text
- share the supported import extension set through internal/utils
* feat(datasource): add Seafile frontend connector and docs
Wire the Seafile data source into the editor dialog, channel labels
and the five locales, and document how to connect a Seafile 10.0.1
library.
- connector definition with base_url + API token fields and icon
- picker guard: one library per data source, at least one selection
- "library" resource type and icon in the lazy tree
- channel label in the knowledge base filter, document views and chat
- i18n for labels, guide steps and the eight seafile_* sync error codes
- website-docs integration guide, data source and extension point doc
updates, and Seafile in the README data source lists
---------
Co-authored-by: zaqqmm <q-zhang10@qq.com>
* fix(chat_pipeline): treat non-JSON model refusals as skipped graph extraction
When a chunk carries nothing extractable (e.g. a table-of-contents page),
the LLM correctly answers with a prose refusal such as "抱歉…". parseOutput
then fed that prose to json.Unmarshal, failing with a confusing
"invalid character 'æ'" (the first byte of a CJK character), marking the
chunk task GRAPH_EXTRACT_FAILED and letting asynq replay the identical
doomed LLM call up to the retry limit.
Classify responses that contain no JSON structure at all (no '{' or '[')
as errModelDeclined and complete the extraction with an empty graph so the
task succeeds as an explicit skip. Malformed or truncated JSON (structure
present) still fails and retries as before.
Fixes#3600
* fix(chat_pipeline): keep empty model responses retriable in graph extraction
An empty response is usually transient (gateway returning 200 with no
content, a reasoning model spending its whole budget on reasoning,
content filtering), and a retry often succeeds. Only non-empty prose
with no JSON structure is treated as a declined extraction.
* fix(graph): skip prose refusals only in the async chunk task, keep truncation retriable
ParseGraph no longer turns a prose answer into an empty graph. It returns
an error wrapping ErrModelDeclined, and ChunkExtractService.Handle is the
only caller that treats it as a skip (span output skipped=model_declined).
The /initialization "try extract" endpoint and query-side entity extraction
report the refusal as a failure again, so the graph settings form no longer
gets its few-shot examples replaced with an empty result.
Extractor.Extract drops the ErrModelDeclined marker when finish_reason is
"length": prose with no JSON because the output budget ran out is
truncation, and asynq should retry it.
* fix(graph): retry every truncation spelling, not only finish_reason=length
Extract kept a prose answer retriable only when FinishReason was exactly
"length". max_tokens / max_output_tokens (and case/space variants that
IsLengthFinishReason already accepts), a stream that broke before the stop
event ("incomplete") and an adapter that reports no reason were still read
as a refusal, so the async chunk task skipped the chunk for good.
Only a reason that proves the model stopped on its own now counts as a
refusal. Ollama's non-streaming Chat also forwards done_reason, so a
num_predict cut-off is reported as "length" instead of an empty string.
* fix(graph): only treat a response with no JSON anywhere as a refusal
The refusal check looked at the first extracted fence, so a prose fence
followed by a JSON fence was skipped as a refusal instead of failing as a
retriable parse error.
---------
Co-authored-by: LuckVd <LuckVd@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
* fix(kb): let update API set vlm_config
UpdateKnowledgeBaseRequest only carried name/description/config, so the
PUT /knowledge-bases/:id endpoint could never change a knowledge base's
multimodal (VLM) config, even though CreateKnowledgeBase accepts a
top-level vlm_config. Thread an optional vlm_config through the handler
and service so the update path mirrors create (nil = no change).
Fixes#1723
* test(kb): pass the vlm_config argument in tests added on main
* fix(kb): accept only model-managed vlm_config fields on update
The update API copied the request's VLMConfig wholesale, so a caller
could set the legacy ModelName/BaseURL/APIKey/InterfaceType fields and
have the VLM client call BaseURL directly, outside model management and
its SSRF checks. Only Enabled/ModelID/DescriptionLanguage/
CustomInstructions are taken now; legacy fields keep their stored value.
A referenced model must exist and be a VLLM model (400 otherwise), and
disabling clears ModelID, matching the initialization config endpoint.
* fix(kb): validate and gate vlm_config on the update API
- Enforce the 4000-character custom_instructions cap
(types.ValidateKnowledgeBasePromptInstructions), as create and
/initialization/config already do.
- vlm_config is a KB setting: require kbSettingsAccess (owner workspace
or admin share) like /initialization/config, so share editors get 403.
- Stored legacy model_name/base_url keep IsEnabled() true on their own,
so disabling returned 200 but left VLM on, and managed -> disabled fell
back to the old endpoint. Clear them when the request enables a managed
model_id, or disables VLM without echoing back the stored
model_name+base_url (GET-then-PUT keeps legacy on). Request legacy
fields are only compared, never written. Enabling without model_id on a
non-legacy KB is now a 400 instead of a silent no-op.
- Document the vlm_config semantics in the KB API reference.
* fix(kb): keep the legacy VLM endpoint only for pure legacy knowledge bases
CreateKnowledgeBase stores vlm_config as sent, so a managed model_id can
sit next to legacy model_name/base_url; resolveVLM then uses the managed
model. The update's keep-legacy paths (disable echoing the stored legacy
fields, enabled=true without model_id) cleared model_id but kept the
legacy fields, so IsEnabled() stayed true and image calls moved to the
stored base_url.
Those paths now apply only when no model_id is stored. On a mixed config
a disable clears everything, and enabled=true without model_id is a 400,
the same as on any managed knowledge base.
---------
Co-authored-by: wizardchen <wizardchen@tencent.com>
* fix(model): treat 400 as reachable in chat connection test again
checkChatModelConnection probes with max_tokens=1 and is meant to treat a
400 as "endpoint reachable, auth OK". It detected that by matching the
go-openai wording "status code: 400". Since #3470 the error comes from
api.HTTPError ("API request failed with status 400: ..."), so the branch
never matched and the probe reported a failure.
This shows up with reasoning models behind LiteLLM: the 1-token budget
cannot finish a message, the gateway answers 400, and Test Connection
fails although the saved model chats fine.
Match the status code via errors.As on *api.HTTPError instead of the
message text.
* test(handler): drop unused request parameter in fake chat gateway
* fix(model): report a 400 that carries an auth error as auth failure
Gemini's native API answers an invalid key with 400 INVALID_ARGUMENT /
API_KEY_INVALID. Since the connection check now treats any typed 400 as
reachable, that showed "连接正常,模型可用" for a bad key. Keep the 400 pass
only when the body does not describe a credential problem, and let
classifyConnectionError recognise those bodies so the message says
认证失败 instead of a bare 连接失败.
---------
Co-authored-by: wizardchen <wizardchen@tencent.com>
Running `make docs` on main no longer reproduces the committed docs/*:
every definition loses its package-qualified name (types.* instead of
github_com_Tencent_WeKnora_internal_types.*), enums disappear, ErrorCode
becomes a plain integer, and docs/swagger_contract_test.go fails
(TestModelDeleteUsageContract).
Cause: internal/localsandbox is not a dependency of cmd/server (its
importers are behind the `desktop` build tag), but swag's directory walk
reaches it. Its `const X = core.X` aliases make swag load
internal/localsandbox/core again through go/loader, and that second load
re-registers every already-deduplicated type under its short name without
enum values. Excluding the directory removes the second load.
That load was also hiding a second problem: skill_handler.go references
errors.AppError in @Failure without importing internal/errors, so with the
exclude swag stops with "cannot find type definition: errors.AppError".
A blank import lets swag resolve it.
Co-authored-by: Victor Maznyuk <victor@maznyuk.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(frontend): 修复复制模型时模型名称被改写的问题
* fix(model): preserve model name and credentials when copying a config
Copying rewrote the upstream model name and posted redacted parameters, so the duplicate could not authenticate. Clone the stored row, cap the display name, and skip a new download when the local model is already active.
* fix(lint): clear new golangci-lint findings on model copy
Check c.Error results, wrap the long test line, and format the stub. The pull request lint range also includes the new HTTP error test, whose unused request parameter failed revive.
---------
Co-authored-by: wizardchen <wizardchen@tencent.com>