* feat(assistant): add persistent multi-agent collaboration and live task views
* fix(ci): wrap runtime notice message append
* fix(agent): preserve collaboration results and prevent duplicate execution
* fix(agent): fence panic followups and preserve approval timelines
* test(frontend): stub connector labels in assistant refresh fixture
* fix(migrations): avoid collaboration migration collision with main
* fix(assistant): preserve child continuations and artifact access
* fix(frontend): align artifact and icon checks with updated UI
* fix: enforce child approvals and finalize interrupted collaboration runs
* feat: support inherited temporary agent workers
* docs: clarify inherited worker scope and lifecycle
* fix: harden assistant retrieval and final delivery
* fix(agent): keep closed child prompts continuable and renew active deadlines
Expired child approvals were looked up by the child session, so the parent group stayed open and the run became needs_attention. Active collaborations also expired one hour after creation.
* fix(lint): clear golangci-lint findings on the collaboration PR
The previous CI run failed on line length, gofumpt, unchecked closes, and an unused dial parameter.
* fix(ci): use the public npm registry for frontend dependencies
* fix(agent): address collaboration review findings
- keep ordinary fallbacks when a turn delegated no work
- throttle lease/deadline heartbeats and drop duplicated child answers
- force-close or compact aggregates that exceed the size limit
- clamp completion budget to the model output limit
- honor prompt_suspend for non-collaboration tools
- clean up collaborations and child sessions on session delete, prune old rows
- bound concurrent child executions globally
- retry prompt classification and tolerate transient heartbeat errors
- scope prompt history to listed messages, reject nil tenants
* feat(assistant): let the assistant 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
* feat(assistant): let the assistant manage agents
Expose custom agents to the operation catalog (list, get, create, copy,
update, delete) plus read-only model and MCP service lookups, so the
assistant can set up agents end to end.
- Add PATCH /api/v1/agents/:id. PUT replaces the whole config, so a
one-field change from the assistant would wipe the rest; PATCH only
overlays the fields it carries and reuses the PUT validation path.
- Add x-agent-detail so long fields such as the system prompt are only
projected for single-object reads, not lists.
- Add label_param so a create without a target is labelled by its name.
- The approval card lists agent setting changes and resolves model,
knowledge base and MCP IDs to names.
- Deny sharing, publishing channels, credentials and OAuth routes; model
and MCP endpoints, headers and secrets are never projected.
- Update the assistant prompt, starters, API docs and Go SDK.
* feat(assistant): list skills and configure agent skill scope
- Expose usable skill names for an agent sandbox without exposing skill
administration or connection settings to the model.
- Validate PATCH selections against the workspace sandbox usable set so
invented names and missing sandbox selections cannot be saved.
- Show skill changes in approvals and align the assistant prompt, API
documentation, and Go SDK with focused refusal and projection tests.
* feat(assistant): isolate conversation history
- Keep assistant conversations out of ordinary session lists, search, artifacts and delete-all cleanup.
- Add private, paginated assistant history with session switching, confirmed deletion and stale-session recovery.
- Backfill session kinds safely on Postgres and SQLite, preserve kinds on forks, and align API docs and SDK coverage.
* feat(assistant): refresh pages after successful data changes
- Carry decoded mutation targets through live tool-result events without
exposing refresh metadata to the model or persisted chat history.
- Coalesce page and selector refreshes, update document drawers, and warn
about changed agents while preserving open editor drafts.
- Cover mutation, approval, stream, lifecycle and cache behavior with Go
and Node tests using the existing frontend runner and component fixtures.
* feat(assistant): add agent page context and resource scope limits
- Attach verified agent context and persist personal scope across turns and approvals.
- Enforce resource boundaries before operation and Wiki approvals, including edited arguments.
- Add scope controls, translations, API and SDK support, and regression coverage.
* refactor(assistant): remove the scope limit
The scope picker confused users and duplicated what RBAC and the access
level already enforce. Keep the agent page context: the agent editor
still publishes agent_id and the backend still verifies it.
* feat(assistant): render operation and product-doc results
Show find/run operations and WeKnora docs as structured cards instead of raw JSON.
* feat(assistant): default new agents to smart-reasoning
Quick-answer cannot call MCP, and agent.update could not change the mode. New agents now start in smart-reasoning, and a patch can switch agent_mode.
* fix: resolve assistant management CI failures
* feat(agent): 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
* 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>
* 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>
* 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>
* 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>
* feat(sandbox): stream interactive PTYs from Cube and E2B
Give session sandboxes a provider-neutral terminal capability so a later
WebSocket layer can attach without knowing Cube vs E2B. Long-lived
streams use a timeout-free client; idle terminals keep the sandbox alive
by refreshing TTL, and a workspace can set how long to wait before
disconnect.
* feat(session): bridge browser terminals to the session sandbox
Mint a short-lived ticket over a normal authenticated POST so the browser
WebSocket never puts the access JWT in the query string. After upgrade,
recheck the bound token, membership, and session ownership so logout or
revocation tears the PTY down. Provisioning stays opt-in: a GET
handshake only creates a sandbox when the client sends provision=1.
* feat(chat): add a sandbox terminal panel beside the conversation
Open a side panel with an xterm attached to the session sandbox. Starting
the terminal is an explicit click so merely opening the panel does not
create or resume a microVM; reconnects stay lookup-only until the user
confirms create-and-start. Persist the remote shell PID in
sessionStorage so a refresh reattaches instead of spawning an orphan.
* feat(sandbox): let workspaces set terminal idle disconnect
Expose the idle-disconnect duration in the sandbox config editor so an
operator can close unused terminals and let the provider TTL pause the
sandbox, instead of leaving PTYs open for the built-in 15 minutes.
* feat(chat): show generated files in the sandbox side panel
Move the per-message artifact list into the first tab of the right-hand panel so generated files stay in view with the terminal. Keep the old drawer only for embedded chat.
* fix(sandbox-terminal): keep tickets out of logs and live PTYs across refresh
Gin was copying the handshake JWT into response_body logs, silent access-token
rotation dropped open terminals as AUTH_REVOKED, and first-use provisioning
missed shared agents. Local echo now skips password prompts.
---------
Co-authored-by: hailongzhao <hailongzhao@tencent.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
* refactor(resource-access): unify scoped authorization and transfer recovery
* fix(resource-access): close reparse and transfer review gaps
* fix: enforce explicit file bindings and recover move cleanup
* fix: align mutation admission and cleanup scope checks
* feat(sandbox): enhance skill management in sandbox configurations
Updated the skill management system to allow listing, installing, and removing skills within sandbox configurations. The ListSkills function now accepts a sandboxConfigID to filter skills based on the selected configuration. Introduced a new SandboxSkillsDrawer component for managing skills through the UI, along with necessary updates to the API and localization files to support these features.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: keep skill maintenance sessions out of the console session list
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat: store and expose the installer transcript locators
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat: record the skill installer agent's conversation
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat: stream and persist the installer transcript during a skill install
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat: expose install transcript locators on the skill type
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat: add the floating skill install transcript window
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat: open the install transcript from the sandbox skills drawer
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(sandbox): 重构技能安装体验,支持内联时间线、编辑第4步及保留镜像指针
- 替换右下角浮窗为内联安装时间线 (SkillInstallTimeline.vue)
- 新增 GET /api/v1/sandbox-configs/:id/skills/:skillId/transcript 接口,支持回放与追尾
- 移除 /sessions/continue-stream 依赖,避免 404 问题
- 事件日志以 install_prompt 开头,不再将工具调用 preamble 拼入最终答案
- 删除 SkillInstallTranscript.vue,技能条目下可展开/折叠时间线
- 编辑向导新增第 4 步「管理技能」
- Cube/E2B 环境:连接 → 模板 → 运行配置 → 技能(第4步)
- Docker/Local 环境:无第4步(无快照镜像)
- 首次创建必须按 1→2→3 顺序,第3步保存成功后自动进入第4步
- 已有配置支持步骤条数字跳转,可直接访问任意步骤
- 卡片菜单「管理技能」打开同一抽屉并定位至第4步
- SandboxSkillsDrawer.vue 重命名为 SandboxSkillsPanel.vue,去除独立抽屉壳
- 修复保存运行配置时冲掉 skill_image 的问题
- 顶部展示信息(基础模板/快照ID/版本/构建时间)读取 config.skill_image
- 编辑器保存 payload 不再包含 skill_image,合并时保留已有 SkillImage 和 VolumeMount
- MergeSandboxConfigForUpdate 增加对 SkillImage 和 VolumeMount 的保护
- 已冲掉的配置需重新安装技能才能恢复镜像指针
- 「查看安装过程」在安装开始时即显示
- 技能列表中出现「正在安装」状态即展示按钮
- 若记录尚未写入,展示等待提示并自动重试,避免误报「没有留下记录」
* 沙盒内技能目录从 UUID 改成 SKILL.md 的 name。
* fix(sandbox): heal stuck skill rows and block planted maintenance sessions
The reaper left a mid-upgrade install spinning forever when the old snapshot was still live, and restored removals to ready after the pointer had already moved. Client session create/update can no longer hide chats behind the skill_maintenance: prefix.
* style: gofumpt the skill reaper test stubs
* style: satisfy golangci on the tenant skill admin API
* feat(sandbox): rebuild skill images at turn boundaries, not mid-exec
Hold a session turn lease through AgentQA so an install cannot tear down
the live sandbox between tool calls; the next turn's first resolve picks
up the new image. Configs can instead keep existing sandboxes and boot
the new snapshot only for new sessions.
* fix(sandbox): judge stuck skill runs from the snapshot chain
InstalledSnapshotID only records the generation that installed a skill; later
installs of other skills advance the live pointer without rewriting older rows.
Comparing those IDs made the reaper fail healthy installs and delete live
skills whose removal had stalled.
---------
Co-authored-by: hailongzhao <hailongzhao@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
Persist extracted and explicit memories across sessions with topic
resolution, semantic recall, document affinity, consolidation, workspace
settings, and inbox/interests UI.
* cubesandbox support
* feat(agent): add sandbox shell execution, file management tools, and Artifacts collection/download system
- Add three sandbox agent tools: shell_exec / sandbox_ls / sandbox_read
- shell_exec: safely execute shell commands in session sandbox with timeout & output truncation
- sandbox_ls: enumerate files under sandbox artifact output directory with recursive listing & pagination
- sandbox_read: read sandbox file content with offset-based chunked reading
- Add Artifacts system:
- ArtifactCollector: real-time collection of sandbox tool output files, attached to messages
- /api/artifacts/{session_id}/{message_id}/{filename}: download endpoint for frontend
- ChatArtifactsDrawer.vue: frontend artifacts sidebar UI
- DB migration 000066_message_artifacts: add artifacts column to messages table
- Attachment sandbox staging: upload user attachments to session sandbox on QA request for skill tool access
- Update Agent Prompts: add shell/sandbox tool usage constraints and safety rules
- Extend Agent Observe: include agent steps in Langfuse observability tracing
- Refactor Sandbox SessionManager: support session-scoped file listing, reading, and status queries
- Frontend: render artifact events in AgentStreamDisplay, i18n updates for 4 locales
- Add comprehensive tests: shell_exec_test, sandbox_read_test, artifact_collector_test, etc.
* feat(agent):add remote sandbox client abstract & client errors
* feat(sandbox): implement Redis binding store with distributed lifecycle lock;
* feat(sandbox): add remote session lifecycle with ownership context
Implement remoteSessionLifecycle to coordinate persistent remote sandboxes
across multi-instance deployments. Supports Resolve (lazy provision,
recovery, race-safe create) and Destroy with compare-delete semantics.
Add ownership context isolation to decouple remote resource cleanup from
request cancellation.
* feat(sandbox): add CubeRemoteClient adapter for RemoteSandboxClient
Implement CubeRemoteClient as a provider-neutral RemoteSandboxClient
implementation. Error normalization, timeout mapping, and metadata
support are fully integrated. SDK details remain private to the
adapter.
* refactor(sandbox): decouple SessionBoundManager from Cube
Remove internal/sandbox/cube.go (CubeSandbox, sync.Map reaper). Add
RemoteSandbox as provider-neutral Sandbox interface implementation.
Rewrite SessionBoundManager to depend on RemoteSandboxClient +
SessionSandboxBindingStore + SessionExistenceChecker, with all
lifecycle ops delegated to remoteSessionLifecycle (Redis + distributed
lock). Application-layer interfaces migrated to RemoteDirEntry/StatEntry
with time.Time ModTime. Cleanup delegated to provider idle-timeout.
* refactor(agent): enhance session capability handling in sandbox manager
- Introduced sessionFileStore and sessionShellExecutor functions to centralize capability checks for session-scoped file and shell execution.
- Updated agent service to register tools based on the presence of session filesystem capabilities, improving compatibility with various sandbox backends.
- Refactored tests to validate behavior when session capabilities are absent, ensuring robust handling of different sandbox types.
- Removed Cube-specific checks, promoting a more provider-neutral approach to session management.
* refactor(sandbox): add E2B backend, modernize Cube adapter, and enable multi-instance Redis binding
- Add e2b_remote_client.go (~850 lines) — full RemoteSandboxClient implementation
covering lifecycle, execution, and filesystem ops (ListDir/Stat/MakeDir/Remove)
- Wire E2B into NewManagerFromType and container/bootstrap path (buildE2BManager)
- Dependency: matiasinsaurralde/go-e2b v0.1.0
- Cut ~1500 lines of legacy SDK wrapper (cube_client.go, cube_envd.go,
cube_defaults.go) and replace with direct *cubesandbox.Client usage
- Parse CubeProxy URL directly in adapter (parseProxyURL), removing the
old hand-rolled envd transport layer
- Pass lifecycle extra fields (onTimeout, autoResume) via SDK CreateOptions.Extra
- Target Cube deployment v0.5.1
- Add RemoteNetworkPolicy to RemoteCreateRequest with AllowInternetAccess,
AllowPublicTraffic, AllowOut/DenyOut — shared by Cube and E2B adapters
- Both adapters default to permissive (internet+public on) for backwards compat
- Add selectSessionBindingStore() — Redis-backed or in-memory, controlled by
WEKNORA_SANDBOX_REDIS_NAMESPACE / WEKNORA_REDIS_NAMESPACE
- Add repositorySessionExistenceChecker — checks session existence via DB
(gorm.ErrRecordNotFound → not exists, transient errors → preserve binding)
- newSandboxManager() now accepts redisClient + sessionRepo; deprecated
hardcoded NewMemorySessionSandboxBindingStore() in production path
- buildSessionCreateRequest default timeout action: Kill → Pause+AutoResume
(Cube and E2B). Sessions survive brief idle periods; providers still
handle TTL-based reaping.
- buildSessionCreateRequest() and effectiveHTTPTimeout() parameterized
by RemoteProvider (was hardcoded to Cube Config fields)
- NewSessionBoundManager validates provider and delegates defaults to
per-provider apply*Defaults helpers
- Legacy SDK wrapper: cube_client.go, cube_envd.go, cube_defaults.go,
cube_envd_test.go, cube_net_diag_test.go, cube_test.go (~2500 lines)
- Unused helpers: DefaultManager.validateExecution, IsRemoteTerminal,
IsRemoteUnsupported, IsRemoteTransient, ShouldPreserveRemoteBinding
- Dead Config fields: CubeEnvdPort, CubeIdleTTL, AllowedCmds
- Dead ExecuteResult method: GetOutput
- Unused test: session_artifacts_integration_test.go
- Preloaded skill: sandbox-test-python
- Extract shared httpErrorKind() from per-adapter normalize functions
- Add SupportsFilesystemEnumeration capability flag — gates SessionFileStore
advertisement (E2B returns true post-reconnect, Cube always true)
- Fix stale comments: Cube-only → remote backends, remove "tomorrow"/"future"
- Bump session sandbox TTL defaults: 604800s → 300s (.env.example)
- Update docs/agent-skills.md: full multi-instance deployment guide
Total: 29 files, +1188 / -3721
* feat(agent): bind collected skill artifacts to owning message in resource registry
When ArtifactCollector persists a skill-generated file it now registers a
resource:// binding (owner_type=message, owner_id=assistantMessageID,
relation=artifact) in addition to the messages.artifacts JSONB record. This
mirrors how knowledge uploads and chat attachments bind their resources, so
artifacts can be enumerated and garbage-collected through the resource
registry instead of only via the message JSONB column.
- ArtifactCollector: inject ResourceCatalog, add messageID to Collect/
maybePersist, and add best-effort bindArtifactResource (binding failures are
logged, never drop the artifact; only resource:// refs are bound).
- agent_stream_handler: pass assistantMessageID into Collect.
- Renumber message_artifacts migration 000066 -> 000077 to resolve the
version collision with existing migrations (upstream now uses 000075/000076).
- Tests: update collector signatures and add coverage for the binding path
and for graceful degradation when Bind fails.
Note: binding applies to newly generated artifacts only; existing rows are
not backfilled.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(sandbox): harden remote sandbox security and artifact collection
Disable Cube local fallback so skill scripts never run on the host when
the remote provider is unavailable. Require Redis for cube/e2b binding
unless WEKNORA_SANDBOX_ALLOW_MEMORY_BINDING=true for single-node dev.
Collect artifacts with WithoutCancel so user stop does not drop files,
reject shell_exec work_dir outside /workspace, and refuse session-scoped
Execute when a local fallback would be engaged.
* fix(ci): gofmt sandbox files and resolve artifact drawer type error
Apply gofmt to PR-touched Go files and narrow ChatArtifactsDrawer
props in AgentStreamDisplay so session-id is always a string.
* fix(sandbox): adapt to upstream main after rebase
Renumber the message_artifacts migration 000077 -> 000079: upstream now
uses 000077_remove_wiki_log and 000078_chunk_editing_and_custom_metadata.
Declare empty model-handle policies for shell_exec / list_sandbox_files /
read_sandbox_file. Upstream added a coverage test requiring every
UI-exposed tool to declare one; sandbox output is arbitrary skill-authored
content, so it gets the same treatment as execute_skill_script.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(sandbox): replace single tenant sandbox config column with a configs table to support multi-sandbox config per tenant.
* feat(sandbox): add sandbox config entity, cordon lease and session pin field
* feat(sandbox): add sandbox config repository with tenant scoping and cordon lease
* feat(sandbox): stamp sandbox config ID onto sandbox metadata
* feat(sandbox): scope sandbox listing, release and reaping to a single config
* feat(sandbox): resolve managers per config and refuse cordoned or missing configs
* feat(sandbox): implement session pinning and config identity change detection
- Add SessionSandboxPinner with read/pin/clear to bind session to config
- Refactor four entry points (execute/attachment/artifact/destroy) to use pinned config
- Add config_identity.go to detect identity changes by effective values (APIURL/APIKey/Domain/ProxyURL)
- Add SandboxIdentityChanged with key-masked comparison to prevent false 409 conflicts
- Fix artifact collection for default backend and destroy for legacy empty-pin sessions
* feat(sandbox): add multi-tenant sandbox config management and HTTP APIs
Service layer:
- Add sandbox config business service supporting CRUD and inventory listing
- For non-identity changes (e.g., template, TTL), save directly without locking or remote interactions
- For identity changes (e.g., API key, endpoint), reject save if there are still live sandboxes under this config on the remote side,
and return structured inventory details (sandbox count, affected sessions, related agents) for frontend prompting
- Before deleting a config, check remote live sandboxes; if occupied, reject and prompt user to end sessions or create a new config
- Identity comparison based on effective values to avoid normal saves being misidentified as credential rotation
HTTP interfaces and routing:
- Add REST endpoints for sandbox config (List/Create/Get/Update/Delete/Inventory)
- Mask sensitive credentials (API key, etc.) in all read responses
- Return 409 with structured inventory details on rejection scenarios
- sandbox-check probing supports specifying an existing config_id directly
- Remove old handler file, consolidate validation logic into service layer
- DI wiring and route registration for all six endpoints
* feat(sandbox): add sandbox_config_id field to allow agent referencing named sandbox config
- Add SandboxConfigID field to CustomAgentConfig with omitempty; empty value falls back to global defaults
- Validate config existence on create/update; return 400 if not found
- Inject sandboxConfigService into CustomAgentHandler
- Add unit tests covering field serialization and validation logic
* feat(sandbox, agent): Migrate sandbox config to multi-config CRUD, support named backend selection and workspace scripts policy
Migrate frontend API from legacy KV single-config to /sandbox-configs REST interface, supplement type definitions, detection methods and policy fields; refactor sandbox settings page to multi-config card grid, manage configs with cube/e2b tabs, add editor drawer for create/edit/delete, connection testing and occupancy hints, and add workspace scripts policy toggle; add sandbox config dropdown in Agent editor skill section, integrate config caching, and support selecting named config or falling back to deployment default.
* feat(sandbox): Unify sandbox disable semantics and add tenant-level policy master switch
- Backend: Unify interception in resolveTenantSandboxForConfig with priority: global disable > tenant disable > default fallback > named config; add deploymentSandboxDisabled() using env var to avoid mis‑impacting named E2B; update WorkspaceSandboxPolicy comment as master switch for entire workspace; add unit tests for various scenarios.
- Frontend: Sync i18n copy: button text changed to "Disable/Enable sandbox execution"; confirmation dialog clarifies impact scope; success/failure messages aligned.
- Semantic layering: WEKNORA_SANDBOX_MODE=disabled disables globally; tenant‑level "Disable sandbox execution" only disables for the current workspace.
* feat(sandbox): Add SSRF protection, Agent binding to named configs, and reference query capabilities
- Add outbound URL security guard to validate Cube/E2B API/Proxy addresses against SSRF (including cloud metadata), support allowing private endpoints via env var, link-local always blocked
- Add named backend type validation, only cube/e2b can be stored as workspace named config
- Add sandbox config ID field to Agent at runtime, resolve sandbox for attachments and execution based on Agent's selected named config instead of always global default
- Add query to list Agents referencing a sandbox config ID, useful for deletion/changes to show dependents
- Adapt artifact collector and other callers to fill missing resolve signature parameter
* fix(sandbox): fix session teardown and config-update, add HTTP pool sharing for Cube
Session teardown & deletion ordering
- Move sandbox destroy (and pin `Clear`) before soft‑delete operations (`DeleteSession`/`BatchDeleteSessions`/`DeleteAllSessions`) to prevent remote sandbox leaks and stale pins.
- Pass deployment‑wide `SessionBoundManager` as fallback into `resolveTenantSandboxForConfig` for sentinel pins (`"-"`) to support deployment‑default sessions.
## Config update edge cases
- When identity fields change but old credentials cannot build a client or list config sandboxes, log a warning and proceed with the update instead of returning `sandbox_inventory_unverifiable`; live sandboxes still return 409.
- UI: move `sandboxes_still_live` / `unverifiable` alerts to the top of the sandbox config drawer and auto‑scroll on save refusal and connectivity check results.
Artifact collection for Cube skills
- Pre‑create `/workspace/output` via envd with correct ownership/permissions for `DefaultSandboxExecUser` to ensure Cube skill artifacts are collected properly by `ArtifactCollector`.
HTTP pool sharing for named Cube configs
- Named sandbox configs rebuilt a client on every `Resolve`, causing fresh TCP connections to CubeAPI and the envd proxy on each request.
- Add `CubeTransportPool` and `cubeSplitTransport`:
- Control plane traffic reuses the same `SharedTransport` as E2B.
- Data plane traffic uses a guarded transport cached per proxy host:port, preserving the sandbox `Host` header.
- Wire the pool through the tenant resolver `buildClient`; keep SDK defaults for the deployment‑default manager and connectivity probes.
* feat(sandbox): sandbox execution DefaultUser change from root to user
* fix(multi-sandbox-config-per-tenant): align deployment config with tenant resolver and centralize defaults
- Merge form overrides onto DeploymentConfig() via WEKNORA_SANDBOX_* env vars
instead of DefaultConfig() hardcoded values, allowing empty fields to inherit
from .env rather than Go constants
- Centralize deployment baseline parsing in sandbox/defaults.go with
DeploymentConfig, CubeConfigFromEnv, E2BConfigFromEnv
- Delegate container startup to shared helpers to avoid drift
- Propagate tenant env_vars through ResolveEffectiveConfig into
buildSessionCreateRequest for both Cube and E2B session sandboxes
* fix(multi-sandbox-config-per-tenant): fix some bugs frontend.
* fix(sandbox): guard check-path dials, fix staging gate and shared-agent binding tenant
Three defects found while reviewing the remote sandbox work:
- The Cube connectivity probe and the deployment-default Cube/E2B managers
built clients without a guarded transport, so an admin-supplied api_url or
proxy_url could reach link-local addresses via DNS rebinding even though
save-time validation passed. All three now dial through the same outbound
guard the per-tenant resolver enforces.
- Attachment staging was gated on the process-wide manager, so a workspace
pointing an agent at a named Cube/E2B config while the deployment default
stayed docker/local would run its tools remotely against an empty
/workspace/input. The gate now resolves the manager the session actually
runs on.
- Session to sandbox bindings were keyed by the tenant in context, which a
shared agent deliberately swaps for the agent owner's so models, KBs and
named configs resolve in the sharing workspace. Session deletion only ever
knows the session's own tenant, so teardown looked up a key nobody wrote
and abandoned a paused MicroVM that keeps billing. The binding tenant is
now carried separately and survives CloneContext.
* chore(sandbox): renumber migrations above upstream and de-collide test stub
Upstream main took 000079 (knowledge_folder_path) and 000080
(knowledge_base_auto_tag_config) while this branch was open, so the three
sandbox migrations move to 000081-000083. golang-migrate requires unique,
ordered versions, and the RAISE NOTICE labels move with the file names.
Main also added a handler test declaring stubSessionService in the same
package; the artifact download test's configurable variant is renamed rather
than merged, since the two stubs answer GetSession differently.
---------
Co-authored-by: hailongzhao <hailongzhao@tencent.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
Restrict channel-managed sessions (API keys, IM, embed) to tenant admin
in the Web console for list/read paths, hide channel sidebar buckets from
non-admins, and add CountSessionsBySource for aggregate stats without
exposing session rows to viewers.
Let tenant admins list and open API-key sessions from the Web console while
keeping per-key isolation for everyone else. Pin the session source filter so
it no longer jumps when switching buckets, and resolve session origin on read
so deep links stay in sync with the active folder after refresh.
Let users upload documents in chat without ingesting them into a knowledge base: files are parsed in the background, referenced by ID on send, and expire after a configurable TTL.
Introduce tenant-scoped storage backend registry so workspaces can register
multiple storage instances and bind each knowledge base to a specific backend,
with migration from legacy tenant-level storage config and new settings UI.
Align product copy, API docs, Swagger descriptions, and i18n strings
with workspace terminology while keeping internal tenant identifiers
and headers unchanged for API compatibility.
Enable agents to configure starter prompts and async follow-up questions after completed answers, with durable caching, analytics events, and chat/embed UI integration.
Replace the standalone /platform/system/* routes with a single
"系统设置" section inside the canonical Settings modal. The previous
SystemLayout.vue / SystemAdmins.vue surfaces are removed and their
functionality (system admin roster, global settings) is hosted directly
in SystemSettings.vue under the standard `.section-header` /
`.settings-group` skeleton. Legacy URLs redirect to the modal section
so external bookmarks don't 404.
Backend:
- SystemSettingService.Reset + repo.Delete: drop the DB override for a
key so the 3-tier resolver falls back to ENV / built-in default.
Idempotent (resetting a never-persisted key returns nil); emits an
audit row only on real deletions, invalidates the local cache, and
publishes to peers via the existing pubsub channel.
- TenantService.BulkSetStorageQuota: overwrite every tenant's
storage_quota in one statement. Powers POST /system/admin/tenants/
apply-default-storage-quota; bypasses the per-tenant whitelist on
PUT /tenants/:id which intentionally forbids storage_quota edits.
- AuditAction{SystemAdminPromoted,SystemAdminRevoked} constants and
emitAdminAudit() in SystemHandler — promote / revoke now leave an
audit trail with TenantID=0 and {target_email,target_username,
idempotent|changed} in details.
- SystemSetting.LastModifiedByName: derived per-request display label
(username, email fallback) so the UI shows "wizardchen" instead of
a UUID prefix without storing a denormalised column.
Frontend:
- SystemSettings.vue rewritten against the Settings modal skeleton with
auto-persisting controls (switch/select @change, input/inputnumber
@blur, tag-input + per-delta popconfirm for SSRF whitelist and admin
roster). auth.registration_mode change goes through an inline
popconfirm; cancel rolls back. Reset / bulk-apply also inline
popconfirms — no dialog modal for these per-row affordances.
- Priority hint panel surfaces the DB > ENV > default resolver order
so operators can reason about "I set the env but it doesn't show up".
- Router: /platform/system, /platform/system/settings, /platform/system/
admins are now compatibility redirects to /platform/settings?section=
system-global.
- Settings modal sized 900x700 → 1080x780 and content-wrapper 600 → 760
so the wider tables (members, system settings) breathe; <1100px
viewport still flexes to the screen.
- i18n: system.globalSettings.* keys for title / description / loading /
empty / badges / priority hint / per-key labels / reset / bulkApply /
admins (label, placeholder, save messages, popconfirm copy) across
zh-CN, en-US, ko-KR, ru-RU.
Misc:
- internal/utils/filesize.go doc: clarify MAX_FILE_SIZE_MB is a
deploy-time-only knob (nginx + docreader + frontend each cache the
env at startup); a SystemAdmin UI override would mislead operators
because nginx would still 413. Until all four layers can hot-reload
the limit in lockstep, this stays env-only.
- internal/utils/security.go: SSRF whitelist parser/runtime now drives
off SystemSettingService for live updates; ENV remains the fallback
for never-overridden deployments.
- Added WEKNORA_BOOTSTRAP_SYSTEM_ADMIN_EMAIL environment variable to promote a specified user to system admin on startup.
- Introduced a new bootstrap process in `bootstrap.go` to handle the promotion logic.
- Updated `.env.example` to document the new environment variable and its behavior.
- Created new views for managing system administrators and system settings, including listing, promoting, and revoking admin privileges.
- Enhanced the frontend to reflect the new system admin features, including UI elements for admin management and settings configuration.
- Updated API interfaces to support system admin functionalities, ensuring proper data handling and user management.
Updated the memory management logic to utilize a server-side per-user preference for enabling memory. The `enable_memory` field is now conditionally set based on user preferences, allowing for better control in both normal and embedded contexts. Adjusted relevant API handlers and request structures to support this change, ensuring backward compatibility with existing clients.
Refs: #1303
PR #1309 plumbed user-scope into the session/message service layer so
non-owner / wrong-tenant lookups now surface as ErrSessionNotFound at
every entry point that goes through sessionRepo.Get. The handler-side
mapping, however, only existed in 4 of the 8 affected sites:
- handler/session/handler.go:GetSession ✓ already mapped (with `==`)
- handler/session/handler.go:UpdateSession ✓ already mapped (with `==`)
- handler/session/handler.go:DeleteSession ✓ already mapped (with `==`)
- handler/session/handler.go:BatchDeleteSessions ✓ already mapped (with `==`)
- handler/session/handler.go:ClearSessionMessages ✗ always 500
- handler/session/stream.go:ContinueStream session lookup ✓ (with `==`)
- handler/session/stream.go:ContinueStream message lookup ✗ always 500
- handler/message.go:LoadMessages (recent + before-time) ✗ always 500
- handler/message.go:DeleteMessage ✗ always 500
Result: a Contributor in tenant A asking for a Contributor B's session
messages got a 500 instead of 404 — the wire response leaked
"something is broken" rather than "you can't see this URL", which
breaks SDK / frontend axios interceptor error handling that keys on
HTTP status.
Two changes:
1. Add ErrSessionNotFound → 404 mapping to the 4 sites that lacked it
(ClearSessionMessages, ContinueStream's GetMessage, LoadMessages's
two paths, DeleteMessage).
2. Replace `err == errors.ErrSessionNotFound` with
`stderrors.Is(err, errors.ErrSessionNotFound)` everywhere. Sentinel
error comparison must use errors.Is so wrapped errors
(`fmt.Errorf("...: %w", ErrSessionNotFound)`) still match. Today no
service-layer caller wraps, but a future refactor that does would
silently turn 404s into 500s with no test catching it.
Tests:
- internal/handler/message_session_not_found_test.go covers the four
new mapping sites in handler/message.go (LoadMessages-recent,
LoadMessages-before-time, DeleteMessage) and pins the wrapped-error
behaviour with a dedicated regression test that fmt.Errorf("%w") a
sentinel must still be detected as ErrSessionNotFound. The bare
handler is hit through gin.Engine + middleware.ErrorHandler so the
response shape matches production exactly.
- PR #1309's existing service-level tests (session_user_scope_test,
session_test on the repository) still pass — this PR is a strictly
handler-layer follow-up.
The Agent ran a parallel context cache (Redis/in-memory) on top of the
messages table to feed multi-turn history into the LLM. That dual-write
caused subtle drift (e.g. compression diverging from DB, system-prompt
swaps lost on restart) and required a separate ClearContext path on
session/IM clear.
Make the messages table the single source of truth:
- Add service.LoadAgentHistory: rebuilds chat.Message history per turn
from the persisted messages, expanding AgentSteps into proper OpenAI
assistant_with_tool_calls + tool messages and replaying the canonical
final answer (with <think> blocks stripped). final_answer tool calls
are filtered to avoid duplicating the trailing answer.
- Make AgentEngine stateless across turns: drop ContextManager / sessionID
cache plumbing from the engine, agent service, and CreateAgentEngine
signature. The engine only uses sessionID for logging/event emission.
- Wire AgentQA to load history from DB on demand using HistoryTurns
(default 5) when MultiTurnEnabled, otherwise run with empty history.
- Delete the llmcontext package (ContextManager interface, Redis/memory
storage, factory) and the SessionService.ClearContext API path; IM
/clear and session message clear no longer need to invalidate cache.
Behavior preserved: KnowledgeQA-mode replay is unchanged (turns with
empty AgentSteps just produce the single canonical assistant message),
and Agent-mode turns now consistently see prior tool calls and results.
- Apply the session-list additions to the SQLite init migration (Lite build)
and make QueryPaged dialect-aware: LOWER(..) LIKE on SQLite, ILIKE on
Postgres, drop NULLS LAST on SQLite. Escape LIKE wildcards in the keyword
via the existing escapeLikeKeyword helper.
- SetPinned now returns rowsAffected so the handler can respond 404 on
unknown / unauthorized session IDs instead of a misleading 200.
- GET /sessions always returns the enriched shape (pin state + IM origin
fields) so the frontend never needs a second roundtrip; the dual-path
legacy branch in the handler is gone.
- Register pin routes with the wildcard name that matches each verb's
existing radix tree (POST :session_id, DELETE :id) and accept either
param name in the handler; avoids gin's "wildcard conflicts" panic.
- Drop the redundant [platform] prefix from IM session titles now that
the list renders a platform icon alongside the title; add unit tests
for shortID / buildUserSessionTitle / buildThreadSessionTitle.
- Frontend: remove the submenu search input and its i18n/keyword wiring
(search lives elsewhere in the app); pin icon uses the TDesign `pin`
glyph and inherits color so the active session turns green; optimistic
pin moves the item to the top of the list so it shows up at the top
of the Pinned group; IM text badge replaced by the platform SVG icons
from assets/img/im, desaturated by default and full-color on hover
or when the session is active.
Sessions today are a flat list ordered by updated_at. Two gaps showed up in
practice:
- Users cannot find specific chats as the list grows beyond a screen.
- IM-created sessions (WeCom/Feishu/Slack/...) are indistinguishable:
every title was "IM-<platform>" or "IM-<platform>-<username>" and the
list API hid the underlying im_channel_sessions mapping, so admins had
no way to tell which Feishu group a session came from.
Backend
- Migration 000039 adds sessions.user_id (owner), is_pinned, pinned_at
plus a composite index for the list query. Existing rows keep user_id
NULL and stay visible at the tenant level for backward compatibility.
- CreateSession now writes the caller's user_id from auth context.
- GET /sessions accepts keyword / source / agent_id. When any filter is
set, the response switches to enriched items that LEFT JOIN
im_channel_sessions and expose im_platform / im_chat_id / im_thread_id
/ im_user_id / im_agent_id / im_channel_id. No filters => legacy shape,
existing clients unaffected.
- Ordering: is_pinned DESC, pinned_at DESC NULLS LAST, updated_at DESC.
- POST/DELETE /sessions/:id/pin for user-scoped pin/unpin.
- IM session titles: "[platform] <user|chat|thread>" with short ID
suffixes so group/DM/thread sessions are visually distinct without
needing a round-trip to fetch a display name from the IM adapter.
Frontend
- Search input debounced at 300ms drives the keyword filter.
- Pinned chats render in a dedicated group above the time-based groups,
with a pin icon and a pin/unpin entry in the per-chat dropdown.
- IM chats get a short [platform] badge in the list.
- Pin toggle is optimistic and guards against double-clicks.
- zh/en/ko/ru i18n keys added for the new strings.
- Implemented a new API endpoint to clear all messages in a session, enhancing session management capabilities.
- Updated the frontend to include a clear messages option in the session menu, allowing users to easily remove chat history.
- Added localization support for the new feature in English, Korean, Russian, and Chinese, improving accessibility for a broader audience.
- Enhanced the chat view to handle session message clearing events, ensuring a responsive user experience.
These changes significantly improve the user experience by providing a straightforward method to manage session messages effectively.
- Updated configuration to support three tasks in the assistant's prompt: rewriting questions, classifying intent for knowledge base retrieval, and analyzing attached images.
- Implemented backend functionality to update image descriptions in user messages, ensuring that image context is preserved across conversation history.
- Modified session handling to return complete session data after updates, improving the accuracy of session information provided to users.
- Enhanced the chat pipeline to include detailed image descriptions and manage image captions effectively, enriching user interactions with visual content.
These improvements significantly enhance the application's multimodal capabilities, providing a more robust and user-friendly experience when handling image-based queries.
- Added functionality for image uploads in chat, allowing users to attach images for multimodal Q&A.
- Enhanced the input field to handle image selection via drag-and-drop and paste, with validation for file types and sizes.
- Updated the backend to process images alongside text queries, including support for image analysis.
- Introduced new UI components for image previews and management, improving user interaction with uploaded content.
- Added localization strings for image upload features and error messages, enhancing accessibility for users in multiple languages.
These changes significantly improve the chat experience by enabling users to incorporate images into their queries, facilitating richer interactions and responses.
- Introduced a new API function `deleteAllSessions` to allow deletion of all sessions for a tenant.
- Updated the `BatchManageDialog` component to support a confirmation dialog for deleting all sessions.
- Enhanced the menu component to reflect the new delete all functionality with appropriate confirmation messages.
- Added internationalization support for the new delete all confirmation message in multiple languages.
These changes improve session management by providing users with the ability to delete all sessions at once, enhancing the overall user experience.
- Updated the AgentSelector component to improve agent selection logic, ensuring accurate representation of selected agents.
- Introduced new AgentShareSettings component for managing agent sharing with organizations, including UI for selecting organizations and displaying shared agents.
- Enhanced API interactions for sharing agents, including new methods for listing and managing agent shares.
- Improved localization support for agent sharing features across multiple languages.
- Updated various components to reflect changes in agent capabilities and sharing status, enhancing user experience and clarity.
This update strengthens the agent management features, providing users with better tools for sharing and selecting agents within organizations.
- Added support for tracking the status of FAQ import tasks, including progress indicators for ongoing imports.
- Introduced new localization strings for processing tasks and batch operations in multiple languages.
- Updated the FAQ entry manager to display import progress and improved user feedback during the import process.
- Enhanced the KnowledgeBase component to reflect the processing state of knowledge items, improving user experience during document uploads.
- Implemented batch deletion functionality for chunks, streamlining the management of knowledge base content.
- Removed outdated DEVELOPMENT.md, consolidating development instructions into relevant documentation.
- Updated conversation configuration to include new parameters such as max rounds, embedding thresholds, and rewrite prompts.
- Enhanced UI components to support new conversation settings, including AgentSettings.vue and related views.
- Improved localization in English, Russian, and Chinese for new conversation configuration fields and UI elements.
- Implemented logic to apply tenant-specific conversation settings, ensuring defaults are respected.