Commit Graph

213 Commits (main)

Author SHA1 Message Date
lyingbug 09b9c98d54
fix: preserve business session identity in model requests (#4491)
* fix: preserve business session identity in model requests

* fix: propagate session identity to auxiliary model calls
2026-10-19 22:14:09 +08:00
lyingbug ba253bcbac
feat(agent): unified agent permission model with grants and run modes (#4490)
* 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.
2026-10-19 20:52:15 +08:00
lyingbug 2e8b3aa729
fix(agent): let open_page finish the turn with the answer above it (#4472)
* 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
2026-10-19 14:47:43 +08:00
lyingbug 966d841d19
feat(assistant): add durable multi-agent collaboration and live task views (#4438)
* 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
2026-10-19 12:14:15 +08:00
lyingbug 7115cb2a61
feat(assistant): trial runs, session grants, page links, and MCP/model/skill management (#4375)
* 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
2026-10-16 23:36:01 +08:00
AstonKrss 12e3e49d80
fix(chat): persist failed quick-answer turns so errors survive refresh (#4306)
* 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
2026-10-16 17:50:14 +08:00
lyingbug 4d4acec418
feat(assistant): manage agents and skills, separate history, refresh pages (#4344)
* 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
2026-10-15 21:43:20 +08:00
lyingbug 450b6ed1b7
feat(assistant): side panel, access levels and role-aware operations (#4342)
* feat(frontend): add dockable assistant side panel

* feat(assistant): access levels, role-aware operations and assistant settings

* fix(assistant): preserve approval and workspace access safeguards
2026-10-15 18:18:22 +08:00
lyingbug 687b178706
feat(agent): add the built-in WeKnora assistant with an operation catalog (#4302)
* 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
2026-10-15 12:18:30 +08:00
lyingbug 234aa948db
docs(swagger): document the real request and response types (#4304)
* 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.
2026-10-15 01:41:42 +08:00
lyingbug 383d26535a
feat(agent): persist human-in-the-loop prompts with a shared broker (#4250)
* 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
2026-10-14 20:37:28 +08:00
Ochan Kwon 31c6055687
feat(agent): name the turn's chat model on the completion event (#4252)
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.
2026-10-13 23:07:32 +08:00
lyingbug 194bffbb0a
feat(agent): read chat attachments on demand (#4203)
* 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
2026-10-13 14:37:17 +08:00
nullptr-error 150d8cc605
feat(sandbox): Docker 后端支持交互式终端 (#4023)
Docker 沙箱后端支持会话侧栏的交互式终端:TTY exec 劫持连接收发原始字节,窗口大小走 ExecResize;终端打开期间定期刷新空闲回收活动标记。

Docker exec 无法重新附着,关闭时按每次打开注入的 WEKNORA_TERMINAL_ID 向 shell 及其子进程发送 SIGHUP(nohup 任务保留),仅对仍存活的 shell 补 SIGKILL。ready 帧新增 reattachable,Docker 为 false 时前端不自动重连。Docker 沙箱未运行时返回 SANDBOX_STOPPED,提示可能已被回收。

Co-authored-by: WHUTcjh-2024 <202126324+WHUTcjh-2024@users.noreply.github.com>
2026-10-10 21:38:03 +08:00
诉说晚秋 932b750b2f
fix(agent): preserve steering order across persistence failures (#4078)
* fix(agent): 保持追加指令在持久化失败后的消费顺序

* fix(session): 限制追加指令持久化重试次数,避免单条消息阻塞队列

同一条追加指令的用户消息连续写库失败 3 次后,将其标记为 consumed+dropped 退出队列,
后续指令按原顺序继续注入,也不会把它作为 follow-up 的 query 导致整批积压滞留。
入队时去除 NUL 字符(PostgreSQL text 列不接受)。

---------

Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-10 20:32:20 +08:00
Sairaj-24 8125ed250f
fix(chat): keep custom metadata on knowledge-chat references (#4087)
* 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>
2026-10-10 14:20:38 +08:00
lyingbug 65f88f4121
feat: judge image hits by their image in rerank and show them to vision models (#4013)
* 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
2026-10-09 13:01:48 +08:00
hailongzhao bccb4b151b fix(embed): 内嵌网页只传图片不输入文字时不再返回 400
内嵌网页的输入框允许只带图片或附件就点击发送,但 CreateKnowledgeQARequest.Query
带有 binding:"required",parseQARequest 也拒绝空 query,于是只传图片直接返回
400 "Query content cannot be empty"。

入口处理:去掉 binding:"required";文字为空但带有内联图片数据或内联附件时,
用 types.UploadOnlyQuestion 生成一句替用户提问的问题(中文界面为「请根据我
上传的内容回答。」,其他语言为英文),交给模型、检索、标题、会话历史索引、
追问建议和记忆使用。只有 URL 的图片不算上传,因为客户端传入的图片 URL 会被
清掉;预上传的 attachment_ids 也不算,这类文件在流开始后才解析,可能失败或
超时,届时模型没有任何内容可答。其余空 query 仍返回 400。

存储与显示:qaRequestContext 新增 userInput,保存用户消息时只存用户实际
输入,只传图片时为空,刷新后与发送当下显示一致;query 仍是给模型的问题。
steer 追问复制上一轮的请求上下文,显式设置 userInput,避免在只传图片的一轮
之后把追问存成空消息。

会话历史:文字为空但带图片或附件的用户消息,在两处历史重建里补上同一句
问题。知识问答流水线(loadAndProcessHistory)原先会整轮丢弃;Agent 历史
(LoadAgentHistory)原先会发出空的用户消息,被 SanitizeMessages 剔除后
前后两条回答被合并。

去掉 binding 标签会让 gofmt 重新对齐整个 CreateKnowledgeQARequest 的行尾
注释,这些既有的超长行因此会被 PR 的增量 lint 视为新增。按仓库惯例把字段
注释移到字段上一行(注释文字不变,swagger 描述不受影响),并把 Go 字段
KnowledgeIds 改名为 KnowledgeIDs(JSON 名仍是 knowledge_ids,接口不变)。

同步更新 swagger 文档,query 不再是必填字段。
2026-09-30 15:26:51 +08:00
Victor Maznyuk bad7afa6ae fix(sandbox): pass desktop slot timing to the renew goroutine
renewDesktopSlot read desktopSlotRenew and desktopSlotLease from its own
goroutine. release() stops that goroutine without waiting for it, so the
read is unordered with the test cleanup that restores the values, and
`go test -race ./internal/handler/session/` fails in
TestDesktopSlotCancelsHoldWhenKeyExpires on every run.

acquireDesktopSlot now reads both durations before starting the goroutine
and passes them in; the go statement orders the reads, and the renew loop
no longer touches the package variables. Behaviour is unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 22:01:39 +08:00
wizardchen 6c83d7ab47 revert: take the plugin system back out of main
Reverts the eleven plugin system PRs merged on 2026-09-26 so they can be
reviewed before landing:

* a829d7cc9 agent tools served by plugins (#3733)
* 4f5d475c3 Jira example plugin (#3730)
* 01222aac8 dynamic form options, OAuth connections and resource limits (#3729)
* cf502ba46 event delivery and webhooks (#3728)
* 996696057 sandboxed plugin pages (#3727)
* da4ef68d9 standalone plugin hosts (#3725)
* 728007ada remote runtime, Python SDK (#3724)
* ff49f9491 Host API and document parsers (#3721)
* 4328ab26a code plugins (#3720)
* ed63e35cc declarative plugins (#3716)
* c91a8d11f plugin system foundation (#3711)

The tree is back to 47773b5bd, migrations included: no environment ran
the plugin migrations (versioned 000115-000119, sqlite 000034-000038).
2026-09-26 14:58:18 +08:00
lyingbug cf502ba46a
feat(plugin): event delivery and webhooks for plugins (P2 batch 6) (#3728)
* feat(plugin): event delivery and webhooks for plugins
2026-09-26 14:47:13 +08:00
lyingbug 1bf717a54d
feat(chat): open cited documents at the cited passage (#3700)
* feat(chat): open cited documents at the cited passage

Clicking a citation used to show only the parsed chunk. It now opens the
original file in the references panel, jumps to the cited place and
highlights it, narrowed to the sentence the citation supports.

Parsing records where each chunk sits in the original file
(chunks.source_locators): PDF page and paragraph boxes from the docreader,
MinerU and PaddleOCR-VL layouts; Word paragraphs, slides, sheet rows and
EPUB chapters aligned in Go against any parser engine's Markdown; text
offsets for Markdown/TXT; segment times for audio. Pipeline text rewrites
are followed with a line-diff remapper. Scanned PDF pages get their OCR
text as quotes at search time so a sentence can pick its page.

The frontend renders PDFs with pdf.js and every other previewable type
with the existing preview, then highlights with the CSS Custom Highlight
API in a highlighter yellow that stays visible against the brand green.

* fix(docreader): serialize source blocks outside main so tests import it

test_docx_tables stubs docreader.parser in sys.modules, so importing
docreader.main from a later test failed in the full unittest discover run.
The wire conversion now lives in docreader.source_wire, which needs only
the proto.

* fix(chat): tighten source locators from review

- Remap rewritten-line-for-line stretches by line so scanned PDF pages
  no longer drift onto the wrong page.
- Keep the source preview mounted for citations in the file already open.
- Wait for in-flight PDF page renders before looking for the text layer.
- Count image rune offsets in one pass; stream xlsx rows up to maxUnits.
- Start text locators after a UTF-8 BOM, as viewers decode without it.
- Only re-query image children for scanned-page results.
- Seek audio citations without autoplay and drop stale seek listeners.
- Fix the SQLite migration's cross-reference to versioned/000113.

* fix(migrations): renumber chunk source locators after main's chunk_images

main took versioned 000113 and sqlite 000032 for chunk_images, so the
source_locators column moves to versioned 000114 and sqlite 000033.
2026-09-25 13:26:16 +08:00
lyingbug 04adc13272
fix(retrieval): fix recall correctness, score scales, cost and agent tools (#3687)
* fix(retrieval): keep index writes and shared-KB lookups correct

Index writes
- Image OCR/caption chunks were indexed without IsEnabled, so every engine
  but Postgres stored them disabled and retrieval never returned them.
  The SQLite engine re-enables the affected rows at startup.
- FAQ edits, similar-question additions and import merges re-index under
  the old SourceID and relied on the engine overwriting it. Postgres and
  SQLite kept the stale row (ON CONFLICT DO NOTHING); ES v8 and Qdrant
  mint a new document ID and kept both. FAQ re-indexing now deletes the
  old rows first, and Postgres/SQLite BatchSave upserts by
  (source_id, source_type).
- Postgres: drop the GORM default tag on is_enabled, which replaced false
  with true on insert and indexed disabled chunks as enabled.
- SQLite: BatchSave no longer attaches vectors and FTS rows to the wrong
  rows when part of a batch already exists, and vecTables is guarded
  against concurrent map writes.
- CopyIndices: Postgres filters to the copied knowledge, pages by id and
  keeps is_enabled; SQLite copies every row of a chunk (generated
  questions included) with stable source IDs and enabled state.

Shared knowledge bases
- Chat merge: FAQ answer population and neighbor expansion look chunks up
  without the caller-tenant filter, like parent resolution (#3342).
- Neighbor expansion never cuts the retrieval hit; the length budget goes
  to the text adjacent to it.
- FAQ negative questions are applied whenever an FAQ KB is in scope and
  to chunks of shared FAQ KBs.
- Search results get image_info for shared-KB chunks.
- search_knowledge reads FAQ metadata from the search result instead of
  one tenant-scoped query per hit, so shared FAQs render their answers.

* fix(retrieval): put every retrieval score on one scale

Scores from different retrieval paths were ranked together while living on
different scales, so ordering depended on which path produced a hit.

Fusion
- RRF ranked a chunk by its position in the concatenation of every
  vector (or keyword) list, appended in goroutine completion order. The
  second list's best hit ranked behind every hit of the first, and the
  order changed between identical requests. Each list is now ranked on
  its own by score and a chunk takes its best rank.
- RRF is divided by its maximum, so hybrid scores land in [0, 1] like
  vector-only (cosine) and keyword-only (rescaled BM25) results. Raw RRF
  topped out near 0.016 and lost to any single-retriever hit it was ranked
  against across searches (document targets, model groups, FAQ calls);
  rerank's base-score term and MMR's relevance term had nothing to use.
- Keyword-only BM25 is rescaled per list; engines' BM25 is not comparable.
- FAQ iterative retrieval fuses each round like the first pass instead of
  sorting raw BM25 and cosine together, starts at twice the depth already
  searched, triggers when any single vector list is full (the old summed
  count never matched with more than one list) and replaces results per
  round.

Rerank and chat pipeline
- The FAQ boost is no longer capped at 1; capping made strong FAQs tie at
  1.0 and fall to the tie-breaker. The composite score before boosts is
  kept as composite_score.
- The FAQ direct-answer threshold is compared against that pre-boost
  score, and the FAQ that cleared it is the one marked match="exact"
  rather than the first FAQ.
- Graph hits no longer carry a fabricated retrieval score of 1.0, which
  ranked them above every scored hit when rerank did not run; the
  composite score uses the model score in its place.

Engines
- OpenSearch and Weaviate return (1 + cos) / 2; their drivers now report
  cosine similarity and map thresholds onto the engine scale, so a
  threshold means the same on every engine.
- Milvus L2 returned squared distance, ranked farthest-first downstream,
  and took the threshold as a radius; scores and radius are converted.
- The multi-store normalizer no longer maps Milvus through (s + 1) / 2,
  which put it on a different scale from every other engine and from its
  own single-store results.

Docs updated for fusion, normalization, FAQ boost and iterative recall.

* perf(retrieval): bound rerank, agent and pipeline cost; stop failing on slow or missing models

Rerank
- Rerankers report the longest document a request can carry
  (max_document_chars / max_request_chars minus the query) and the rerank
  stage fits its own passages to it, trimming appended captions, OCR and
  generated questions first. One chunk with a large screenshot's OCR used
  to exceed the vendor limit and fail the whole batch, so every candidate
  lost its score and the threshold stopped applying.
- Rerank HTTP requests default to a 60 s timeout; chat and agent contexts
  carry no deadline, so a stalled self-hosted rerank server held the turn
  open.
- OCR and caption chunks no longer repeat their own text from image_info in
  the passage.
- The chat pipeline and the agent tool rerank at most 200 candidates, best
  retrieval score first.
- A rerank model that cannot be loaded degrades to retrieval order instead
  of failing every chat turn, as the search APIs already do; without rerank
  results the merge stage keeps only RerankTopK hits instead of enriching
  every one.

Retrieval APIs
- knowledge-search match_count and rerank.top_k are capped at 200
  (unbounded values multiplied into tens of thousands of billed rerank
  passages); normalizedMatchCount clamps to the pool size so the
  over-retrieval arithmetic cannot overflow.
- hybrid-search with rerank recalls at least rerank.top_k deep.

Agent
- search_knowledge fits its rendered output to four fifths of the tool
  output budget, dropping the lowest-ranked rows and telling the model how
  many it omitted; the model's view is rebuilt from Data, which registry
  truncation never reached.
- Agent searches skip neighbor/parent/related enrichment rows, which were
  never retrieved yet tripled the rerank input.
- ParallelToolCalls is enabled. The model was always told it may call tools
  in parallel while the engine ran them one by one; only read-only tools
  overlap, anything else stays a barrier.

Chat pipeline
- Query expansion searches keywords only (its variants are local rewrites
  whose embeddings repeat the main search) and is skipped when keyword
  matching is off.
- Entity extraction, a second LLM call, is skipped for intents that need no
  KB retrieval and uses the rewritten query.
- Partial-overlap dedup tokenizes each text once instead of per pair, and
  only compares token overlap between texts within 3x of each other's size.

Storage
- Migration 000112 adds btree indexes on embeddings(knowledge_id) and
  (chunk_id); document deletes, chunk re-index and enable/tag updates
  scanned the whole table.
- Shared-KB knowledge rows are fetched in one query instead of one per ID.
- Drop GORM Debug() from the ParadeDB keyword query and the knowledge batch
  lookup, which logged SQL and user queries on every search.

Docs updated for the API limits, rerank timeout and passage fitting, agent
parallel tools and output budget, and pipeline changes.

* fix(retrieval): make agent tools and pipeline stages report what they did

Agent tools
- query_knowledge_graph now queries the graph store: entity names from the
  query are matched in each KB's graph, relations are returned (and shown to
  the model), and the entities' source chunks lead the results, with text
  search as a supplement. It used to run text search only, so a graph-only
  KB always answered "no relevant graph information".
- search_knowledge reports failures instead of "no matching chunks": when
  every search fails the tool fails with the reason; partial failures are
  listed. A failed query embedding falls back to keyword search for hybrid
  KBs, as the chat pipeline does.
- Keyword mode uses rerank to order hits, not to reject them (identifiers
  score low), and the empty-result hint no longer sends keyword mode back to
  keyword mode.
- Dedup keeps siblings under one parent, no longer merges every image chunk
  of a document through chunk_index 0, and keeps the better-scored copy.
- Search rows omit a <match> excerpt that only repeats the content; snippet
  terms are segmented for Chinese queries and skip stopwords, and FAQ
  matched questions are chosen by match strength.
- read_document query mode returns next_offset when truncated and resumes
  from offset.
- wiki_search over-fetches under document/tag scopes before filtering and
  says when every match was out of scope.
- Prompts point to read_document(id=cN, context=k) for surrounding text.
- The agent editor hides the retrieval-strategy section in agent mode,
  where search_knowledge uses the global retrieval settings.

Chat pipeline
- Intent labels are normalized; an unknown label retrieves instead of
  silently skipping the knowledge base, and web_search without web search
  enabled searches the knowledge bases.
- Image turns get a 2048-token rewrite budget, and a reply cut off by the
  cap is salvaged field by field instead of being discarded.
- History references are matched by how much of the query they cover;
  Jaccard against chunk-sized text never reached its threshold.
- Entity search resolves chunks of org-shared KBs within the turn's KB
  scope, skips chunks whose document is gone (it used to panic) and caps
  graph chunks at 30.
- Empty history is not fetched twice; fetched pages are cut on a rune
  boundary.

Retrieval
- A multi-KB search whose primary KB has no vectors embeds the query with a
  vector KB's model instead of failing on an empty model ID.
- Rerank passages include the chunk's heading breadcrumb, which is part of
  what was embedded.
- SQLite FTS searches the content column only and turns a lone Han
  character into a prefix query; TencentVectorDB ef follows TopK.

Docs updated for the agent tools and pipeline stages.

* fix(retrieval): address review findings on the retrieval fixes

- Restore NeedsRetrieval for web_search without web search enabled: the
  intent prompt "web_search" is how the user learns web search is off, and
  running KB retrieval instead bypassed it.
- query_knowledge_graph keeps the case of entity terms; Neo4j matches node
  names with case-sensitive CONTAINS, so lowercased terms never matched
  English entities.
- An empty search_knowledge or query_knowledge_graph result states partial
  failures in its text, which is all the model sees for an empty result.
- SQLite BatchSave replaces a source in one transaction, so a failed insert
  keeps the old rows instead of leaving the source unindexed.
- Reuse stringSliceValue and an exported searchutil.ContainsChinese instead
  of new copies; drop an unused named return and the FAQ obsolete-source
  delete that the full per-chunk delete now covers.

* fix(retrieval): address second review of the retrieval fixes

- query_knowledge_graph: under a document/tag scope, keep only relations
  whose entities come from an in-scope evidence chunk (the graph namespace
  is the whole KB); drop chunks whose document no longer exists; report a
  graph or text search failure even when the other source returned hits.
- search_knowledge: record the hybrid -> keyword fallback taken when the
  query embedding fails in mode_fallbacks, so an empty result is not read
  as "no semantic match".
- query understanding salvage: take a cut-off value only for the image
  description; a truncated rewrite_query or intent is dropped instead of
  replacing the user's query.
- Graph hits (no retrieval score) are kept past the no-rerank RerankTopK
  cut and the rerank candidate cap instead of always falling below them.
- FAQ boost is capped at 1 again so scores stay on the [0, 1] scale; FAQs
  tied at the cap are ordered by their pre-boost score.
- Negative-question filtering loads only candidates of FAQ knowledge bases.
- read_document query continuation starts one chunk before offset so the
  first match keeps its preceding context at a page boundary.
- graphSearchTerms and searchQueryTokens share one queryTerms splitter.
2026-09-25 10:48:18 +08:00
nullptr-error 65d8a34ead
fix(desktop): pair the Lite browser against the local API listener (#3677)
* fix(desktop): pair the Lite browser against the local API listener

The Wails page origin cannot become the extension WebSocket, and a page-controlled host must not be able to redirect that pairing link.

* fix(desktop): check the proxy test response body close

golangci-lint errcheck rejects an unchecked Body.Close in the new desktop proxy tests.

---------

Co-authored-by: hailongzhao <hailongzhao@tencent.com>
2026-09-24 20:43:25 +08:00
lyingbug 9fc08c2079
feat(retrieval): unify rerank across search APIs and expose diagnostics (#3675)
* feat(retrieval): unify rerank across search APIs and expose diagnostics

The two retrieval APIs each missed half of the job: hybrid-search could
tune recall but never reranked, knowledge-search always reranked with the
tenant config and exposed no recall parameters. Rerank itself lived in
four places with drifting thresholds, passages and composite scores.

- internal/reranking: one rerank stage (passage = title + cleaned body +
  captions/OCR + generated questions, threshold with degradation and
  top-1 fallback, composite score, MMR) used by the chat pipeline, the
  agent search_knowledge tool and both APIs.
- hybrid-search: optional `rerank` object; absent keeps the old behavior.
- knowledge-search: vector/keyword thresholds, match_count, recall-path
  switches and a `rerank` object that can override or disable rerank.
- Rerank model resolution: request > tenant RetrievalConfig > first
  rerank model; an unknown requested model is a 400. Load or call
  failures degrade to retrieval order instead of failing the search.
- Responses carry meta.rerank (outcome, model, thresholds, top score) so
  an empty result explains itself (#2391).
- Go SDK and website-docs updated, including a "which API" section.

Refs #2976

* docs(retrieval): lead with which search API to use and when

knowledge-search is the default for callers; hybrid-search is the
low-level recall interface. Add a scenario table so the choice does not
hinge on reading the whole capability comparison.
2026-09-24 20:41:49 +08:00
wizardchen 02734d7499 feat(chat): add session reasoning controls and polish model configuration 2026-09-23 17:12:19 +08:00
徐少 2c6ae0c262
fix(session): reject invalid QA queries before session lookup (#3477)
* fix(session): reject invalid QA queries before session lookup

* fix(session): narrow shared QA input validation
2026-09-23 12:01:33 +08:00
hahahahahayesyeseys 407b184081 fix(chat): report truncated model fallback answers 2026-09-23 11:57:21 +08:00
hahahahahayesyeseys 78d7d862e0 fix(chat): surface truncated quick answers 2026-09-22 19:44:38 +08:00
nullptr-error 22cbcdfa57
feat(sandbox): run unpinned Lite sessions on the host OS sandbox (#3549)
* feat(sandbox): resolve workspace paths through WorkspaceLayout

Keep remote sessions on the /workspace contract, while file, shell, and
artifact code follow the session layout instead of hardcoded paths.

* fix(sandbox): fail closed on host layout lookup and restore the shell blacklist

Treat host vs remote as an explicit origin, refuse inspect outside ReadRoots,
and skip collection when the output tree is missing or equals the project root.

* fix(sandbox): close leftover fail-open holes in the layout path

Keep host copy, collection, and prompt text from falling back to /workspace when a lookup fails or an adapter returns unclean roots.

* fix(sandbox): satisfy golangci-lint on the layout helpers

Wrap new copy and test lines to 120 columns, and add the exported comments revive requires.

* fix(sandbox): gofmt the read_file layout copy wrap

* feat(sandbox): add host as an OS-enforced backend type

Host is not a named/pinnable config: each command is a fresh local process, unlike Docker, Cube, and E2B.

* feat(session): persist Lite host workspace directory

Empty means an auto-allocated folder. Standard edition leaves the column unused so the shared session model still loads. SQLite also gains the tenant skill tables Lite shell_exec already expects.

* feat(localsandbox): adapt the host OS sandbox to session interfaces

File tools stay outside Seatbelt and are bounded by PathGuard. A revoked project directory fails closed instead of allocating a replacement workspace.

* feat(sandbox): run unpinned Lite sessions on the host backend

Lite opts into host explicitly; web stays disabled when no named remote config exists. Host workspaces are not destroyed or auto-committed.

* feat(desktop): pick and persist host project directories

The native folder dialog is the authorization path; typed paths are rejected. settings.sandbox.host tells the client when this edition can use it.

* fix(sandbox): fail closed on Lite host layout lookup misses

Unpinned host sessions were described as /workspace when pin read or
sandbox resolve failed. Prompts and attachment staging now share the
same fallback so Lite never pretends the remote tree exists.

* fix(frontend): keep settings.sandbox.host in sync with the backend keys

TestDeploymentCapabilityKeysMatchFrontend requires the lists to match. Host stays fail-closed like docker so a missed probe does not show Lite-only UI.

* fix(lint): satisfy golangci-lint on the host sandbox wiring

Check c.Error, wrap lines over 120 columns, put context first on versionsWorkspace, and document exported adapter methods.

---------

Co-authored-by: hailongzhao <hailongzhao@tencent.com>
2026-09-22 19:35:03 +08:00
lyingbug 33c0333ec9
fix(chat): restore shared workspace images after stream completion (#3523)
* fix(chat): restore shared workspace images after stream completion

* test(chat): wrap shared image completion cases for lint

* fix(chat): wait for persisted completion and preserve streamed replies
2026-09-22 00:16:58 +08:00
Leo Dawn 56d075e213
fix(sandbox): resolve a session's pinned sandbox in the workspace that owns it (#3471)
* fix(sandbox): resolve a session's pinned sandbox in the workspace that owns it

tenant_sandbox_configs is keyed by (tenant_id, id), so a config id is not an
address on its own. sessions.sandbox_config_id stored only the id and every
reader took the workspace from the ambient request context.

That holds inside a chat turn, which already runs under the agent's workspace
(WithExecutionTenant in the QA handler). It breaks for a shared agent
everywhere else, because a shared agent runs on ITS OWNER's sandbox config
while the session belongs to the borrower, and these paths run from plain
requests whose only tenant is the session owner's:

  * DeleteSession resolved nothing and returned after a warning. Cube and E2B
    create session sandboxes with onTimeout=pause, so the MicroVM was not
    reclaimed later either: it stayed paused, billing, with nobody holding its
    id. ReapOrphanSandboxes has no production caller, so nothing recovered it.
  * The terminal and desktop panels failed on both branches - attaching to the
    pinned sandbox and provisioning a new one - with ErrSandboxConfigNotFound,
    which terminalErrorFrame maps to a bare INTERNAL close reason. The panel is
    offered unconditionally and already forwards agent_source_tenant_id, so
    this was a dead end the user could reach in one click.
  * Fork read the pin through PinnedSessionSandbox, got no manager, and
    silently degraded to SNAPSHOT_UNSUPPORTED, losing the sandbox state.
  * The fork snapshot lease recorded the session's workspace next to the
    lending workspace's config id, so the reaper could not resolve it either.

Record the owning workspace beside the pin and make the pair travel together
as SandboxPin. Readers now take the workspace from the pin and fall back to the
session's own, which is what every non-borrowed pin (and every row written
before this column) resolves to - so behaviour for own agents is unchanged.

The provision path has no pin yet, so the WebSocket handler passes the agent's
workspace along with its config: terminalProvisionPin already resolved the
shared agent, it just discarded the tenant resolveAgent handed back.

Backfill in the migration is limited to sessions whose pinned config does not
exist in their own workspace - the only ones that can have borrowed it - using
the lending workspace recorded on their newest shared-agent message. Lite has
no shared spaces, so the SQLite mirror adds the column without a backfill.

* fix(sandbox): backfill the pin owner from the config row and self-heal legacy pins

Three gaps in the session sandbox pin owner:

Backfilling from messages.agent_tenant_id names the wrong workspace. The
pin is sticky to the session's FIRST sandbox, while the newest message
carrying agent_tenant_id may belong to a later shared agent from another
workspace. Writing that tenant leaves teardown resolving a config the
workspace does not own - the very failure the column exists to fix.
tenant_sandbox_configs.id is a global UUID primary key, so joining the
config row itself names the workspace that actually owns the pin.

The column was INTEGER while every other tenant id is BIGINT/uint64.
Postgres INTEGER is 32-bit signed, so a large tenant id would not fit.

Rows the SQL backfill cannot reach keep sandbox_config_tenant_id = 0
forever: the reader falls back to the caller's workspace but never
records what it learned. The next chat turn already runs under the
workspace that can resolve the config, so persisting it there is what
lets a later DELETE, panel open or fork find the sandbox. recordOwner
only writes when the lookup actually succeeded and the stored owner is
still unset - stamping the caller's tenant onto a failed lookup would
brand a sticky pin left by a previous shared agent with the wrong
workspace.

Also renames the lentSandboxConfg typo and corrects the fork degrade
reason in a comment: a lent config that resolves to nil fails
BoundSandboxID, so the fork degrades to SANDBOX_GONE, not
SNAPSHOT_UNSUPPORTED.

* fix(sandbox): require a named backend before recording a pin's owner

The self-heal wants to persist an owner "that actually resolved this config",
but a nil error does not prove that. resolveTenantSandboxForConfig returns a
disabled manager with no error twice before it ever reads the config row: for
the workspace kill switch, and for an empty or deployment-default config id.

That reopens the leak this column exists to close. The SQL backfill correctly
leaves sandbox_config_tenant_id at 0 whenever the pinned config belongs to the
session's own workspace, which is most existing rows. One turn of a shared
agent lent by a workspace whose admin has script execution turned off then
short-circuits on the kill switch, returns nil, and stamps that lending
workspace onto a config it does not own. The next DELETE resolves the pin there,
finds nothing, and strands the paused MicroVM.

The pin branch runs before agentConfigID is read, so the shared agent does not
even need a sandbox config of its own to trigger it.

A named backend (Cube/E2B/Docker) is the proof, and it is the same condition
that is already allowed to CREATE a pin further down: what may write a pin may
update whose it is. A config that exists but resolves to type "disabled" is
skipped as well - ownership is genuine there, but such a config never creates a
sandbox, so no teardown can go missing.

The deployment-default pin was inert either way (both workspaces short-circuit
to a manager with no DestroySession), but it is covered too so a later
relaxation of the proof cannot quietly reopen the kill-switch case.

Both tests fail without the guard.

---------

Co-authored-by: hailongzhao <hailongzhao@tencent.com>
2026-09-21 15:38:39 +08:00
nullptr-error d4b9fd0c72
feat(session): in-place rewind with workspace checkpoint reset (#3469)
* refactor(session): extract shared workspace git reset helper

Fork bootstrap and in-place rewind both need the same /workspace reset
script. Move it out of fork_bootstrapper so rewind can reuse it without
copying ExecShellCommand plumbing.

* feat(message): add DeleteMessagesFrom for rewind truncation

Rewind needs a composite created_at+id cursor so same-millisecond
messages after the fork point are not left behind. Delete inside a
transaction and return the rows so callers can log the count.

* feat(session): add in-place rewind service

Truncate the current session at a user or assistant message and git-reset
the live sandbox when a reachable checkpoint exists. Reset failure is
fail-closed so messages are never deleted ahead of the workspace.

* feat(session): expose POST /sessions/:id/rewind

Wire SessionRewindService through the session handler and container so
the client can rewind in place. Busy sources map to 409; git reset
failures stay 500.

* feat(chat): add rewind API client and i18n copy

Expose rewindSession with the same 180s timeout as fork, and add
chat.rewind strings in all five locales so the confirm dialog is not
hardcoded Chinese.

* feat(chat): add rewind button with confirm dialog

Offer in-place rewind next to fork on user and assistant messages.
Confirm before truncating the thread, then reset locally and prefill
the original question when the cut point is a user message.

* fix(chat): confirm rewind with a compact popover

Replace the full-page confirm dialog with a small popconfirm above the
rewind button, and shorten the swagger description to satisfy line length.

* fix(chat): skip markdown images with an empty destination

Empty ![]() was rendered as <img src="">, which shows as a broken image in the reply.

* fix(chat): clip sandbox panel slide-in and rename open tooltip

Keep the enter animation inside the viewport so it cannot flash a document
scrollbar and jump the page. Rename the header toggle from sandbox terminal
to expand sidebar.

* fix(session): 回滚时完成截断、互斥发送并重拉历史

客户端中断不再让 git reset 成功后留下未删的消息;reset/删消息前复查 busy,并锁住当前会话输入。成功后重拉历史,避免切会话预填串台和 steer 分段截错。

* fix(session): 工作区 git 外置,并让未开箱 fork 的回滚对齐 SHA

checkpoint、回滚和 fork 共用 --git-dir=/var/lib/weknora/workspace.git,避免 rm -rf /workspace 丢掉历史。
未开箱分叉会话回滚时改写或清除 ForkBootstrap,避免第一次开箱仍 reset 到旧切点。

* fix(session): 回滚加会话锁,并堵住发送中回滚与脏 SHA

同一会话并发回滚互斥(进程内 + Redis),冲突返回 409。发送/流式中禁用回滚按钮;历史重拉成功后再改界面。未开箱 fork 的 checkpoint SHA 必须是 40 位 hex。工作区 git 只认外置 GIT_DIR,不再 mv/rm 根上的 .git。

* fix(session): 未开箱 fork 回滚成功时不要提示没有沙箱

ForkBootstrap 已对齐切点后返回 workspace_reset,前端走「已回滚」;清掉引导时改报 NO_CHECKPOINT。纯聊天仍用 NO_SANDBOX。

* fix(chat): stub composerLocked in steer interaction tests

handleSteerMsg now bails when rewind locks the composer. The VM harness
did not provide that ref, so CI threw ReferenceError on every steer case.

* fix(session): allow git-layout mkdir in pinned checkpoint test

SkipWorkspacePrep still omits the input/output bootstrap exec. The
checkpoint script now mkdirs WORK_TREE and GIT_DIR, so the old
"command must not contain mkdir" assertion was stale.

* fix(session): block send while rewind holds the session lock

BeginTurn now fails if the rewind key is held, so AgentQA cannot start
during git reset. Knowledge-chat and executeQA check the same lock
before persisting messages. composerLocked is still page-local.

* fix(session): close send/rewind races and fail closed without a checkpoint

Hold the turn lease before persist so rewind cannot truncate an in-flight
send. TryLockRewind fails while a turn is live; emptying the conversation
resets the workspace through the same git path as a SHA rewind.

* fix(session): wrap rewind reset call to satisfy line length lint

* fix(session): fail closed on a replaced sandbox and close leftover rewind holes

Do not truncate history when the live workspace cannot follow the checkpoint, retry deletes after a successful git reset, and keep send and rewind exclusive even without a sandbox manager.

* fix(session): address rewind review findings

Correctness:

- Adopt a pre-move /workspace/.git into SessionGitDir on first use. Sandboxes
  provisioned before the git dir moved out of the work tree still hold their
  checkpoints there, so every SHA recorded on those turns stopped resolving:
  rewind 500'd instead of truncating and fork's rollback failed on a bad
  object. Adoption is guarded on the new dir being absent and on the work-tree
  repo carrying the checkpointer's committer identity, so an agent's own
  `git init` in /workspace is left alone.
- Only fail a send closed when BeginSessionTurn reports a rewind lock. Every
  other lease error degrades to running without a lease, as before rewind
  existed; a Redis blip on the lease script was rejecting the user's message.
- Release an abandoned fork snapshot after the truncate lands, not before.
  Clearing the bootstrap column is a DB write a retry can redo; deleting the
  snapshot is not, and a delete that exhausted its retries left the fork with
  no workspace to boot from under a full transcript.
- Re-acquire the rewind lock when a renew call errors, not just when it
  reports the lease lost. Sitting the tick out let a short Redis outage expire
  the 2m key mid-reset and hand the session to a second rewind.
- Keep the history cursor when a post-rewind reload fails. Clearing it sent
  the next scroll-up back to the newest page, which the kept prefix already
  holds, instead of to older messages.

Efficiency:

- Add ListAssistantCheckpointsUpTo and use it to answer "which checkpoint does
  kept history still reach". Rewind was reading every message body and artifact
  row in the session to find one SHA.
- Take the send-side turn lease once per request. The handler already holds it
  before persisting; QARequest.TurnLeaseHeld lets the QA services skip their
  own, so IM/MCP still take one and HTTP send stops doubling every rewind check
  and lease round trip.
- Batch the suggestion delete behind DeleteByMessageIDs instead of one query
  per deleted message while the rewind lock is held.
- Resolve the rewind affordance for the whole transcript in one pass rather
  than two list scans per rendered row on every streamed token.

Cleanup:

- Drop the SANDBOX_REPLACED skip reason, which the service never produces (it
  fail-closes with a 409), along with its copy in all five locales.
- Drop GetMessagesBySession from rewindMessageStore; rewind never calls it.
- Drop the unused chat.rewind.confirmTitle copy from all five locales.
- Restore the chatHeader.toggleSandboxPanel wording this branch had changed
  unrelated to rewind.

---------

Co-authored-by: hailongzhao <hailongzhao@tencent.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-20 21:01:00 +08:00
lyingbug 093c16cbb3
fix(agent): end the turn when the completion cap truncates an answer (#3449)
* fix(agent): end the turn when the completion cap truncates an answer

A round that came back with finish_reason=length and no tool calls used to
fall through analyzeResponse as non-terminal. With no tool calls to run,
appendToolResults pushed the half-written answer back into the history as a
plain assistant message with nothing telling the model to continue, so the
next round rewrote the answer from the top, hit the same cap, and repeated
until the round budget ran out or the user cancelled.

Three guards, each independently load-bearing:

- analyzeResponse gains a truncation case: deliver the partial text and end
  the turn. A cap hit that produced no text at all has nothing to hand over
  and defers to the existing bounded empty-content retry. No continuation
  nudge is sent — it only grows the prompt with the discarded fragment, and
  assistant prefill, the reliable form, is unavailable on most
  OpenAI-compatible endpoints.
- A consecutive-length breaker stops the loop when truncation keeps landing
  inside tool-call arguments, the one shape that still legitimately loops.
- The stuck-loop detector now counts an identical lack of content. A model
  burning its whole budget on reasoning returns empty every round, which used
  to land in the else branch and reset the counter, so the guard could never
  fire on the case that needed it most.

The answer event and its Done marker carry a truncated flag through the SSE
metadata, and the chat UI shows the same style of notice it already uses for
fallback answers.

Fixes #3446

* fix(agent): treat unterminated reasoning as no answer and keep the truncation marker

Review follow-up on three ways the truncation path could still mislead.

An inline <think> block that the cap cut off never gets its closing tag, so
the pair regex left it whole and the round looked like it had produced an
answer. The truncation case then skipped the empty-content retry it exists
for and emitted the chain of thought as the final answer. StripThinkBlocks
now drops a dangling <think> through end of input, which is what the
streaming splitter already does with the same text, so the two agree on what
counts as an answer.

The truncation marker only rode on the SSE metadata, and a finished
conversation is rebuilt from agent_steps rather than replayed from stream
events. A reloaded, shared or re-opened turn therefore lost the notice and
its half-written answer looked complete. AgentStep carries the flag now — it
is a jsonb column, so no migration — and the frontend marks the rebuilt
answer event and message from it.

The consecutive-length guard ran before the round was recorded, so a final
round of "let me look that up" plus a truncated tool call handed that
preamble over as the final answer, with its tool calls never refused and the
preamble never retracted from the answer area. The guard now records the
round and fails its tool calls the way every other truncated round does, and
a response carrying tool calls never donates its text as the answer.
2026-09-20 13:17:50 +08:00
lyingbug 9e0c28fbc9
feat(artifacts): let users delete generated files (#3447)
* feat(artifacts): let users delete generated files

技能生成的文件此前只能列出、预览和下载,没有任何删除入口,后端
handler/service/repository 三层都没有实现。DeleteSession 里那句注释
("a dedicated GC job or explicit hard-delete API is the right place to
reclaim storage") 留的就是这个位置。

Tombstone, not a row delete. message_artifacts 新增 deleted_at,删除只
打标记不删行。position 是下载接口寻址用的下标(msg.Artifacts[index]),
物理删掉中间一行会让它后面的文件整体前移,已有链接下到错的文件;而
ArtifactCollector 的去重集就是从这张表读的,行没了之后沙箱里 mtime 未变
的同名文件下一轮就会被重新采集回来,删了又出现。墓碑同时挡住这两条。
loadArtifactsByMessage 因此刻意保留墓碑,展示侧用 MessageArtifacts.Live
过滤;NewMessageArtifactRecords 带上 DeletedAt,任何一次消息重写都能把
墓碑原样写回去。

Bytes. 字节是真回收的,走 catalog.Release 引用计数:一份文件可能同时被
知识库条目和后续回答持有,只有所有持有者都放手才 DeleteFile。删多个版本
时同一个对象可能来自多条消息,每条消息的绑定都要释放,字节只删一次。
回收发生在打标记之后,且只针对本次调用真正认领到的行——并发的第二次删除
认领不到任何行,也就不会去动别人正在回收的对象。释放失败一律保留字节:
留个孤儿 blob 以后还能靠墓碑上的 url 回收,删错了则是别人的文档里的图片
凭空消失。

Scope. 会话内面板每个版本单独一行,删的就是点的那一版;产物库一行代表
一个文件(带版本数),默认连同该文件在这个会话里的所有版本一起删,否则
删完这一行还在、只是显示上一版。权限比下载严一档:下载认共享智能体的
只读访问,删除只认会话归属人。

Inline references. 正文里的 resource:// 引用渲染成置灰加删除线的卡片,
不可点击,和「模型引用了不存在的文件」的 --pending 态区分开。图片类产物
也降级成卡片:走 renderImage 只会拉取失败,留下一张永远加载不出来的图。
墓碑必须留在传给渲染器的产物列表里——句柄形式与知识库图片同形,过滤掉
之后句柄对不上本条回答,会被当成外部受保护图片去拉一个已经不存在的
blob,结果是裂图。组件里因此拆出 liveArtifacts 只给计数和文件列表用。

Also: 产物库是 offset 分页的无限列表,删一行会让后续页整体前移漏掉一条,
改成按已显示行数取下一页并按 key 去重;access.ResolveMessageArtifact 与
MessageReferencesFile 不再让墓碑授权访问;SessionArtifacts 过滤墓碑,
避免新回答把引用绑到已删文件上;版本澄清文案不再把已删版本算进版本数。

docs/swagger.* 未重新生成:仓库里那份已经落后若干功能,重生成会带进约
1000 行无关漂移,另开 PR 同步。

* fix(artifacts): close the delete holes found in review

Regeneration. loadKnownSet 把墓碑的 ContentHash 也放进了去重集,于是
knownSameContent 会把「删除后技能重新生成、字节恰好相同」当成 fork
checkout 那种 restore:不上传、不挂回本轮回答,文件再也回不来。墓碑现在
只登记 (path, mtime),不进 hash 也不进 byPath —— 前者才是「沙箱文件没动
过就别复活」需要的键,后者是「同内容恢复」的短路,两件事不该共用。
RecordRestoredArtifactMtime 也不再改墓碑:它的 mtime 就是那把锁。

Message file proxy. /sessions/:id/messages/:message_id/files 走
MessageReferencesFile,而正文检查在最前面且无条件为真。删除不会重写回答,
resource:// 句柄还留在正文里,于是这条代理会继续把已删文件交出去——包括
交给共享智能体的只读访客,也包括「字节因为知识库还持有而没被回收」的情形。
现在先看 artifacts:命中本条消息的墓碑直接 false,命中 live 直接 true,
其余(知识库图、附件)才回落到正文。同一文件挂在多个位置时只要还有一个
live 就仍然可取。

Cross-session bytes. CreateForked 复制产物行时连同存储 URL 一起复制,但
不会给副本重新 Bind,所以 catalog 的引用计数看不到分叉。在父会话里删除会
把分叉还在用的字节删掉。无 catalog 部署、以及存的是裸 provider 路径的行,
同样不在计数覆盖内。回收前新增一道 CountLiveArtifactsByURL:只要还有任何
未删除的行指向同一对象就保留字节,查不出来也保留。配套加了 url 的部分索引。

Atomicity. SoftDeleteSessionArtifacts 原来逐条 UPDATE 不带事务,删多版本
时中途失败会留下「一部分已隐藏、字节没回收、接口 500、用户重试 404」。
现在整批放进一个事务。writeMessageArtifacts 是整表替换,拿着删除前快照的
并发写会让墓碑复活而字节已在回收,现在按 position 把已存在的 deleted_at
合并回去——删除是唯一不允许被过期写覆盖的属性。

all_versions 两个路由改用同一个解析器(strconv.ParseBool),此前一个是
== "true"、另一个是 != "false",显式传 1/TRUE 在两边语义不同;缺省值仍
按路由区分。

测试:收集器三条(未动不复活 / 重新生成要回来 / live 的同内容恢复仍短路)、
access 三条(正文不能复活已删授权、多副本只要有 live 就可取、非产物引用
仍走正文)、service 七条(归属人校验、他人会话拒绝、并发认领为空、live
行仍在则保留字节、guard 失败保留字节、多版本按对象归并 owner、无
source_path 不扫全会话)、repository 三条(墓碑抗过期写、事务回滚、跨会话
URL 计数)、handler 一条(两个路由的 all_versions 解析矩阵)。其中
「重新生成要回来」在改回旧实现时确认会失败。

client/ 没有 artifacts 相关 API(只有一个 SSE 事件类型常量),无需同步。
2026-09-20 13:01:46 +08:00
po-et 1b36030502 perf(chat): replay a stored stream a segment at a time
continue-stream replays every stored event as its own SSE frame, and
events are stored at the granularity the model emits them: one chunk per
AppendEvent, no accumulation. A long answer with a dozen length-limited
continuations is tens of thousands of chunks, and every reconnect during
it (a refresh, a re-entered page) replays them all, one write, one flush
and one client-side pass each; the report on #3362 counts 47,196 events
for a single replay, with the page frozen while they arrive.

Coalesce them on the way out. Each run of consecutive, unfinished
thinking or answer chunks of one segment (same type and event ID) is
replayed as one event carrying the run's concatenated content, its last
timestamp and the union of its data. A done chunk, a chunk of another
type or of another segment ends the run and passes through untouched:
the client marks a segment finished on its done chunk without appending
that chunk's content, and it accumulates content by event_id, so what it
assembles is the same text in the same order, in a few frames per
segment instead of one per token. The live path, the stored events and
the completion marker are unchanged.
2026-09-19 21:43:57 +08:00
lyingbug b82fd6c0f9
fix(security): close the low-severity shared-space findings (#3416)
* fix(security): close the low-severity shared-space findings

Verified and fixed from the shared-space permission review:

- Embed channels kept knowledge_ids, tag_ids, mentioned_items, skill_names
  and summary_model_id from anonymous visitors. Mentions are only scoped
  for shared agents, so a visitor could query any KB (and pick any model)
  of the channel workspace by ID. The payload now drops them; the widget
  never sends them.
- PUT /knowledgebase/:kb_id/wiki/issues/:issue_id/status updated any issue
  by ID. The update is now scoped to the path's KB (404 otherwise).
- A direct org invite let the inviter attach any user of the target
  workspace (or any user by ID) as its representative, whose username and
  email the roster then showed to all members. Direct adds attach no
  representative, and the roster returns emails only for the caller's own
  workspace.
- COS and KS3 dropped the bucket (and COS the region) segment when turning
  a path into an object key, while the tenant check scans every segment:
  cos://42/<region>/prefix/7/... passed as tenant 42 and read tenant 7's
  object from a shared bucket. Both must now match the service's config.
- Shared agent listings returned the full agent to receivers. Prompts and
  the creator's user ID are withheld; capabilities and scope stay visible.
- Temporary document uploads let the caller pick the parser engine (and
  its credentials) of a shared agent's workspace; only the agent's rules
  choose one there now.
- Suggested questions used request / message-snapshot knowledge_ids
  without a permission check. Each document is now resolved to its KB and
  checked like KB IDs, including a shared agent's scope.
- IM channels accepted any knowledge_base_id (and any agent ID on create).
  Both must belong to the channel's workspace, the KB also to a restricted
  API key's allow-list.
- KB-restricted API keys could list org-shared KBs outside their allow-list
  in the organization views; those listings are now filtered.
- With enable_rbac=false, RequireKBAccess let cross-workspace denials
  through. That switch is for roles inside a workspace; the guard now
  always denies another workspace's KB, since handlers behind it load by
  ID without a tenant filter.
- The org member limit was counted before and enforced apart from the
  insert; it is now checked in the insert's transaction with the
  organization row locked (SQLite serializes writers instead).
- The UpdateOrganization route comment and API doc said owner-only; the
  service and UI allow org admins. Comment and doc corrected.

Documented, not changed: issued /r/ and presigned links stay valid until
they expire after a share is revoked.

* fix(security): address review of the low-severity shared-space fixes

- Embed payloads also drop question_origin. It selects a KB like an
  @mention for agents that retrieve only when mentioned, and the widget
  never sends it; the selection stays inside the agent's scope, but an
  anonymous visitor should not pick among its KBs. suggestion_attribution is
  kept (the widget sends it and it is validated).
- The receiver view of a shared agent also withholds the follow-up
  suggestion instruction, a prompt like the others. Starter questions are
  shown to receivers anyway, and the sharer's name is displayed by design.
- Follow-up suggestion generation moves into the agent's workspace with
  types.WithExecutionTenant instead of a bare tenant rewrite, so the
  caller is pinned before the document permission check runs. The auth
  middleware and the shared run already pinned it; this removes the
  dependency on that.
- KS3 CopyFile copies only from the service's own bucket (as COS and S3
  do); another bucket's path is a cross-backend copy.

Tests cover the dropped question_origin, the follow-up instruction and the
/shared-agents listing, a follow-up context with the tenant switched, a
repeated wiki issue status update, and the KS3 copy source.
2026-09-18 22:58:46 +08:00
lyingbug db8e7611be
fix(security): close cross-workspace access paths in shared spaces (#3408)
* fix(security): close cross-workspace access paths in shared spaces

A review of how shared-space (organization) members reach each other's
resources found six paths that bypass the org-share permission model:

- presigned-preview signed any resource handle or storage path, turning a
  known resource:// handle into an anonymous /r/ URL that outlives share
  revocation. It now requires the path to belong to the caller's tenant,
  like /files.
- POST /initialization/initialize let a shared-KB editor rewrite the owner
  workspace's models (base URL, API key) in place. Only the KB's own
  workspace may call it, and rewriting a stored model needs the same
  authority as PUT /models/:id.
- KB JSON carried the legacy inline credentials (storage_config
  secret_id/secret_key, which initialization fills with the MinIO env
  keys, and vlm_config api_key) to every share receiver. They are withheld
  from JSON; their DB columns are unchanged.
- A chat without agent_source_tenant_id resolved shares before the
  caller's own agent, so a member sharing a same-ID built-in agent took
  over other workspaces' default agent. Own agents now win, built-in
  agents can no longer be shared (existing such shares no longer resolve),
  and embed channels drop a visitor-supplied source workspace.
- Any org-admin tenant (even a tenant Viewer inside it) could raise another
  workspace's KB share to editor/admin, and the route guard was bypassable
  via an unrelated :id. Share management is now: the sharer from the source
  tenant (Contributor+), source-tenant Admin+, or an org-admin tenant's
  Admin+ that may only remove or lower. share_id must belong to :id.
- Wiki write tools were registered for every wiki KB in the search targets,
  which only need read access, so a viewer share (e.g. via the built-in
  wiki fixer) could edit or delete another workspace's wiki pages. They now
  act only on KBs the caller may edit.

* fix(security): close the KB settings path and owner details for share receivers

Follow-up to the shared-space review:

- PUT /initialization/config shares the route guard that admits share
  editors, so an editor could still rebind the owner's KB models, chunking
  and storage, and storage backends resolved against the caller's workspace
  let it bind the owner's KB to its own backend. Another workspace now needs
  an admin share (the only share level the frontend offers settings to) and
  may not change the storage binding at all.
- GET /initialization/config showed model base URLs and bucket locations to
  any admin of the caller's own workspace, including share receivers. They
  now only see whether credentials are configured.
- Wiki write tools on the caller's own KBs had no role floor, so a tenant
  Viewer (and the IM, embed and MCP endpoint principals that run as Viewer)
  could write through an agent what the HTTP routes deny. Writes now need
  Contributor+, or the ingest capability for a scoped API key, following
  the RBAC rollout switch.
- resolveAgent logs the share lookup error instead of a nil own-agent error
  when a shared selector fails.

* fix(security): close the medium shared-space access findings

Follow-up to the high-risk fixes, from the same review:

- Wiki fixer moved into a shared KB's workspace ran with the caller's own
  config there: an unset MCP mode registered all of the owner's MCP
  services, and an "all" KB scope reached the owner's other KBs. The scoped
  run now uses the built-in config pinned to that one KB, without MCP,
  skills, sandbox or web search, and falls back to the KB's own model.
- An unset MCP mode means "all" at runtime but is shown as none in the share
  scope; shared runs now treat it as none.
- Quick-answer mode used the request's web_search_enabled alone, so a
  receiver could turn on search the agent disables and spend the owner's
  provider quota. It now requires the agent setting too, as agent mode does.
- summary_model_id picked any model of the workspace a run executes in. It
  is ignored for shared agents and the relocated wiki fixer.
- A workspace that left or was removed from an organization kept sharing its
  KBs and agents. Its shares are revoked on departure, and share queries and
  permission checks require the source workspace's membership and a live
  organization, which also covers rows left behind earlier.
- Sharing an agent exposes its KB scope to all members, so a Contributor
  could share colleagues' KBs (or "all") through an agent. The sharer must
  now be able to share each KB directly (creator or Admin+; "all" needs
  Admin+), also when a shared agent's scope is widened later.
- A scoped API key with manage_channels could mint an MCP endpoint token
  wider than itself. Endpoints it creates, updates or rotates must stay
  within its KB allow-list and capabilities.
- A shared agent's run indexed the receiver's Q&A into the owner's chat
  history KB; indexing now uses the session owner's configuration.
- Sharing an agent with skills keeps injecting the owner's skill
  environment values (product decision); the share panel now warns that
  members can read them. Preview of originals through read-only shares is
  kept as designed and documented.
2026-09-18 22:00:02 +08:00
lyingbug 2be7bd4063
fix(agent): search bound knowledge bases before answering, and pass suggested-question origins (#3400)
* fix(agent): search bound knowledge bases before answering, and pass suggested-question origins

A user picked the suggested question "为什么在比较图形时需要谨慎处理?"
and the agent answered in round 1 with no tool call, claiming it had
searched the knowledge base and found nothing, then explained misleading
statistical charts. The question had been generated from "Corners Don't
Look Like That: Regarding Screenspace Ambient Occlusion" in a bound base,
where "comparing graphs" means SSAO falloff curves.

Two things let that happen: the grounding prompt said "Stable general
explanations need no lookup", and nothing told the agent where the
question came from - the base in question had no profile, only two
recent titles in the directory, and the click sent the text alone.

Prompt
- With knowledge tools available, search bound bases before answering a
  question about a topic, even one that reads like general knowledge;
  directory profiles and recent titles cannot prove a base lacks it.
- The general-explanation exemption applies only without bound bases.
- Say you searched or found nothing only when a search tool ran.

Question origin
- Suggested questions from FAQ/document chunks also return knowledge_id.
- Picking one on the home or chat page sends question_origin
  {knowledge_base_id, knowledge_id} with that question only.
- The service keeps the origin only when its base is inside the turn's
  resolved scope and the document belongs to that base; it never
  changes the scope (unlike knowledge_base_ids, which narrows it).
- The engine renders it in runtime_context as <question_origin> with the
  base and document handles and a note to search it before answering.

* fix(agent): keep question origins across file/tag scopes and bind them to the send

Review follow-up for the suggested-question origin.

- Scope check: the origin was kept only when its base was in the resolved
  KB list, which is empty for file-only and tag-only scopes even though
  their bases are searched. It is now checked against SearchTargets after
  they are built; the document is kept only when a target for that base
  covers it (unfiltered base, or a document scope listing it).
  resolveQuestionOriginInfo re-checks SearchTargets, looks up the name of
  a base that is not in kbInfos, and the renderer omits an unknown name.
- Frontend: the origin travelled through module-level "pending" state, so
  a send that returned early (agent not ready, upload in progress,
  steering) left it behind and a second pick overwrote it. It now rides
  with the one send: triggerSend(text, options) -> createSession ->
  send-msg -> sendMsg / changeFirstQuery.
- RetrieveKBOnlyWhenMentioned: suggestions are still generated from the
  agent's bases, but picking one retrieved nothing. The origin now
  selects its base, as an @mention would, when the agent may read it.
- API sync: question_origin in docs/api/chat.md and swagger;
  QuestionOrigin on the Go SDK's KnowledgeQARequest/AgentQARequest and
  knowledge_id on SuggestedQuestion.
2026-09-18 17:00:47 +08:00
lyingbug 6db8fdd601
feat(artifacts): artifacts library page backed by a message_artifacts table (#3384)
* feat(artifacts): add an artifacts library with its own message_artifacts table

Skill-generated files were only reachable from inside the conversation that
produced them. This adds a sidebar entry and a page that lists them across
every conversation the user can see.

Storage: artifacts move out of the messages.artifacts JSONB column into a new
message_artifacts table (PostgreSQL 000103, SQLite 000023), backfilled on
upgrade. The table is now the only source of truth; the old column is kept and
the down migration writes the table back into it. The message repository
loads artifacts for every message it returns and writes them on create,
update (when non-nil) and fork, so callers still use Message.Artifacts.
mod_time is stored as RFC 3339 text because the collector matches files on
nanosecond mtimes, which PostgreSQL timestamps would truncate.

API: GET /api/v1/artifacts lists the latest version of each file (grouped by
session + source path, with version_count), scoped like the session list,
with keyword / file type filters and paging. Downloads keep using the
per-session endpoint.

Frontend: "产物/Artifacts" sidebar entry (hidden without sandbox support), a
library page with type tabs, search, date groups, infinite loading, preview
drawer, download and jump-to-conversation; strings in all five locales. The
sidebar's top-menu paths are now one shared list.

* fix(artifacts): keep the restore hash guard and count versions by URL

RecordRestoredArtifactMtime again only stamps rows whose content hash matches
the restored content (and ignores empty hashes), and never rewrites the hash,
matching MessageArtifacts.WithRestoredMtime. Without the guard a restore of
v1's content also moved v2's mtime and relabelled v2 with v1's hash.

The library's version_count now counts distinct URLs per (session, source
path). A later answer that references an earlier file stores another row with
the same URL, which COUNT(*) reported as an extra version.

* fix(artifacts): scope the library to web chats and clear the legacy column

The library used the session list's default scope, which counts sessions
without an owner as legacy tenant-level rows. IM sessions are created without
an owner, so every member saw the file names and titles of every IM chat
(downloads then 404 for non-admins). The library now applies the same "web"
bucket predicate as the home sidebar, extracted from QueryPaged so the two
cannot drift: no IM mapping (including cleared ones), no embed marker, no
API-key owner.

Migrations 000103 / SQLite 000023 now clear messages.artifacts after the
backfill. Message loads still SELECT *, so the stale copy was read on every
history load. Only rows that carried artifacts are rewritten; the column stays
for instances on the old binary during a rolling upgrade, and the down
migration still rebuilds it from the table.

* fix(migrations): keep the 000103 backfill alive on malformed artifact JSON

A single file_size that is not an integer ("12.5", "") or a created_at that
does not parse ("garbage", month 13) raised a cast error and failed the whole
migration, blocking startup. Casts now go through pg_temp helpers that return
NULL on bad input, falling back to 0 and the message's created_at; valid rows
are unchanged. SQLite casts never raise; its migration test now covers the
same malformed values.

* docs(artifacts): describe the web-only library scope and the cleared legacy column
2026-09-18 12:10:19 +08:00
养乐多 e3ac49cace fix(agent): report failed tool executions as tool_result, not error
response_type=error was being emitted when a tool execution failed,
but that type is reserved for internal agent failures (LLM/pipeline
errors), which clients treat as a crashed run. A failed tool call is
still a tool result: both the chat SSE handler and the skill install
transcript now emit response_type=tool_result with success=false and
the error string in metadata, so clients render it as a failed tool
card and let the agent recover instead of treating the run as dead.

Frontend needs no change: useChatStreamHandler already resolves tool
outcome from the success metadata field, history replay rebuilds from
agent_steps, and the API playground stops failing a whole request on
a recoverable tool error.
2026-09-18 11:11:21 +08:00
wizardchen 38be45c9d1 refactor: remove unused private Go helpers 2026-09-17 15:51:51 +08:00
nullptr-error 42e6163981
feat(session): fork conversations from a historical user message (#3304)
* feat(session): add fork schema and history queries

为会话分叉增加数据模型与迁移,并提供截至分叉点的消息查询以及会话内的 request_id 配对。

* feat(sandbox): add git, fork snapshots, and bootstrap hook

沙箱镜像安装 git,Docker 快照使用独立的 fork 命名空间,并在首次创建会话沙箱时接入可选 bootstrap。

* feat(session): checkpoint workspace at the end of each turn

每轮结束后对沙箱 /workspace 打 git checkpoint,并避免 fork 后因 mtime 刷新重复挂上产物、以及附件仍绑在父会话而无法还原。

* feat(session): fork conversations and reap orphan snapshots

支持从历史 user 消息分叉会话、首次打开时从快照 bootstrap,并在失败或删除未打开的分叉时回收孤儿快照。

* feat(chat): add session fork entry, prefill, and badges

在用户消息上提供分叉入口,进入新会话时预填原问题,并展示降级提示与来源角标。

* style: add missing newline so session_fork_delete_test.go is gofmt-clean

* fix(session): prune later git history when rolling a fork workspace back

reset --hard 只还原工作区,分叉点之后的 commit 仍可被 checkout。校验 SHA 后丢掉其他 ref 并 gc,避免错误基线。

* style(session): clear golangci-lint findings on the session-fork diff

Pre-push lints the whole PR against main; wrap long lines, check c.Error,
and fix gofumpt/revive/staticcheck so the merge can be pushed.

* fix(chat): show the fork button on hover without shifting the thread

Overlay the action so revealing it no longer expands the user bubble and janks the messages below.

* fix(chat): drop the fork landing banners

Keep the original question prefilled; do not explain sandbox snapshot vs checkpoint on the new thread.

* fix(agent): dedupe artifacts by content hash, not size

Same-path same-size rewrites were skipped as restores. Keep path+mtime as the cheap skip, hash bytes when mtime moves, and stamp the restored mtime onto this session only.

* feat(session): allow forking from an assistant answer

User forks still copy history before the question and prefill it. Assistant forks copy through that reply and reuse its checkpoint, with a degrade tooltip when none exists.

* fix(session): resolve parent attachments from a forked chat

Fork copies attachment IDs onto the new messages but leaves temporary_documents on the parent. Preview and Get now look up those IDs on the fork's copied history instead of a scoped miss.

* fix(agent): rewrite sandbox refs after a content-hash skip

Fork restores change mtime on unchanged files, so Collect returns empty
and named citations were left as sandbox: paths. Resolve those names
against session artifacts, notify only real uploads, and stamp restored
mtime only on the matching content hash.

* fix(session): drop a dead fork snapshot and retry checkpoint rewrite

Create from a missing template now abandons bootstrap so the next
Resolve uses a normal sandbox. A failed checkpoint rewrite no longer
marks the bootstrap consumed, which previously made nested forks
SANDBOX_REPLACED.

* fix(session): load forked parent attachments into the prompt

ResolveForPrompt used session-scoped lookup, so copied parent attachment
IDs passed Get but never reached the model. Use the same resolveInSession
path as preview.

* fix(chat): keep the user-message fork button visible

The control was hover-only, which hid it on touch. Always show it, and
drop the unused degrade tooltip.

---------

Co-authored-by: hailongzhao <hailongzhao@tencent.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-17 14:20:18 +08:00
VictorMaznyuk b94612a7ec
fix(agent): PUT no longer erases the avatar, and driver errors stay server-side (#3230)
* fix(agent): PUT no longer erases the avatar, and driver errors stay server-side

Two defects in the custom-agent API, both of which surface as a successful or
misleading response.

1. A config-only PUT wiped the avatar.

   UpdateAgentRequest.Avatar was a plain string, so "field omitted" and
   "explicit clear" were indistinguishable, and UpdateAgent assigned it
   unconditionally. Any caller that updated only the config — which is what
   an edit form or an SDK client does when it sends the config it changed —
   silently zeroed the avatar and still received 200.

   Avatar now travels as *string end to end: nil keeps the stored value, a
   pointer to "" is an explicit clear. The service takes it as a separate
   argument because *types.CustomAgent cannot express the difference.

2. Raw repository/driver errors reached the client.

   The fallback branches forwarded err.Error() verbatim, so a postgres
   message — for example "ERROR: value too long for type character
   varying(64) (SQLSTATE 22001)" — was returned in the API response. That
   leaks schema details and tells the caller nothing actionable. Each
   fallback now returns a fixed message naming the operation; the full error
   is still logged immediately above, so nothing is lost for diagnosis.

   The same oversized-avatar case is now rejected earlier, by ValidateAvatar,
   as a 400 that names the varchar(64) limit instead of a 500 produced by the
   database.

Typed sentinels and *errors.AppError keep their existing behaviour — only the
untyped fallbacks changed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(agent): complete avatar preservation and regression coverage

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-14 20:50:15 +08:00
nullptr-error 6ccc5cedf1
feat(sandbox): add a graphical desktop to session sandboxes (#3245) 2026-09-14 20:37:37 +08:00
wizardchen a799f23b26 feat(sandbox): stream live shell and install command output
Publish a bounded stdout/stderr tail for pending shell_exec and skill installs without putting partial logs into the model context.
2026-09-12 10:16:39 +08:00
lyingbug 7e53c31671
feat(browser): connect local Chrome with task controls and display modes (#3180)
* feat(browser): integrate BrowserSkill local task tabs and account pairing

* feat(browser): refine task routing, lifecycle, and display modes

* fix(browser): reclaim temporary task tabs and groups

* test(database): cover browser authorization migration schema
2026-09-11 17:59:27 +08:00
lyingbug 72581cb462 Revert "feat(sandbox): add safe live file management to session sandboxes (#3…"
This reverts commit 01205b3d56.
2026-09-11 17:42:08 +08:00
DEMO 01205b3d56
feat(sandbox): add safe live file management to session sandboxes (#3181)
* feat(sandbox): add safe live file management to session sandboxes

* fix(sandbox): keep live files from waking paused sandboxes

Serialize directory entries as "directory", refuse Files-tab Connect on paused runtimes, and cap list/delete trees so oversized workspaces fail closed.

---------

Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-11 17:31:53 +08:00
wizardchen 5cf093706e fix(chat): preserve steering continuity and composer focus 2026-09-09 20:15:23 +08:00