WeKnora/internal/handler/session/qa.go

1955 lines
74 KiB
Go
Raw Normal View History

package session
import (
"context"
"crypto/sha256"
"encoding/json"
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
stderrors "errors"
"fmt"
"net/http"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
2026-04-10 04:49:20 +00:00
"sync"
"time"
"github.com/Tencent/WeKnora/internal/application/access"
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/logger"
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 13:01:00 +00:00
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/storageurl"
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
"github.com/Tencent/WeKnora/internal/stream"
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
"github.com/Tencent/WeKnora/internal/types"
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
"github.com/Tencent/WeKnora/internal/types/interfaces"
secutils "github.com/Tencent/WeKnora/internal/utils"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
feat(sandbox) (#2301) * 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>
2026-08-10 13:28:20 +00:00
const (
maxAttachmentUploadsPerRequest = 5
maxAttachmentUploadTotalBytes = int64(100 * 1024 * 1024)
)
// qaRequestContext holds all the common data needed for QA requests
type qaRequestContext struct {
ctx context.Context
c *gin.Context
sessionID string
requestID string
receivedAt time.Time // Wall-clock time the handler started processing the request
query string
session *types.Session
customAgent *types.CustomAgent
assistantMessage *types.Message
knowledgeBaseIDs []string
knowledgeIDs []string
tagScopes []types.TagScope
tagIDs []string
mcpServiceIDs []string
skillNames []string
summaryModelID string
localBrowserEnabled bool
webSearchEnabled bool
mentionedItems types.MentionedItems
effectiveTenantID uint64 // when using shared agent, tenant ID for model/KB/MCP resolution; 0 = use context tenant
sharedAgentReadOnly bool // access was granted by a read-only agent share
images []ImageAttachment // Uploaded images with analysis text
userMessageID string // Created user message ID (populated after createUserMessage)
userCreatedAt time.Time // Persisted user message timestamp, echoed on agent_query
channel string // Source channel: "web", "api", "im", etc.
attachments types.MessageAttachments // Processed base64 file attachments (legacy inline uploads)
attachmentIDs []string // Pre-uploaded session-scoped document IDs, resolved after SSE starts
attachmentMetas types.MessageAttachments // Metadata-only view of attachmentIDs for the persisted user message
suggestionAttribution *types.SuggestionAttribution
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 09:00:47 +00:00
questionOrigin *types.QuestionOrigin
// resourceRewriter turns internal storage references in the outbound stream
// into directly loadable URLs when the caller asks for `resource_urls=public`.
// Disabled (a pass-through) in the default handle mode.
resourceRewriter *storageurl.StreamRewriter
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
// steerSink bridges the engine's round-boundary drain to the steer
// sub-list and user-row persistence. Set by setupSSEStream for agent
// runs only.
steerSink *steerSink
// Snapshot of the request fields needed to persist the input-bar state
// for session restoration. Kept verbatim from the request so we record
// what the user had selected on the UI (not server-side resolutions).
reqAgentEnabled bool
reqAgentID string
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
// skipSSE is set for server-started follow-up runs (steer backlog after
// the previous turn exits). Events still land in StreamManager so the
// client can attach via continue-stream; nothing is written to gin.
skipSSE bool
// steerCarryOver is appended to this run's steer sub-list before the run
// is published as live, so leftover inject / after messages from the
// previous run are visible to this engine from round 1 and to any client
// that reloads the queue.
steerCarryOver []interfaces.StreamEvent
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 13:01:00 +00:00
// turnLeaseHeld records that executeQA already took the send-side turn
// lease for this request, so the QA service does not take a second one.
turnLeaseHeld bool
}
// buildQARequest converts the qaRequestContext into a types.QARequest for service invocation.
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
// steerSink rides along when the caller set one, so agent runs drain mid-run
// message injections at round boundaries.
func (rc *qaRequestContext) buildQARequest() *types.QARequest {
imageURLs, imageDescription := extractImageURLsAndOCRText(rc.images)
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
req := &types.QARequest{
Session: rc.session,
Query: rc.query,
AssistantMessageID: rc.assistantMessage.ID,
SummaryModelID: rc.summaryModelID,
CustomAgent: rc.customAgent,
SharedAgentReadOnly: rc.sharedAgentReadOnly,
KnowledgeBaseIDs: rc.knowledgeBaseIDs,
KnowledgeIDs: rc.knowledgeIDs,
TagScopes: rc.tagScopes,
MCPServiceIDs: rc.mcpServiceIDs,
SkillNames: rc.skillNames,
ImageURLs: imageURLs,
ImageDescription: imageDescription,
UserMessageID: rc.userMessageID,
WebSearchEnabled: rc.webSearchEnabled,
LocalBrowserEnabled: rc.localBrowserEnabled,
Attachments: rc.attachments,
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 09:00:47 +00:00
QuestionOrigin: rc.questionOrigin,
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 13:01:00 +00:00
TurnLeaseHeld: rc.turnLeaseHeld,
}
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
if rc.steerSink != nil {
req.SteerSink = rc.steerSink
}
return req
}
// parseQARequest parses and validates a QA request, returns the request context
func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestContext, *CreateKnowledgeQARequest, error) {
receivedAt := time.Now()
ctx := logger.CloneContext(c.Request.Context())
requestID := secutils.SanitizeForLog(c.GetString(types.RequestIDContextKey.String()))
logger.Infof(ctx, "[%s] TTFB:start request_id=%s received_at=%d",
logPrefix, requestID, receivedAt.UnixMilli())
// Get session ID from URL parameter
sessionID := secutils.SanitizeForLog(c.Param("session_id"))
if sessionID == "" {
logger.Error(ctx, "Session ID is empty")
return nil, nil, errors.NewBadRequestError(errors.ErrInvalidSessionID.Error())
}
// Parse request body
var request CreateKnowledgeQARequest
if err := c.ShouldBindJSON(&request); err != nil {
logger.Error(ctx, "Failed to parse request data", err)
return nil, nil, errors.NewBadRequestError(err.Error())
}
// Validate query content
if request.Query == "" {
logger.Error(ctx, "Query content is empty")
return nil, nil, errors.NewBadRequestError("Query content cannot be empty")
}
// Resolve the storage-reference representation up front: once the SSE stream
// has started an invalid value can no longer be reported as a 400.
resourceRewriter, err := h.resolveStreamRewriter(c)
if err != nil {
fix(api): close the resource_urls=public gaps found in review Follow-up on resource_urls=public. Review turned up one authorization gap plus a set of correctness problems in the streaming path. Authorization: - Embed channels were documented as excluded, but nothing enforced it. The delegating handlers hand the visitor's own gin context to the shared handlers, so ?resource_urls=public — and a deployment-wide RESOURCE_URL_MODE=public — reached anonymous traffic and produced shareable, credential-free URLs that bypass the channel-scoped /embed/:channel_id/files proxy. ensureEmbedSession now pins the request context to handle mode, which covers every delegated endpoint including future ones. The downgrade is silent so a client that forwards the parameter keeps working. - A knowledge-base-restricted API key is refused with 403. Such a key is already denied /files because a raw storage path cannot be bound to its allow-list, so handing it anonymous file URLs would reopen that hole from the other side. The default handle mode stays available to it. Streaming: - Rewriter.ref holds its lock across resolution. Resolver implementations keep an unsynchronised per-provider cache, so the previous unlocked window was a real data race for any caller sharing a StreamRewriter between goroutines — which its own doc comment invited. Serialising also collapses a concurrent duplicate into one signature. - Release the holdback buffer on every path that ends a stream while the client is still connected: a user-requested stop, an error event, and giving up on the event store. Only completion flushed before, so the tail generated just before a stop was silently dropped. - A released tail carries the metadata of the event it was cut from instead of a bare event_id. - The maxHeldBytes safety valve aligns to a UTF-8 boundary rather than cutting a character in half, and an unclosed "![…](" only holds back a whitespace-free destination under 2048 bytes, so prose that merely mentions Markdown image syntax no longer stalls the stream behind the buffer. Also resolves the mode before running a knowledge search instead of after, so an invalid value no longer costs a full retrieval, and warns once per distinct bad RESOURCE_URL_MODE value instead of once per process. Co-authored-by: lyingbug <lyingbug@users.noreply.github.com>
2026-08-04 15:46:54 +00:00
logger.Warnf(ctx, "Rejected resource URL mode: %v", err)
return nil, nil, err
}
if h.suggestionService != nil && request.SuggestionAttribution != nil {
if err := h.suggestionService.ValidateAttribution(ctx, sessionID, request.Query, request.SuggestionAttribution); err != nil {
return nil, nil, errors.NewBadRequestError("invalid suggestion attribution")
}
}
// SSRF protection: strip client-supplied URL/Caption fields from image attachments.
// The URL field must only be populated server-side by saveImageAttachments; an
// attacker could inject internal network URLs to trigger SSRF via the LLM provider.
for i := range request.Images {
request.Images[i].URL = ""
request.Images[i].Caption = ""
}
// Log request details
if requestJSON, err := json.Marshal(request); err == nil {
logger.Infof(ctx, "[%s] Request: session_id=%s, request=%s",
logPrefix, sessionID, secutils.SanitizeForLog(secutils.CompactImageDataURLForLog(string(requestJSON))))
}
// Get session. QA writes new messages into the session, so use the strict
// owner scope: a tenant admin may read an API-key session but must not be
// able to post messages to it (which would otherwise fail later at message
// creation with a 500 instead of a clean not-found).
session, err := h.sessionService.GetOwnedSession(ctx, sessionID)
if err != nil {
logger.Errorf(ctx, "Failed to get session, session ID: %s, error: %v", sessionID, err)
return nil, nil, errors.NewNotFoundError("Session not found")
}
// Get custom agent if agent_id is provided. Backend resolves shared agent from share relation (no client-provided tenant).
customAgent, effectiveTenantID, sharedAgentReadOnly := h.resolveAgent(ctx, c, request.AgentID, request.AgentSourceTenantID)
if request.AgentSourceTenantID != 0 && customAgent == nil {
return nil, nil, errors.NewNotFoundError("Shared agent not found")
}
// Merge @mentioned items into knowledge_base_ids and knowledge_ids
kbIDs, knowledgeIDs := mergeKnowledgeTargets(request.KnowledgeBaseIDs, request.KnowledgeIds, request.MentionedItems)
if err := types.AuthorizeTenantAPIKeyKnowledgeTargets(ctx, kbIDs, knowledgeIDs); err != nil {
2026-07-05 02:25:37 +00:00
return nil, nil, err
}
// The built-in wiki fixer is invoked from a KB page, not from a tenant's
// regular agent picker. When the KB is shared, run it in the source tenant
// only if the caller has edit permission, so KB-scoped models/tools resolve
// without granting viewers write capability.
if customAgent != nil && customAgent.ID == types.BuiltinWikiFixerID {
if scopedAgent, scopedTenantID := h.resolveWikiFixerTenantScope(
ctx,
customAgent,
c.GetUint64(types.TenantIDContextKey.String()),
types.TenantRoleFromContext(ctx),
kbIDs,
); scopedTenantID != 0 {
customAgent = scopedAgent
effectiveTenantID = scopedTenantID
sharedAgentReadOnly = false
}
}
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 14:00:02 +00:00
// A per-request model override resolves in the workspace the run executes
// in. For a shared agent, or the wiki fixer moved into a shared KB's
// workspace, that is the owner's, where it could select any of the owner's
// models; it would also be stored as the message's model for follow-ups.
if effectiveTenantID != 0 && effectiveTenantID != c.GetUint64(types.TenantIDContextKey.String()) {
request.SummaryModelID = ""
}
if request.LocalBrowserEnabled && (customAgent == nil || !customAgent.IsAgentMode()) {
return nil, nil, errors.NewBadRequestError("Local browser requires an agent with tool calling enabled")
}
// Log merge results for debugging
logger.Infof(ctx, "[%s] @mention merge: request.KnowledgeBaseIDs=%v, request.MentionedItems=%d, merged kbIDs=%v, merged knowledgeIDs=%v",
logPrefix, request.KnowledgeBaseIDs, len(request.MentionedItems), kbIDs, knowledgeIDs)
// Process inline base64 images: decode and save to storage.
// VLM analysis for RAG paths is deferred to the pipeline rewrite step.
// For pure chat paths with non-vision models, VLM analysis runs here as fallback.
if len(request.Images) > 0 {
if customAgent == nil || !customAgent.Config.ImageUploadEnabled {
logger.Warnf(ctx, "[%s] Image upload is not enabled for this agent, rejecting %d images", logPrefix, len(request.Images))
return nil, nil, errors.NewBadRequestError("Image upload is not enabled for this agent")
}
tenantID := c.GetUint64(types.TenantIDContextKey.String())
agentStorageProvider := customAgent.Config.ImageStorageProvider
if err := h.saveImageAttachments(ctx, request.Images, tenantID, agentStorageProvider); err != nil {
logger.Errorf(ctx, "[%s] Failed to save images: %v", logPrefix, err)
return nil, nil, errors.NewBadRequestError(fmt.Sprintf("Image save failed: %v", err))
}
// VLM analysis is always deferred to after SSE stream is up:
// - Agent mode: runs in async execution flow with tool_call/tool_result events
// - Normal RAG mode: runs in the pipeline rewrite step with progress events
// - Normal pure-chat mode: runs in the async goroutine with progress events
}
2026-04-10 04:49:20 +00:00
// Process file attachments: decode and save to storage, extract content
var processedAttachments types.MessageAttachments
if len(request.AttachmentUploads) > 0 {
logger.Infof(ctx, "[%s] processing %d attachment(s)", logPrefix, len(request.AttachmentUploads))
feat(sandbox) (#2301) * 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>
2026-08-10 13:28:20 +00:00
// Decode first and validate actual bytes. Client-declared file_size is
// metadata only and must not be trusted for memory or sandbox limits.
maxSize := secutils.GetMaxFileSize()
decodedAttachments, decodeErr := decodeAndValidateAttachmentUploads(
request.AttachmentUploads,
maxAttachmentUploadsPerRequest,
maxSize,
maxAttachmentUploadTotalBytes,
)
if decodeErr != nil {
return nil, nil, errors.NewBadRequestError(decodeErr.Error())
2026-04-10 04:49:20 +00:00
}
tenantID := c.GetUint64(types.TenantIDContextKey.String())
attachmentRuntimeCtx := ctx
if effectiveTenantID != 0 {
attachmentRuntimeCtx = types.WithExecutionTenant(ctx, effectiveTenantID)
}
2026-04-10 04:49:20 +00:00
// Use ASR only when the agent has audio upload enabled.
asrModelID := ""
if customAgent != nil && customAgent.Config.AudioUploadEnabled && customAgent.Config.ASRModelID != "" {
asrModelID = customAgent.Config.ASRModelID
}
// Resolve the agent's chat parser engine from attachment file types
if customAgent != nil {
for _, att := range request.AttachmentUploads {
ext := strings.ToLower(filepath.Ext(att.FileName))
if engine := customAgent.Config.ResolveChatParserEngine(ext); engine != "" {
attachmentRuntimeCtx = context.WithValue(attachmentRuntimeCtx, types.ChatParserEngineContextKey, engine)
break
}
}
}
2026-04-10 04:49:20 +00:00
// Process all attachments concurrently.
processedAttachments = make(types.MessageAttachments, len(request.AttachmentUploads))
var wg sync.WaitGroup
errChan := make(chan error, len(request.AttachmentUploads))
for i, upload := range request.AttachmentUploads {
wg.Add(1)
go func(idx int, att AttachmentUpload) {
defer wg.Done()
processed, err := h.attachmentProcessor.ProcessAttachment(
feat(sandbox) (#2301) * 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>
2026-08-10 13:28:20 +00:00
attachmentRuntimeCtx, decodedAttachments[idx], att.FileName, int64(len(decodedAttachments[idx])), tenantID, asrModelID,
2026-04-10 04:49:20 +00:00
)
if err != nil {
errChan <- fmt.Errorf("attachment %d processing failed: %w", idx+1, err)
return
}
processedAttachments[idx] = *processed
}(i, upload)
}
wg.Wait()
close(errChan)
if len(errChan) > 0 {
err := <-errChan
logger.Errorf(ctx, "[%s] attachment processing failed: %v", logPrefix, err)
return nil, nil, errors.NewBadRequestError(fmt.Sprintf("attachment processing failed: %v", err))
}
logger.Infof(ctx, "[%s] all attachments processed", logPrefix)
}
// Pre-uploaded documents may still be parsing. Only fetch their metadata
// here (fast, available even while processing) to validate agent file-type
// limits and to record the attachments on the persisted user message. The
// heavy content selection happens after the SSE stream is up, so the send
// is not blocked while parsing finishes (see resolveTemporaryAttachments).
var attachmentIDs []string
var attachmentMetas types.MessageAttachments
if len(request.AttachmentIDs) > 0 {
normalizedIDs, normErr := normalizeTemporaryAttachmentIDs(request.AttachmentIDs)
if normErr != nil {
return nil, nil, errors.NewBadRequestError(normErr.Error())
}
tenantID := session.TenantID
attachmentMetas = make(types.MessageAttachments, 0, len(normalizedIDs))
for _, id := range normalizedIDs {
doc, getErr := h.temporaryDocuments.Get(ctx, tenantID, sessionID, id)
if getErr != nil || doc == nil {
return nil, nil, errors.NewBadRequestError(
fmt.Sprintf("attachment %s was not found in this session", secutils.SanitizeForLog(id)))
}
if customAgent != nil && len(customAgent.Config.SupportedFileTypes) > 0 {
ext := strings.TrimPrefix(strings.ToLower(doc.FileType), ".")
if !containsFileType(customAgent.Config.SupportedFileTypes, ext) {
return nil, nil, errors.NewBadRequestError(
fmt.Sprintf("file type %s is not supported by this agent", ext))
}
}
attachmentMetas = append(attachmentMetas, types.MessageAttachment{
ID: doc.ID, URL: doc.ResourceRef, FileName: doc.FileName,
FileType: doc.FileType, FileSize: doc.FileSize,
})
}
attachmentIDs = normalizedIDs
}
mentionScopes := tagScopesFromMentionedItems(request.MentionedItems)
requestTagIDs := dedupRequestStrings(request.TagIDs)
if err := validateUnscopedTagIDs(orphanTagIDsForScope(requestTagIDs, mentionScopes), secutils.SanitizeForLogArray(kbIDs)); err != nil {
return nil, nil, errors.NewBadRequestError(err.Error())
}
tagScopes := mergeTagScopesFromRequestIDs(mentionScopes, requestTagIDs, secutils.SanitizeForLogArray(kbIDs))
tagIDs := dedupRequestStrings(append(request.TagIDs, mentionedIDsByType(request.MentionedItems, "tag")...))
mcpServiceIDs := dedupRequestStrings(append(request.MCPServiceIDs, mentionedIDsByType(request.MentionedItems, "mcp")...))
skillNames := dedupRequestStrings(append(request.SkillNames, mentionedIDsByType(request.MentionedItems, "skill")...))
executionContext, agentID, agentTenantID, modelID := buildMessageExecutionContext(
ctx,
customAgent,
effectiveTenantID,
request.SummaryModelID,
secutils.SanitizeForLogArray(kbIDs),
secutils.SanitizeForLogArray(knowledgeIDs),
secutils.SanitizeForLogArray(tagIDs),
tagScopes,
secutils.SanitizeForLogArray(mcpServiceIDs),
secutils.SanitizeForLogArray(skillNames),
request.WebSearchEnabled,
)
executionContext.LocalBrowserEnabled = request.LocalBrowserEnabled
// Build request context
reqCtx := &qaRequestContext{
ctx: ctx,
c: c,
sessionID: sessionID,
requestID: requestID,
receivedAt: receivedAt,
query: request.Query,
session: session,
customAgent: customAgent,
assistantMessage: &types.Message{
SessionID: sessionID,
Role: "assistant",
RequestID: c.GetString(types.RequestIDContextKey.String()),
IsCompleted: false,
Channel: request.Channel,
AgentID: agentID,
AgentTenantID: agentTenantID,
ModelID: modelID,
ExecutionContext: executionContext,
},
knowledgeBaseIDs: secutils.SanitizeForLogArray(kbIDs),
knowledgeIDs: secutils.SanitizeForLogArray(knowledgeIDs),
tagScopes: tagScopes,
tagIDs: secutils.SanitizeForLogArray(tagIDs),
mcpServiceIDs: secutils.SanitizeForLogArray(mcpServiceIDs),
skillNames: secutils.SanitizeForLogArray(skillNames),
summaryModelID: secutils.SanitizeForLog(request.SummaryModelID),
webSearchEnabled: request.WebSearchEnabled,
localBrowserEnabled: request.LocalBrowserEnabled,
mentionedItems: convertMentionedItems(request.MentionedItems),
effectiveTenantID: effectiveTenantID,
sharedAgentReadOnly: sharedAgentReadOnly,
images: request.Images,
channel: request.Channel,
attachments: processedAttachments,
attachmentIDs: attachmentIDs,
attachmentMetas: attachmentMetas,
suggestionAttribution: request.SuggestionAttribution,
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 09:00:47 +00:00
questionOrigin: request.QuestionOrigin,
reqAgentEnabled: request.AgentEnabled,
reqAgentID: request.AgentID,
resourceRewriter: resourceRewriter,
}
return reqCtx, &request, nil
}
feat(sandbox) (#2301) * 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>
2026-08-10 13:28:20 +00:00
func decodeAndValidateAttachmentUploads(
uploads []AttachmentUpload,
maxCount int,
maxFileBytes, maxTotalBytes int64,
) ([][]byte, error) {
if len(uploads) > maxCount {
return nil, fmt.Errorf("at most %d attachments are allowed per request", maxCount)
}
decoded := make([][]byte, len(uploads))
var total int64
for i, upload := range uploads {
data, err := DecodeBase64Attachment(upload.Data)
if err != nil {
return nil, fmt.Errorf("attachment %d decode failed: %w", i+1, err)
}
actualSize := int64(len(data))
if actualSize > maxFileBytes {
return nil, fmt.Errorf("attachment %d exceeds size limit of %d bytes", i+1, maxFileBytes)
}
total += actualSize
if total > maxTotalBytes {
return nil, fmt.Errorf("attachments exceed total request limit of %d bytes", maxTotalBytes)
}
decoded[i] = data
}
return decoded, nil
}
func buildMessageExecutionContext(
ctx context.Context,
agent *types.CustomAgent,
effectiveTenantID uint64,
modelOverride string,
knowledgeBaseIDs []string,
knowledgeIDs []string,
tagIDs []string,
tagScopes []types.TagScope,
mcpServiceIDs []string,
skillNames []string,
webSearchEnabled bool,
) (types.MessageExecutionContext, string, uint64, string) {
locale := types.LanguageFromContextOrDefault(ctx)
snapshot := types.MessageExecutionContext{
KnowledgeBaseIDs: knowledgeBaseIDs,
KnowledgeIDs: knowledgeIDs,
TagIDs: tagIDs,
TagScopes: cloneTagScopes(tagScopes),
MCPServiceIDs: mcpServiceIDs,
SkillNames: skillNames,
WebSearchEnabled: webSearchEnabled,
Locale: locale,
LangfuseTraceparent: langfuse.TraceparentFromContext(ctx),
}
if agent == nil {
return snapshot, "", effectiveTenantID, modelOverride
}
modelID := modelOverride
if modelID == "" {
modelID = agent.Config.ModelID
}
agentTenantID := effectiveTenantID
if agentTenantID == 0 {
agentTenantID = agent.TenantID
}
// Marshal/unmarshal gives the snapshot independent backing slices, so a
// later agent edit cannot mutate an in-flight message context.
if agent.Config.QuestionSuggestions != nil {
if encoded, err := json.Marshal(agent.Config.QuestionSuggestions); err == nil {
var suggestions types.QuestionSuggestionConfig
if json.Unmarshal(encoded, &suggestions) == nil {
snapshot.QuestionSuggestions = &suggestions
}
}
}
hashInput := struct {
QuestionSuggestions *types.QuestionSuggestionConfig `json:"question_suggestions,omitempty"`
KnowledgeBaseIDs []string `json:"knowledge_base_ids,omitempty"`
KnowledgeIDs []string `json:"knowledge_ids,omitempty"`
TagIDs []string `json:"tag_ids,omitempty"`
TagScopes []types.TagScope `json:"tag_scopes,omitempty"`
ModelID string `json:"model_id,omitempty"`
}{
QuestionSuggestions: snapshot.QuestionSuggestions,
KnowledgeBaseIDs: knowledgeBaseIDs,
KnowledgeIDs: knowledgeIDs,
TagIDs: tagIDs,
TagScopes: snapshot.TagScopes,
ModelID: modelID,
}
if encoded, err := json.Marshal(hashInput); err == nil {
hash := sha256.Sum256(encoded)
snapshot.AgentConfigHash = fmt.Sprintf("%x", hash[:])
}
return snapshot, agent.ID, agentTenantID, modelID
}
func cloneTagScopes(scopes []types.TagScope) []types.TagScope {
if len(scopes) == 0 {
return nil
}
cloned := make([]types.TagScope, 0, len(scopes))
for _, scope := range scopes {
if scope.KnowledgeBaseID == "" || len(scope.TagIDs) == 0 {
continue
}
cloned = append(cloned, types.TagScope{
KnowledgeBaseID: scope.KnowledgeBaseID,
TagIDs: append([]string(nil), scope.TagIDs...),
})
}
return cloned
}
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 14:00:02 +00:00
// resolveAgent resolves the custom agent by ID: the caller's own agent unless a
// source workspace is given, otherwise (or when no own agent matches) a share.
// Returns (nil, 0) if agentID is empty or not found.
func (h *Handler) resolveAgent(
ctx context.Context,
c *gin.Context,
agentID string,
sourceTenantID uint64,
) (*types.CustomAgent, uint64, bool) {
if agentID == "" {
return nil, 0, false
}
logger.Infof(ctx, "Resolving agent, agent ID: %s", secutils.SanitizeForLog(agentID))
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 14:00:02 +00:00
// Without a source workspace the ID names the caller's own agent first.
// Built-in IDs exist in every workspace, so trying shares first would let
// any org member that shares an agent under such an ID take over the
// caller's default agent (and run the caller's chats in its workspace).
// A rejected shared selector (sourceTenantID != 0) must likewise never
// fall back to a same-ID local agent.
var ownErr error
if sourceTenantID == 0 {
agent, err := h.customAgentService.GetAgentByID(ctx, agentID)
if err == nil && agent != nil {
logger.Infof(ctx, "Using own agent: ID=%s, Name=%s, AgentMode=%s",
agent.ID, agent.Name, agent.Config.AgentMode)
return agent, 0, false
}
ownErr = err
}
var shareErr error
userIDVal, _ := c.Get(types.UserIDContextKey.String())
currentTenantID := c.GetUint64(types.TenantIDContextKey.String())
if h.agentShareService != nil && userIDVal != nil && currentTenantID != 0 {
feat(rbac): lift org membership from per-user to per-tenant (Plan 3, #1303) Before this change, the `organization_members` table keyed on user_id — joining an org as a Viewer in tenant T meant only that one user got visibility on shared KBs/agents, while the rest of T (including its Owner) saw nothing. The mismatch surfaced as confusing UX bugs: "my colleague shared this with us, why can't I see it?" This change replaces `organization_members` with `organization_tenant_members`. Membership and Org-RBAC role now key on (org_id, tenant_id); `representative_user_id` stays as a display-only label of the user who first brought the tenant in. Permission resolution gains a 3-D cap so tenant-RBAC stays honest under cross-tenant sharing: effective = min(share.Permission, tenant_org_role, tenant_role_cap) where tenant_role_cap pins tenant Viewers to OrgRoleViewer regardless of the org-level grant. A Viewer in their own tenant cannot edit a shared KB even if the org granted Editor — preserves the "Viewer = read-only everywhere" promise. Migration 000045 backfills `organization_tenant_members` from the old table by collapsing each (org, tenant) group to its max role, then renames the old table to `organization_members_pre_plan3` for safe rollback. Sqlite mirror (Lite mode) is fresh-bootstrap: the init schema replaces the old table directly. Routes: member-management URLs change from `:user_id` to `:tenant_id`. Org create / join / leave now require Admin+ in the caller's tenant — joining an Org affects everyone in T, so the decision can't sit with a Viewer. Frontend: OrganizationSettingsModal + store update to address members by tenant_id.
2026-05-15 13:49:54 +00:00
callerTenantRole := types.TenantRoleFromContext(ctx)
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 14:00:02 +00:00
agent, err := h.agentShareService.GetSharedAgentForTenant(
ctx, currentTenantID, callerTenantRole, agentID, sourceTenantID)
if err == nil && agent != nil {
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 14:00:02 +00:00
logger.Infof(ctx, "Using shared agent: ID=%s, Name=%s, IsBuiltin=%v, AgentMode=%s, effectiveTenantID=%d",
agent.ID, agent.Name, agent.IsBuiltin, agent.Config.AgentMode, agent.TenantID)
return agent, agent.TenantID, true
}
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 14:00:02 +00:00
shareErr = err
}
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 14:00:02 +00:00
logger.Warnf(ctx, "Failed to get agent, agent ID: %s, source tenant: %d, own error: %v, share error: %v, "+
"using default config", secutils.SanitizeForLog(agentID), sourceTenantID, ownErr, shareErr)
return nil, 0, false
}
// mergeKnowledgeTargets merges request KB/knowledge IDs with @mentioned items into deduplicated slices.
func mergeKnowledgeTargets(requestKBIDs []string, requestKnowledgeIDs []string, mentionedItems []MentionedItemRequest) (kbIDs []string, knowledgeIDs []string) {
kbIDSet := make(map[string]bool)
kbIDs = make([]string, 0, len(requestKBIDs)+len(mentionedItems))
for _, id := range requestKBIDs {
if id != "" && !kbIDSet[id] {
kbIDs = append(kbIDs, id)
kbIDSet[id] = true
}
}
knowledgeIDSet := make(map[string]bool)
knowledgeIDs = make([]string, 0, len(requestKnowledgeIDs)+len(mentionedItems))
for _, id := range requestKnowledgeIDs {
if id != "" && !knowledgeIDSet[id] {
knowledgeIDs = append(knowledgeIDs, id)
knowledgeIDSet[id] = true
}
}
for _, item := range mentionedItems {
if item.ID == "" {
continue
}
switch item.Type {
case "kb":
if !kbIDSet[item.ID] {
kbIDs = append(kbIDs, item.ID)
kbIDSet[item.ID] = true
}
case "file":
if !knowledgeIDSet[item.ID] {
knowledgeIDs = append(knowledgeIDs, item.ID)
knowledgeIDSet[item.ID] = true
}
}
}
return kbIDs, knowledgeIDs
}
// sseStreamContext holds the context for SSE streaming
type sseStreamContext struct {
eventBus *event.EventBus
streamHandler *AgentStreamHandler
asyncCtx context.Context
cancel context.CancelFunc
assistantMessage *types.Message
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
// steerSink bridges the engine's round-boundary drain to the steer
// sub-list and user-row persistence. Nil for non-agent modes.
steerSink *steerSink
// liveRunFailed is set when SetLiveRun failed. executeQA must not start
// the engine: /steer would see no marker and the client would start a
// second turn.
liveRunFailed bool
liveRunErr error
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 13:01:00 +00:00
// releaseTurn ends the sandbox turn lease taken before persist. Knowledge
// mode releases on completion (the pipeline returns before the stream
// finishes); agent mode releases when AgentQA returns.
releaseTurn func()
}
// setupSSEStream sets up the SSE streaming context
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
func (h *Handler) setupSSEStream(reqCtx *qaRequestContext, generateTitle bool, mode qaMode) *sseStreamContext {
// Base context for async work: when using shared agent, use source tenant for model/KB/MCP resolution
baseCtx := reqCtx.ctx
if reqCtx.effectiveTenantID != 0 && h.tenantService != nil {
if tenant, err := h.tenantService.GetTenantByID(reqCtx.ctx, reqCtx.effectiveTenantID); err == nil && tenant != nil {
baseCtx = types.WithExecutionTenant(reqCtx.ctx, reqCtx.effectiveTenantID)
if reqCtx.customAgent != nil {
baseCtx = access.WithSharedAgent(baseCtx, reqCtx.customAgent)
}
baseCtx = context.WithValue(baseCtx, types.TenantInfoContextKey, tenant)
logger.Infof(
reqCtx.ctx,
"Using effective tenant %d for shared agent (model/KB/MCP)",
reqCtx.effectiveTenantID,
)
}
}
feat(sandbox) (#2301) * 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>
2026-08-10 13:28:20 +00:00
// The session's sandbox stays bound to the session owner even when the
// borrowed tenant above drives everything else, because DeleteSession tears
// that sandbox down from a request that only knows the session's tenant.
baseCtx = types.WithSandboxTenantID(baseCtx, reqCtx.session.TenantID)
// An agent that opted out of long-term memory has to be opted out of the
// write path too, not just recall. The two run from different contexts:
// recall is marked inside the QA services, while extraction, the explicit
// "remember this" route and document affinity are all kicked off from
// completeAssistantMessage on a context descended from this one. Marking
// the root of the async work is what keeps them from disagreeing — an
// agent that cannot read the memory must not keep writing to it.
if reqCtx.customAgent != nil {
baseCtx = types.ApplyAgentMemoryPreference(baseCtx, reqCtx.customAgent.Config.MemoryEnabled)
}
eventBus := event.NewEventBus()
asyncCtx, cancel := context.WithCancel(logger.CloneContext(baseCtx))
streamCtx := &sseStreamContext{
eventBus: eventBus,
asyncCtx: asyncCtx,
cancel: cancel,
assistantMessage: reqCtx.assistantMessage,
}
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
// Mid-run steering: only ReAct agent turns (qaModeAgent) have an engine
// loop to drain at and a teardown that ClearLiveRun / kick / discard.
// A custom agent configured as quick-answer still has customAgent != nil
// but executeQA runs KnowledgeQA — publishing a sink there parks /steer
// messages until the Redis TTL expires. The sink is also mirrored onto
// reqCtx so the async goroutine's buildQARequest() picks it up — the
// streamCtx copy alone is never read by the QA call path.
//
// SetLiveRun happens before SSE headers: a 409/503 after text/event-stream
// has started cannot change the status, and the client would sit on a
// stream nobody will write to.
if mode == qaModeAgent && reqCtx.customAgent != nil {
streamCtx.steerSink = newSteerSink(
asyncCtx, reqCtx.sessionID, reqCtx.requestID, reqCtx.assistantMessage,
h.messageService, h.streamManager,
)
reqCtx.steerSink = streamCtx.steerSink
if err := h.streamManager.SetLiveRun(
logger.CloneContext(baseCtx), reqCtx.sessionID,
reqCtx.assistantMessage.ID, reqCtx.requestID,
); err != nil {
logger.ErrorWithFields(reqCtx.ctx, err, map[string]interface{}{
"session_id": reqCtx.sessionID,
})
streamCtx.liveRunFailed = true
streamCtx.liveRunErr = err
return streamCtx
}
}
if !reqCtx.skipSSE {
setSSEHeaders(reqCtx.c)
}
h.writeAgentQueryEvent(
reqCtx.ctx,
reqCtx.sessionID,
reqCtx.userMessageID,
reqCtx.userCreatedAt,
reqCtx.assistantMessage,
)
// Setup stop event handler
h.setupStopEventHandler(eventBus, reqCtx.sessionID, reqCtx.session.TenantID, reqCtx.assistantMessage, cancel)
// Watch for stop events independently of the client SSE connection so a
// user-requested stop reliably cancels generation even when the client
// has already disconnected (e.g. API-Key callers that close the stream
// before POSTing /stop). The watcher self-terminates on a terminal stream
// event, so its lifetime is decoupled from when the QA service call
// returns (KnowledgeQA returns immediately while streaming continues in a
// background goroutine, whereas AgentQA blocks until done). Use a
// connection-independent context derived from baseCtx so it survives the
// client disconnect.
h.startStopWatcher(logger.CloneContext(baseCtx), reqCtx.sessionID, reqCtx.assistantMessage.ID, eventBus)
// Setup stream handler
streamCtx.streamHandler = h.setupStreamHandler(asyncCtx, reqCtx.sessionID, reqCtx.assistantMessage.ID,
feat(sandbox) (#2301) * 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>
2026-08-10 13:28:20 +00:00
reqCtx.requestID, reqCtx.session.TenantID, reqCtx.receivedAt, reqCtx.assistantMessage, eventBus)
// Generate title if needed
if generateTitle && reqCtx.session.Title == "" {
// Use the same model as the conversation for title generation
modelID := ""
if reqCtx.customAgent != nil && reqCtx.customAgent.Config.ModelID != "" {
modelID = reqCtx.customAgent.Config.ModelID
}
logger.Infof(reqCtx.ctx, "Session has no title, starting async title generation, session ID: %s, model: %s", reqCtx.sessionID, modelID)
h.sessionService.GenerateTitleAsync(asyncCtx, reqCtx.session, reqCtx.query, modelID, eventBus)
}
return streamCtx
}
// SearchKnowledge godoc
// @Summary 知识搜索
// @Description 在知识库中搜索(不使用LLM总结)
// @Tags 问答
// @Accept json
// @Produce json
// @Param request body SearchKnowledgeRequest true "搜索请求"
// @Param resource_urls query string false "文件引用形式,public 返回可加载直链" Enums(handle, public) default(handle)
// @Success 200 {object} map[string]interface{} "搜索结果"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge-search [post]
func (h *Handler) SearchKnowledge(c *gin.Context) {
ctx := logger.CloneContext(c.Request.Context())
logger.Info(ctx, "Start processing knowledge search request")
// Parse request body
var request SearchKnowledgeRequest
if err := c.ShouldBindJSON(&request); err != nil {
logger.Error(ctx, "Failed to parse request data", err)
c.Error(errors.NewBadRequestError(err.Error()))
return
}
// Validate request parameters
if request.Query == "" {
logger.Error(ctx, "Query content is empty")
c.Error(errors.NewBadRequestError("Query content cannot be empty"))
return
}
fix(api): close the resource_urls=public gaps found in review Follow-up on resource_urls=public. Review turned up one authorization gap plus a set of correctness problems in the streaming path. Authorization: - Embed channels were documented as excluded, but nothing enforced it. The delegating handlers hand the visitor's own gin context to the shared handlers, so ?resource_urls=public — and a deployment-wide RESOURCE_URL_MODE=public — reached anonymous traffic and produced shareable, credential-free URLs that bypass the channel-scoped /embed/:channel_id/files proxy. ensureEmbedSession now pins the request context to handle mode, which covers every delegated endpoint including future ones. The downgrade is silent so a client that forwards the parameter keeps working. - A knowledge-base-restricted API key is refused with 403. Such a key is already denied /files because a raw storage path cannot be bound to its allow-list, so handing it anonymous file URLs would reopen that hole from the other side. The default handle mode stays available to it. Streaming: - Rewriter.ref holds its lock across resolution. Resolver implementations keep an unsynchronised per-provider cache, so the previous unlocked window was a real data race for any caller sharing a StreamRewriter between goroutines — which its own doc comment invited. Serialising also collapses a concurrent duplicate into one signature. - Release the holdback buffer on every path that ends a stream while the client is still connected: a user-requested stop, an error event, and giving up on the event store. Only completion flushed before, so the tail generated just before a stop was silently dropped. - A released tail carries the metadata of the event it was cut from instead of a bare event_id. - The maxHeldBytes safety valve aligns to a UTF-8 boundary rather than cutting a character in half, and an unclosed "![…](" only holds back a whitespace-free destination under 2048 bytes, so prose that merely mentions Markdown image syntax no longer stalls the stream behind the buffer. Also resolves the mode before running a knowledge search instead of after, so an invalid value no longer costs a full retrieval, and warns once per distinct bad RESOURCE_URL_MODE value instead of once per process. Co-authored-by: lyingbug <lyingbug@users.noreply.github.com>
2026-08-04 15:46:54 +00:00
// Resolve the storage-reference representation before retrieving, so a typo
// or a rejected scope costs nothing.
rewriter, err := h.resolveResourceRewriter(c)
if err != nil {
logger.Warnf(ctx, "Rejected resource URL mode: %v", err)
_ = c.Error(err)
return
}
// Merge single knowledge_base_id into knowledge_base_ids for backward compatibility
knowledgeBaseIDs := request.KnowledgeBaseIDs
if request.KnowledgeBaseID != "" {
// Check if it's already in the list to avoid duplicates
found := false
for _, id := range knowledgeBaseIDs {
if id == request.KnowledgeBaseID {
found = true
break
}
}
if !found {
knowledgeBaseIDs = append(knowledgeBaseIDs, request.KnowledgeBaseID)
}
}
mentionScopes := tagScopesFromMentionedItems(request.MentionedItems)
requestTagIDs := dedupRequestStrings(request.TagIDs)
if err := validateUnscopedTagIDs(orphanTagIDsForScope(requestTagIDs, mentionScopes), secutils.SanitizeForLogArray(knowledgeBaseIDs)); err != nil {
logger.Error(ctx, err.Error())
c.Error(errors.NewBadRequestError(err.Error()))
return
}
tagScopes := mergeTagScopesFromRequestIDs(mentionScopes, requestTagIDs, secutils.SanitizeForLogArray(knowledgeBaseIDs))
if len(knowledgeBaseIDs) == 0 && len(request.KnowledgeIDs) == 0 && len(tagScopes) == 0 {
logger.Error(ctx, "No knowledge base IDs, knowledge IDs, or tag scopes provided")
c.Error(errors.NewBadRequestError("At least one knowledge_base_id, knowledge_base_ids, knowledge_ids, or scoped tag must be provided"))
return
}
if err := types.AuthorizeTenantAPIKeyKnowledgeTargets(ctx, knowledgeBaseIDs, request.KnowledgeIDs); err != nil {
2026-07-05 02:25:37 +00:00
c.Error(err)
return
}
logger.Infof(
ctx,
"Knowledge search request, knowledge base IDs: %v, knowledge IDs: %v, tag scopes: %d, query: %s",
secutils.SanitizeForLogArray(knowledgeBaseIDs),
secutils.SanitizeForLogArray(request.KnowledgeIDs),
len(tagScopes),
secutils.SanitizeForLog(request.Query),
)
// Directly call knowledge retrieval service without LLM summarization
searchResults, err := h.sessionService.SearchKnowledge(ctx, knowledgeBaseIDs, request.KnowledgeIDs, tagScopes, request.Query)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
logger.Infof(ctx, "Knowledge search completed, found %d results", len(searchResults))
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": rewriter.CopyReferences(ctx, searchResults),
})
}
// KnowledgeQA godoc
// @Summary 知识问答
// @Description 基于知识库的问答(使用LLM总结),支持SSE流式响应
// @Tags 问答
// @Accept json
// @Produce text/event-stream
// @Param session_id path string true "会话ID"
// @Param request body CreateKnowledgeQARequest true "问答请求"
// @Param resource_urls query string false "文件引用形式,public 返回可加载直链" Enums(handle, public) default(handle)
// @Success 200 {object} map[string]interface{} "问答结果(SSE流)"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge-chat/{session_id} [post]
func (h *Handler) KnowledgeQA(c *gin.Context) {
// Parse and validate request
reqCtx, request, err := h.parseQARequest(c, "KnowledgeQA")
if err != nil {
c.Error(err)
return
}
// Execute normal mode QA, generate title unless disabled
if request.LocalBrowserEnabled {
_ = c.Error(errors.NewBadRequestError("Local browser requests must use the agent endpoint"))
return
}
h.executeQA(reqCtx, qaModeNormal, !request.DisableTitle)
}
// AgentQA godoc
// @Summary Agent问答
// @Description 基于Agent的智能问答,支持多轮对话和SSE流式响应
// @Tags 问答
// @Accept json
// @Produce text/event-stream
// @Param session_id path string true "会话ID"
// @Param request body CreateKnowledgeQARequest true "问答请求"
// @Param resource_urls query string false "文件引用形式,public 返回可加载直链" Enums(handle, public) default(handle)
// @Success 200 {object} map[string]interface{} "问答结果(SSE流)"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /agent-chat/{session_id} [post]
func (h *Handler) AgentQA(c *gin.Context) {
// Parse and validate request
reqCtx, request, err := h.parseQARequest(c, "AgentQA")
if err != nil {
c.Error(err)
return
}
// Determine if agent mode should be enabled
// Priority: customAgent.IsAgentMode() > request.AgentEnabled
agentModeEnabled := request.AgentEnabled
if reqCtx.customAgent != nil {
agentModeEnabled = reqCtx.customAgent.IsAgentMode()
logger.Infof(reqCtx.ctx, "Agent mode determined by custom agent: %v (config.agent_mode=%s)",
agentModeEnabled, reqCtx.customAgent.Config.AgentMode)
}
// Sanity gate: agent mode requires a resolved CustomAgent. If we got
// here with agent_enabled=true but agent_id missing/unresolvable, the
// AgentQA service will fail deep inside the async goroutine with a
// generic "custom agent configuration is required" error and the user
// just sees a broken stream. Reject early with a clear 400 so the
// frontend can recover (e.g. fall back to quick-answer). Most likely
// cause is a stale localStorage settings blob where selectedAgentId
// got blanked but isAgentEnabled stayed true — usually after a
// cross-tenant switch where the previously selected agent is no
// longer visible.
if agentModeEnabled && reqCtx.customAgent == nil {
logger.Warnf(reqCtx.ctx,
"Agent mode requested without a resolvable agent_id, rejecting; session=%s, request.AgentID=%q",
reqCtx.sessionID, secutils.SanitizeForLog(request.AgentID))
c.Error(errors.NewBadRequestError(
"agent_id is required when agent mode is enabled"))
return
}
// Route to appropriate handler based on agent mode
if agentModeEnabled {
h.executeQA(reqCtx, qaModeAgent, true)
} else {
logger.Infof(reqCtx.ctx, "Agent mode disabled, delegating to normal mode for session: %s", reqCtx.sessionID)
h.executeQA(reqCtx, qaModeNormal, !request.DisableTitle)
}
}
// qaMode determines which QA execution path to use.
type qaMode int
const (
qaModeNormal qaMode = iota // KnowledgeQA pipeline (RAG / pure chat)
qaModeAgent // Agent engine with tool calling
)
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
// persistTurnMessages writes the user and assistant rows for this turn.
// Follow-up handoff calls it before SetLiveRun so POST /steer can verify the
// new assistant instead of seeing an empty session. executeQA skips work that
// is already done when those IDs are populated.
func (h *Handler) persistTurnMessages(ctx context.Context, reqCtx *qaRequestContext) error {
createdUser := false
if reqCtx.userMessageID == "" {
userMessageAttachments := reqCtx.attachments
if len(reqCtx.attachmentMetas) > 0 {
userMessageAttachments = append(
append(types.MessageAttachments{}, reqCtx.attachments...),
reqCtx.attachmentMetas...,
)
}
userMsg, err := h.createUserMessage(
ctx,
reqCtx.sessionID,
reqCtx.query,
reqCtx.requestID,
reqCtx.mentionedItems,
convertImageAttachments(reqCtx.images),
userMessageAttachments,
reqCtx.channel,
reqCtx.suggestionAttribution,
)
if err != nil {
return err
}
reqCtx.userMessageID = userMsg.ID
reqCtx.userCreatedAt = userMsg.CreatedAt
createdUser = true
}
if reqCtx.assistantMessage == nil {
reqCtx.assistantMessage = &types.Message{
SessionID: reqCtx.sessionID,
Role: "assistant",
IsCompleted: false,
RequestID: reqCtx.requestID,
CreatedAt: time.Now(),
}
}
if reqCtx.assistantMessage.ID == "" {
assistantMessagePtr, err := h.createAssistantMessage(ctx, reqCtx.assistantMessage)
if err != nil {
h.rollbackTurnMessages(ctx, reqCtx, createdUser, false)
return err
}
reqCtx.assistantMessage = assistantMessagePtr
}
return nil
}
// rollbackTurnMessages deletes user/assistant rows this request just created
// so a failed SetLiveRun / ClaimLiveRun cannot leave an orphan turn in history.
func (h *Handler) rollbackTurnMessages(ctx context.Context, reqCtx *qaRequestContext, user, assistant bool) {
if h.messageService == nil || reqCtx == nil {
return
}
sessionID := reqCtx.sessionID
if user && reqCtx.userMessageID != "" {
if err := h.messageService.DeleteMessage(ctx, sessionID, reqCtx.userMessageID); err != nil {
logger.Warnf(ctx, "turn rollback failed for user message %s: %v", reqCtx.userMessageID, err)
} else {
reqCtx.userMessageID = ""
}
}
if assistant && reqCtx.assistantMessage != nil && reqCtx.assistantMessage.ID != "" {
if err := h.messageService.DeleteMessage(ctx, sessionID, reqCtx.assistantMessage.ID); err != nil {
logger.Warnf(ctx, "turn rollback failed for assistant message %s: %v", reqCtx.assistantMessage.ID, err)
} else {
reqCtx.assistantMessage.ID = ""
}
}
}
func (h *Handler) rejectIfOtherAgentRunLive(ctx context.Context, reqCtx *qaRequestContext) error {
liveID, _, err := h.streamManager.GetLiveRun(ctx, reqCtx.sessionID)
if err != nil {
return errors.NewServiceUnavailableError("Failed to look up running turn")
}
if liveID == "" {
return nil
}
self := ""
if reqCtx.assistantMessage != nil {
self = reqCtx.assistantMessage.ID
}
if liveID == self {
return nil
}
return errors.NewConflictError("another turn is already running in this session")
}
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 13:01:00 +00:00
func (h *Handler) rejectIfSessionRewinding(ctx context.Context, sessionID string) error {
type rewindSendGuard interface {
RejectSendIfRewinding(context.Context, string) error
}
guard, ok := h.sessionService.(rewindSendGuard)
if !ok {
return nil
}
err := guard.RejectSendIfRewinding(ctx, sessionID)
if err == nil {
return nil
}
if stderrors.Is(err, sandbox.ErrSessionRewindLocked) {
return errors.NewConflictError("session rewind is in progress")
}
return errors.NewInternalServerError(err.Error())
}
func (h *Handler) holdQATurn(ctx context.Context, reqCtx *qaRequestContext) (func(), bool) {
noop := func() {}
if reqCtx == nil {
return noop, true
}
type sessionTurnHolder interface {
HoldSandboxTurn(context.Context, string, string) (func(), error)
}
holder, ok := h.sessionService.(sessionTurnHolder)
if !ok {
return noop, true
}
configID := ""
if reqCtx.customAgent != nil {
configID = reqCtx.customAgent.Config.SandboxConfigID
}
release, err := holder.HoldSandboxTurn(ctx, reqCtx.sessionID, configID)
if err == nil {
// The QA service reads this off the built request and skips its own
// hold, so the send path opens and closes the lease exactly once.
reqCtx.turnLeaseHeld = true
}
if err != nil {
if reqCtx.c != nil && !reqCtx.skipSSE {
if stderrors.Is(err, sandbox.ErrSessionRewindLocked) || stderrors.Is(err, sandbox.ErrSessionTurnActive) {
_ = reqCtx.c.Error(errors.NewConflictError("session rewind is in progress"))
} else {
_ = reqCtx.c.Error(errors.NewInternalServerError(err.Error()))
}
} else {
logger.ErrorWithFields(ctx, err, map[string]interface{}{"session_id": reqCtx.sessionID})
}
return noop, false
}
if release == nil {
release = noop
}
var once sync.Once
return func() { once.Do(release) }, true
}
// executeQA is the unified execution flow for both KnowledgeQA and AgentQA modes.
// It handles message creation, SSE setup, VLM analysis, service invocation, and error handling.
func (h *Handler) executeQA(reqCtx *qaRequestContext, mode qaMode, generateTitle bool) {
ctx := reqCtx.ctx
sessionID := reqCtx.sessionID
// Persist the input-bar state used for this request so reopening the
// session can rehydrate agent / model / KB / web-search / MCP selections.
// This is a pure UI memo (no behavioural effect) and runs in a goroutine
// to avoid adding a DB round-trip to TTFB. Use WithoutCancel so a fast
// client disconnect doesn't drop the write.
go h.persistLastRequestState(ctx, reqCtx, mode)
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
if mode == qaModeAgent {
if err := h.rejectIfOtherAgentRunLive(ctx, reqCtx); err != nil {
if reqCtx.c != nil && !reqCtx.skipSSE {
_ = reqCtx.c.Error(err)
} else {
logger.ErrorWithFields(ctx, err, map[string]interface{}{"session_id": sessionID})
}
return
}
}
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 13:01:00 +00:00
if err := h.rejectIfSessionRewinding(ctx, sessionID); err != nil {
if reqCtx.c != nil && !reqCtx.skipSSE {
_ = reqCtx.c.Error(err)
} else {
logger.ErrorWithFields(ctx, err, map[string]interface{}{"session_id": sessionID})
}
return
}
releaseQATurn, held := h.holdQATurn(ctx, reqCtx)
if !held {
return
}
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
// Agent mode: emit agent query event before message creation
if mode == qaModeAgent {
if err := event.Emit(ctx, event.Event{
Type: event.EventAgentQuery,
SessionID: sessionID,
RequestID: reqCtx.requestID,
Data: event.AgentQueryData{
SessionID: sessionID,
Query: reqCtx.query,
RequestID: reqCtx.requestID,
},
}); err != nil {
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 13:01:00 +00:00
releaseQATurn()
logger.Errorf(ctx, "Failed to emit agent query event: %v", err)
return
}
}
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
createdUser := reqCtx.userMessageID == ""
createdAssistant := reqCtx.assistantMessage == nil || reqCtx.assistantMessage.ID == ""
// Create user message. Include pre-uploaded document metadata so history
// reload shows the attachments even though their content is selected later.
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
if err := h.persistTurnMessages(ctx, reqCtx); err != nil {
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 13:01:00 +00:00
releaseQATurn()
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
if reqCtx.c != nil && !reqCtx.skipSSE {
_ = reqCtx.c.Error(errors.NewInternalServerError(err.Error()))
} else {
logger.ErrorWithFields(ctx, err, map[string]interface{}{"session_id": sessionID})
}
return
}
if mode == qaModeNormal {
logger.Infof(ctx, "Using knowledge bases: %v", reqCtx.knowledgeBaseIDs)
} else {
logger.Infof(ctx, "Calling agent QA service, session ID: %s", sessionID)
}
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
// Move the previous run's leftovers onto this run's queue before the run
// announces itself as live. The other order leaves a window where a
// client that reloads the queue sees an empty one and drops messages the
// user can still see in the composer.
if len(reqCtx.steerCarryOver) > 0 && reqCtx.assistantMessage != nil {
if err := h.streamManager.AppendSteerEvents(
ctx, sessionID, reqCtx.assistantMessage.ID, reqCtx.steerCarryOver,
); err != nil {
logger.Warnf(ctx, "steer carry-over append failed for session %s: %v", sessionID, err)
}
}
// Setup SSE stream
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
streamCtx := h.setupSSEStream(reqCtx, generateTitle, mode)
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 13:01:00 +00:00
streamCtx.releaseTurn = releaseQATurn
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
if streamCtx.liveRunFailed {
if streamCtx.cancel != nil {
streamCtx.cancel()
}
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 13:01:00 +00:00
releaseQATurn()
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
h.rollbackTurnMessages(ctx, reqCtx, createdUser, createdAssistant)
if reqCtx.c != nil && !reqCtx.skipSSE {
if stderrors.Is(streamCtx.liveRunErr, stream.ErrLiveRunExists) {
_ = reqCtx.c.Error(errors.NewConflictError("another turn is already running in this session"))
} else {
_ = reqCtx.c.Error(errors.NewServiceUnavailableError("Failed to publish running turn"))
}
}
return
}
// Normal mode: register completion handler on EventAgentFinalAnswer
// (Agent mode handles completion in the defer block instead)
if mode == qaModeNormal {
var completionHandled bool
// Persist the pipeline's retrieval/attachment stages so a reloaded
// conversation redraws the timeline it showed while streaming, including
// turns that searched and cited nothing.
registerQuickAnswerTimelineRecorder(streamCtx.eventBus, streamCtx.assistantMessage)
// Persist reasoning_content into agent_steps so historical reload can
// reconstruct the thinking card (same shape as Agent-mode steps).
// Accumulate on assistantMessage directly so user-initiated stop also
// keeps whatever reasoning had streamed before the cancel.
streamCtx.eventBus.On(event.EventAgentThought, func(ctx context.Context, evt event.Event) error {
data, ok := evt.Data.(event.AgentThoughtData)
if !ok || data.Content == "" {
return nil
}
appendQuickAnswerReasoning(streamCtx.assistantMessage, data.Content)
return nil
})
streamCtx.eventBus.On(event.EventAgentFinalAnswer, func(ctx context.Context, evt event.Event) error {
data, ok := evt.Data.(event.AgentFinalAnswerData)
if !ok {
return nil
}
streamCtx.assistantMessage.Content += data.Content
if data.IsFallback {
streamCtx.assistantMessage.IsFallback = true
}
if data.Done {
if completionHandled {
return nil
}
completionHandled = true
logger.Infof(streamCtx.asyncCtx, "Knowledge QA service completed for session: %s", sessionID)
updateCtx := context.WithValue(streamCtx.asyncCtx, types.TenantIDContextKey, reqCtx.session.TenantID)
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 06:20:18 +00:00
h.completeQuickAnswerTurn(updateCtx, streamCtx, reqCtx.query, reqCtx.userMessageID)
}
return nil
})
}
// Execute QA asynchronously
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
asyncDone := make(chan struct{})
go func() {
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
defer close(asyncDone)
defer func() {
if r := recover(); r != nil {
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 13:01:00 +00:00
if streamCtx.releaseTurn != nil {
streamCtx.releaseTurn()
}
buf := make([]byte, 10240)
runtime.Stack(buf, true)
stageName := "Knowledge QA"
if mode == qaModeAgent {
stageName = "Agent QA"
}
logger.ErrorWithFields(streamCtx.asyncCtx,
errors.NewInternalServerError(fmt.Sprintf("%s service panicked: %v\n%s", stageName, r, string(buf))),
map[string]interface{}{"session_id": sessionID})
}
// Agent mode: complete the assistant message in defer (normal mode does it via event handler)
if mode == qaModeAgent {
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 13:01:00 +00:00
if streamCtx.releaseTurn != nil {
streamCtx.releaseTurn()
}
// Use WithoutCancel so a user-triggered stop (which cancels
// asyncCtx) doesn't also cancel the GORM UPDATE that persists
// AgentSteps/Content. Without this, cancelled-ctx makes
// GORM skip the write and the agent's intermediate steps
// (thinking / tool_call history) are lost on page refresh.
updateCtx := context.WithValue(
context.WithoutCancel(streamCtx.asyncCtx),
types.TenantIDContextKey, reqCtx.session.TenantID,
)
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
// Claim any follow-up before completing this row. liveAgentRun
// treats a completed assistant as idle and would ClearLiveRun
// the old marker — exactly the new_run window. The follow-up
// SetLiveRun's first; this run's CAS ClearLiveRun then no-ops.
if streamCtx.asyncCtx.Err() != nil {
// The turn was cancelled — a user stop. Stopping means
// stopping: queued follow-ups are dropped rather than
// fired off as a brand-new run the user did not ask for.
injected := map[string]struct{}{}
if streamCtx.steerSink != nil {
injected = streamCtx.steerSink.InjectedIDs()
}
h.discardSteerBacklog(updateCtx, sessionID, streamCtx.assistantMessage.ID, injected)
h.completeStreamAssistantMessage(
updateCtx, streamCtx, reqCtx.query, reqCtx.userMessageID,
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
)
} else {
kicked := h.kickNextRunFromSteerBacklog(updateCtx, reqCtx, streamCtx)
h.completeStreamAssistantMessage(
updateCtx, streamCtx, reqCtx.query, reqCtx.userMessageID,
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
)
// A /steer that landed while we were completing still sits
// on this run. Claim it before ClearLiveRun so it is not
// stranded on a list nobody will drain.
if !kicked {
h.kickNextRunFromSteerBacklog(updateCtx, reqCtx, streamCtx)
}
}
if err := h.streamManager.ClearLiveRun(
updateCtx, sessionID, streamCtx.assistantMessage.ID,
); err != nil {
logger.Warnf(updateCtx, "live run cleanup failed for session %s: %v", sessionID, err)
}
logger.Infof(streamCtx.asyncCtx, "Agent QA service completed for session: %s", sessionID)
}
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 13:01:00 +00:00
// Knowledge mode normally releases on EventAgentFinalAnswer Done.
// If that event never fires, release here so rewind is not blocked
// until the Redis turn TTL expires.
if mode == qaModeNormal && streamCtx.releaseTurn != nil {
streamCtx.releaseTurn()
}
}()
// Resolve pre-uploaded attachments (may still be parsing): waits with a
// timeline step so the send is not blocked, then injects content/images.
h.resolveTemporaryAttachments(streamCtx, reqCtx)
// Run VLM image analysis if applicable
h.runVLMAnalysisIfNeeded(streamCtx, reqCtx, mode)
// Build QA request and invoke the appropriate service
qaReq := reqCtx.buildQARequest()
var serviceErr error
var stageName string
if mode == qaModeNormal {
stageName = "knowledge_qa_execution"
serviceErr = h.sessionService.KnowledgeQA(streamCtx.asyncCtx, qaReq, streamCtx.eventBus)
} else {
stageName = "agent_execution"
serviceErr = h.sessionService.AgentQA(streamCtx.asyncCtx, qaReq, streamCtx.eventBus)
}
if serviceErr != nil {
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 13:01:00 +00:00
if mode == qaModeNormal && streamCtx.releaseTurn != nil {
streamCtx.releaseTurn()
}
// A user-requested stop cancels asyncCtx, which surfaces here as a
// context cancellation. That is an expected outcome, not a failure:
// the stop event already notifies the client, so don't emit a
// spurious error event (which would otherwise show an error toast).
if streamCtx.asyncCtx.Err() != nil {
logger.Infof(streamCtx.asyncCtx, "QA cancelled by user stop for session: %s", sessionID)
} else {
logger.ErrorWithFields(streamCtx.asyncCtx, serviceErr, nil)
streamCtx.eventBus.Emit(streamCtx.asyncCtx, event.Event{
Type: event.EventError,
SessionID: sessionID,
Data: event.ErrorData{
Error: serviceErr.Error(),
Stage: stageName,
SessionID: sessionID,
},
})
}
}
}()
feat(chat): append messages to a running agent turn (#3123) * feat(stream): persist live-run markers and per-run steer queues Mid-run sends need a cross-replica pointer to the generating assistant and a control-plane list that never hits the SSE stream. * feat(agent): inject queued user messages at ReAct round boundaries The engine drains the steer sink after each round, persists accepted rows, and delays Done until after a loop-end inject so the turn can continue. * feat(session): expose /steer and hand leftover messages to a follow-up turn Owner-scoped steer routes queue or inject into the live run, single-flight AgentQA via the live-run marker, and history replay keeps multiple user rows inside one turn. * feat(frontend): queue mid-run messages while an agent turn streams Stop and Send stay visible together, the overlay follows server delivery, and history splits the transcript around injected user bubbles. * fix(frontend): type pending and client_id on SteerQueueItem vue-tsc failed because the overlay sets those fields while POST /steer is in flight. * fix(session): harden steer persist, handoff, and new_run Keep SetLiveRun ahead of SSE and roll back orphan turns, make inject persist idempotent, append-then-delete on rebind, cap overrun rounds, and stop aborting a live stream when /steer returns new_run. * fix(session): satisfy pre-push lint on steer paths Wrap long lines, check discarded Error/Emit results, and keep context as the first argument so the fork push hook can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-09 08:43:33 +00:00
if reqCtx.skipSSE {
<-asyncDone
return
}
// Handle SSE events (blocking)
shouldWaitForTitle := generateTitle && reqCtx.session.Title == ""
h.handleAgentEventsForSSE(ctx, reqCtx.c, sessionID, reqCtx.assistantMessage.ID,
reqCtx.requestID, streamCtx.eventBus, shouldWaitForTitle, reqCtx.resourceRewriter)
}
// runVLMAnalysisIfNeeded runs VLM image analysis within the async goroutine,
// emitting tool_call/tool_result events so the user can see progress.
// For normal mode, VLM only runs on the pure-chat path (no KB, no web search);
// RAG paths defer VLM to the pipeline rewrite step.
// For agent mode, VLM always runs when images and a VLM model are present.
func (h *Handler) runVLMAnalysisIfNeeded(streamCtx *sseStreamContext, reqCtx *qaRequestContext, mode qaMode) {
if len(reqCtx.images) == 0 || reqCtx.customAgent == nil || reqCtx.customAgent.Config.VLMModelID == "" {
return
}
sessionID := reqCtx.sessionID
// In normal mode, only run VLM for pure-chat path
if mode == qaModeNormal {
hasRequestKBs := len(reqCtx.knowledgeBaseIDs) > 0 || len(reqCtx.knowledgeIDs) > 0
agentWillResolveKBs := false
if !hasRequestKBs && reqCtx.customAgent != nil && !reqCtx.customAgent.Config.RetrieveKBOnlyWhenMentioned {
switch reqCtx.customAgent.Config.KBSelectionMode {
case "all":
agentWillResolveKBs = true
case "selected", "":
agentWillResolveKBs = len(reqCtx.customAgent.Config.KnowledgeBases) > 0
case "none":
agentWillResolveKBs = false
default:
agentWillResolveKBs = len(reqCtx.customAgent.Config.KnowledgeBases) > 0
}
}
if hasRequestKBs || agentWillResolveKBs || reqCtx.webSearchEnabled {
return // VLM will be handled by the pipeline rewrite step
}
}
// Emit VLM tool call/result events
toolCallID := uuid.New().String()
iteration := 0 // agent mode uses iteration field
streamCtx.eventBus.Emit(streamCtx.asyncCtx, event.Event{
Type: event.EventAgentToolCall,
SessionID: sessionID,
Data: event.AgentToolCallData{
ToolCallID: toolCallID,
ToolName: "image_analysis",
Iteration: iteration,
},
})
vlmStart := time.Now()
h.analyzeImageAttachments(streamCtx.asyncCtx, reqCtx.images,
reqCtx.customAgent.Config.VLMModelID, reqCtx.query)
outputMsg := "已分析图片内容"
if mode == qaModeAgent {
outputMsg = "已查看图片内容"
}
streamCtx.eventBus.Emit(streamCtx.asyncCtx, event.Event{
Type: event.EventAgentToolResult,
SessionID: sessionID,
Data: event.AgentToolResultData{
ToolCallID: toolCallID,
ToolName: "image_analysis",
Output: outputMsg,
Success: true,
Duration: time.Since(vlmStart).Milliseconds(),
Iteration: iteration,
},
})
}
// defaultAttachmentParseWaitTimeout bounds how long a QA turn waits for
// still-parsing attachments before proceeding with only the finished ones.
// Large or scanned documents can exceed this; raise it via
// WEKNORA_CHAT_ATTACHMENT_WAIT_TIMEOUT_SEC when needed.
const defaultAttachmentParseWaitTimeout = 60 * time.Second
// attachmentParseWaitTimeout returns the configured wait timeout, honoring the
// WEKNORA_CHAT_ATTACHMENT_WAIT_TIMEOUT_SEC override (in seconds) and falling
// back to the default when unset or invalid.
func attachmentParseWaitTimeout() time.Duration {
if raw := strings.TrimSpace(os.Getenv("WEKNORA_CHAT_ATTACHMENT_WAIT_TIMEOUT_SEC")); raw != "" {
if secs, err := strconv.Atoi(raw); err == nil && secs > 0 {
return time.Duration(secs) * time.Second
}
}
return defaultAttachmentParseWaitTimeout
}
// resolveTemporaryAttachments selects prompt content for pre-uploaded documents
// after the SSE stream is live. When any attachment is still parsing it emits a
// "attachment_parsing" timeline step and waits (bounded); unfinished attachments
// are skipped rather than blocking or failing the whole turn.
func (h *Handler) resolveTemporaryAttachments(streamCtx *sseStreamContext, reqCtx *qaRequestContext) {
if len(reqCtx.attachmentIDs) == 0 {
return
}
ctx := streamCtx.asyncCtx
sessionID := reqCtx.sessionID
// Prefer the session's tenant over gin.Context: this runs in an async
// goroutine after the HTTP handler may have returned.
tenantID := reqCtx.session.TenantID
start := time.Now()
var toolCallID string
if h.hasPendingAttachments(ctx, tenantID, sessionID, reqCtx.attachmentIDs) {
toolCallID = uuid.New().String()
streamCtx.eventBus.Emit(ctx, event.Event{
Type: event.EventAgentToolCall,
SessionID: sessionID,
Data: event.AgentToolCallData{
ToolCallID: toolCallID,
ToolName: "attachment_parsing",
Iteration: 0,
},
})
waitTimeout := attachmentParseWaitTimeout()
if reqCtx.customAgent != nil && reqCtx.customAgent.Config.AttachmentParseWaitTimeoutSec > 0 {
waitTimeout = time.Duration(reqCtx.customAgent.Config.AttachmentParseWaitTimeoutSec) * time.Second
}
h.waitForAttachments(ctx, tenantID, sessionID, reqCtx.attachmentIDs, waitTimeout)
}
readyIDs, skipped := h.partitionReadyAttachments(ctx, tenantID, sessionID, reqCtx.attachmentIDs)
var temporaryResult *types.TemporaryDocumentPromptResult
var resolveErr error
if len(readyIDs) > 0 {
temporaryResult, resolveErr = h.temporaryDocuments.ResolveForPrompt(ctx, tenantID, sessionID, readyIDs, reqCtx.query)
}
if toolCallID != "" {
output := fmt.Sprintf("已解析 %d 个附件", len(readyIDs))
if skipped > 0 {
output += fmt.Sprintf(",%d 个未完成已跳过", skipped)
}
success := resolveErr == nil
if resolveErr != nil {
output = fmt.Sprintf("附件解析失败: %v", resolveErr)
}
streamCtx.eventBus.Emit(ctx, event.Event{
Type: event.EventAgentToolResult,
SessionID: sessionID,
Data: event.AgentToolResultData{
ToolCallID: toolCallID,
ToolName: "attachment_parsing",
Output: output,
Success: success,
Duration: time.Since(start).Milliseconds(),
Iteration: 0,
Data: map[string]interface{}{
"display_type": "attachment_parsing",
"parsed_count": len(readyIDs),
"skipped_count": skipped,
},
},
})
}
if resolveErr != nil || temporaryResult == nil {
if resolveErr != nil {
logger.Warnf(ctx, "temporary attachment resolution failed for session %s: %v", sessionID, resolveErr)
}
return
}
attachments := temporaryResult.Attachments
if reqCtx.customAgent != nil && len(reqCtx.customAgent.Config.SupportedFileTypes) > 0 {
filtered := attachments[:0]
for _, att := range attachments {
ext := strings.TrimPrefix(strings.ToLower(att.FileType), ".")
if containsFileType(reqCtx.customAgent.Config.SupportedFileTypes, ext) {
filtered = append(filtered, att)
}
}
attachments = filtered
}
reqCtx.attachments = append(reqCtx.attachments, attachments...)
// Persist the freshly selected content back onto the stored user message.
// The message was created with metadata-only attachment entries (content is
// selected here, after the SSE stream is live), so without this write a
// later Agent-mode turn rebuilds history from the Attachments column and
// sees empty attachments (see buildUserHistoryMessage in agent_history.go).
h.persistResolvedAttachmentContent(ctx, reqCtx, attachments)
if reqCtx.customAgent != nil && reqCtx.customAgent.Config.ImageUploadEnabled {
for _, imageURL := range temporaryResult.ImageURLs {
reqCtx.images = append(reqCtx.images, ImageAttachment{URL: imageURL})
}
}
}
// persistResolvedAttachmentContent writes the parsed content of pre-uploaded
// attachments back onto the stored user message so multi-turn history can
// replay it. Entries are matched by their temporary-document ID; only those
// present on the message are enriched. Failures are logged but never bubble up
// — losing the write only degrades follow-up context, it must not fail the turn.
func (h *Handler) persistResolvedAttachmentContent(
ctx context.Context, reqCtx *qaRequestContext, resolved types.MessageAttachments,
) {
if reqCtx.userMessageID == "" || len(resolved) == 0 {
return
}
// Detach from the request/stream lifetime and pin the session tenant so a
// user-triggered stop (which cancels asyncCtx) does not drop the write.
updateCtx := context.WithValue(
context.WithoutCancel(ctx), types.TenantIDContextKey, reqCtx.session.TenantID,
)
msg, err := h.messageService.GetMessage(updateCtx, reqCtx.sessionID, reqCtx.userMessageID)
if err != nil || msg == nil {
logger.Warnf(updateCtx, "persist attachment content: load user message %s failed: %v",
reqCtx.userMessageID, err)
return
}
byID := make(map[string]types.MessageAttachment, len(resolved))
for _, att := range resolved {
if att.ID != "" {
byID[att.ID] = att
}
}
changed := false
for i := range msg.Attachments {
if msg.Attachments[i].ID == "" {
continue
}
if enriched, ok := byID[msg.Attachments[i].ID]; ok {
msg.Attachments[i] = enriched
changed = true
}
}
if !changed {
return
}
if err := h.messageService.UpdateMessage(updateCtx, msg); err != nil {
logger.Warnf(updateCtx, "persist attachment content: update user message %s failed: %v",
reqCtx.userMessageID, err)
}
}
// normalizeTemporaryAttachmentIDs rejects oversized ID lists before any DB
// lookup, then returns a deduplicated, order-preserving list of non-empty IDs.
func normalizeTemporaryAttachmentIDs(ids []string) ([]string, error) {
if len(ids) > types.MaxTemporaryAttachmentsPerMessage {
return nil, fmt.Errorf("a message can use at most %d attachments", types.MaxTemporaryAttachmentsPerMessage)
}
out := make([]string, 0, len(ids))
seen := make(map[string]struct{}, len(ids))
for _, id := range ids {
id = strings.TrimSpace(id)
if id == "" {
continue
}
if _, ok := seen[id]; ok {
continue
}
seen[id] = struct{}{}
out = append(out, id)
}
return out, nil
}
// hasPendingAttachments reports whether any of the given documents is still
// uploading or being parsed.
func (h *Handler) hasPendingAttachments(ctx context.Context, tenantID uint64, sessionID string, ids []string) bool {
for _, id := range ids {
doc, err := h.temporaryDocuments.Get(ctx, tenantID, sessionID, id)
if err != nil || doc == nil {
continue
}
if doc.Status == types.TemporaryDocumentStatusUploaded ||
doc.Status == types.TemporaryDocumentStatusProcessing {
return true
}
}
return false
}
// waitForAttachments polls until no attachment is pending or the timeout / ctx
// cancellation fires.
func (h *Handler) waitForAttachments(ctx context.Context, tenantID uint64, sessionID string, ids []string, timeout time.Duration) {
deadline := time.Now().Add(timeout)
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
for {
if !h.hasPendingAttachments(ctx, tenantID, sessionID, ids) || time.Now().After(deadline) {
return
}
select {
case <-ctx.Done():
return
case <-ticker.C:
}
}
}
// partitionReadyAttachments splits the ids into ready ones and a count of those
// skipped (missing, failed, or still parsing after the wait).
func (h *Handler) partitionReadyAttachments(ctx context.Context, tenantID uint64, sessionID string, ids []string) (ready []string, skipped int) {
for _, id := range ids {
doc, err := h.temporaryDocuments.Get(ctx, tenantID, sessionID, id)
if err != nil || doc == nil || doc.Status != types.TemporaryDocumentStatusReady {
skipped++
continue
}
ready = append(ready, id)
}
return ready, skipped
}
// persistLastRequestState records the input-bar state the user just sent so
// that reopening this session restores agent/model/KB/web-search/MCP picks.
// Pure UI memo — failures are logged but never bubble up; the caller runs
// this in a goroutine and is safe to discard the returned context.
func (h *Handler) persistLastRequestState(parentCtx context.Context, reqCtx *qaRequestContext, mode qaMode) {
// Detach from the HTTP request lifetime: this write must survive both
// SSE disconnects and the parent gin context being released after the
// handler returns.
ctx := logger.CloneContext(context.WithoutCancel(parentCtx))
agentEnabled := reqCtx.reqAgentEnabled
// Mirror the resolution rule used in AgentQA: a resolved custom agent's
// agent_mode wins over the request flag. For KnowledgeQA the request
// itself carries agent_enabled=false, so this collapses correctly.
if mode == qaModeAgent && reqCtx.customAgent != nil {
agentEnabled = reqCtx.customAgent.IsAgentMode()
}
state := &types.SessionLastRequestState{
AgentID: reqCtx.reqAgentID,
AgentEnabled: agentEnabled,
ModelID: reqCtx.summaryModelID,
KnowledgeBaseIDs: reqCtx.knowledgeBaseIDs,
KnowledgeIDs: reqCtx.knowledgeIDs,
TagIDs: reqCtx.tagIDs,
MCPServiceIDs: reqCtx.mcpServiceIDs,
SkillNames: reqCtx.skillNames,
MentionedItems: reqCtx.mentionedItems,
WebSearchEnabled: reqCtx.webSearchEnabled,
LocalBrowserEnabled: reqCtx.localBrowserEnabled,
}
if err := h.sessionService.UpdateSessionLastRequestState(ctx, reqCtx.sessionID, state); err != nil {
logger.Warnf(ctx, "persist last_request_state failed for session %s: %v", reqCtx.sessionID, err)
}
}
// appendQuickAnswerReasoning accumulates streamed reasoning_content from
// KnowledgeQA (fast answer) into a single AgentStep for history replay.
func appendQuickAnswerReasoning(msg *types.Message, content string) {
if content == "" {
return
}
ensureQuickAnswerStep(msg).ReasoningContent += content
}
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 06:20:18 +00:00
// completeQuickAnswerTurn finishes a KnowledgeQA (fast-answer) turn.
// EventAgentComplete must run before the GORM write: handleComplete attaches
// SandboxCheckpoint (and artifacts) to the in-memory message, and
// completeAssistantMessage is the only persist on this path.
func (h *Handler) completeQuickAnswerTurn(
ctx context.Context, streamCtx *sseStreamContext, query, userMessageID string,
) {
if streamCtx == nil || streamCtx.assistantMessage == nil {
return
}
// A stop can cancel the generation context after the final answer event
// was queued. Preserve the streamed answer just as the Agent defer does.
ctx = context.WithoutCancel(ctx)
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 06:20:18 +00:00
if streamCtx.eventBus != nil {
// MessageID is what handleComplete keys on. Leave FinalAnswer empty:
// KnowledgeQA already accumulated the answer on the message, and
// handleComplete would append FinalAnswer a second time.
_ = streamCtx.eventBus.Emit(ctx, event.Event{
Type: event.EventAgentComplete,
SessionID: streamCtx.assistantMessage.SessionID,
Data: event.AgentCompleteData{
MessageID: streamCtx.assistantMessage.ID,
},
})
}
h.completeStreamAssistantMessage(ctx, streamCtx, query, userMessageID)
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 13:01:00 +00:00
if streamCtx.releaseTurn != nil {
streamCtx.releaseTurn()
}
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 06:20:18 +00:00
}
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 14:00:02 +00:00
// sessionTenantInfoContext makes the tenant info match the session owner (the
// context's tenant here). The chat history KB is read from the tenant info,
// and a shared agent's run carries the agent workspace's: the receiver's
// conversation would be indexed into the owner's chat history KB. When the
// session tenant cannot be loaded the message is not indexed at all.
func (h *Handler) sessionTenantInfoContext(ctx context.Context) (context.Context, bool) {
tenantID, _ := types.TenantIDFromContext(ctx)
if info, ok := types.TenantInfoFromContext(ctx); ok && info != nil && info.ID == tenantID {
return ctx, true
}
if tenantID == 0 || h.tenantService == nil {
return ctx, false
}
tenant, err := h.tenantService.GetTenantByID(ctx, tenantID)
if err != nil || tenant == nil {
logger.Warnf(ctx, "Skipping chat history index: session tenant %d unavailable: %v", tenantID, err)
return ctx, false
}
return context.WithValue(ctx, types.TenantInfoContextKey, tenant), true
}
// completeStreamAssistantMessage makes output readable before notifying clients
// to perform their final image/artifact fetch. A failed write must not announce
// a successful completion whose file authorization evidence is still missing.
func (h *Handler) completeStreamAssistantMessage(
ctx context.Context, streamCtx *sseStreamContext, query, userMessageID string,
) {
if err := h.completeAssistantMessage(ctx, streamCtx.assistantMessage, query, userMessageID); err != nil {
if streamCtx.streamHandler != nil {
_ = streamCtx.streamHandler.handleError(ctx, event.Event{
ID: uuid.New().String(), Type: event.EventError, SessionID: streamCtx.assistantMessage.SessionID,
Data: event.ErrorData{Stage: "message_persistence", Error: "Failed to save assistant message"},
})
}
return
}
if streamCtx.streamHandler != nil {
if err := streamCtx.streamHandler.publishCompletion(ctx); err != nil {
logger.Errorf(ctx, "Append persisted message completion failed: %v", err)
}
}
}
// completeAssistantMessage marks an assistant message as complete, updates it,
// and asynchronously indexes the Q&A pair into the chat history knowledge base.
func (h *Handler) completeAssistantMessage(
ctx context.Context, assistantMessage *types.Message, userQuery, userMessageID string,
) error {
assistantMessage.UpdatedAt = time.Now()
assistantMessage.IsCompleted = true
if err := h.messageService.UpdateMessage(ctx, assistantMessage); err != nil {
logger.Errorf(ctx, "Failed to persist assistant message %s: %v", assistantMessage.ID, err)
return err
}
// Asynchronously index the Q&A pair into the chat history knowledge base for vector search.
// Use WithoutCancel so the goroutine survives after the HTTP request context is done.
bgCtx := context.WithoutCancel(ctx)
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 14:00:02 +00:00
if indexCtx, ok := h.sessionTenantInfoContext(bgCtx); ok {
go h.messageService.IndexMessageToKB(
indexCtx, userQuery, assistantMessage.Content, assistantMessage.ID, assistantMessage.SessionID)
}
if userQuery != "" && h.suggestionService != nil {
go func() {
if _, err := h.suggestionService.EnsureFollowUps(
bgCtx, assistantMessage.SessionID, assistantMessage.ID, false,
); err != nil {
logger.Warnf(bgCtx, "follow-up suggestion generation failed for message %s: %v", assistantMessage.ID, err)
}
}()
}
if userQuery != "" {
go h.recordTurnMemory(bgCtx, assistantMessage, userQuery, userMessageID)
}
return nil
}
// recordTurnMemory runs the long-term memory write path for a finished turn.
//
// This is the single place a conversation can produce memory, and it sits at
// the point where both the RAG and the Agent path converge, so neither mode
// can silently miss it. A stopped conversation arrives with an empty query and
// is skipped by the caller.
func (h *Handler) recordTurnMemory(
ctx context.Context, assistantMessage *types.Message, userQuery, userMessageID string,
) {
if h.memoryService == nil {
return
}
// An explicit "remember ..." directive is stored verbatim and immediately,
// with no model in the loop. This is what makes the default explicit_only
// mode useful rather than merely safe.
if statement, ok := types.DetectExplicitMemory(userQuery); ok {
if _, err := h.memoryService.Remember(ctx, types.MemoryItem{
Kind: types.MemoryKindFact,
Content: statement,
Importance: 4,
Origin: types.MemoryOriginExplicit,
SourceSessionID: assistantMessage.SessionID,
// Attribute to the user's own message, not the answer. Background
// distillation reads that same message, so the two paths must
// agree on provenance or a memory deleted from one can be
// re-derived by the other.
SourceMessageID: userMessageID,
}); err != nil {
logger.Warnf(ctx, "memory: explicit remember failed for message %s: %v", assistantMessage.ID, err)
}
}
h.recordAnswerSources(ctx, assistantMessage)
h.memoryService.ScheduleExtraction(ctx, assistantMessage.SessionID, assistantMessage.ID, assistantMessage.ModelID)
}
// recordAnswerSources notes which documents this answer drew on, so the
// reranker can prefer the material this person keeps working from.
//
// The references attached to an answer are a weaker signal than an explicit
// thumbs-up: they say the retriever kept picking a document, not that the user
// found it useful. They are, however, the only per-person retrieval signal
// available without asking for anything, and the boost they earn is capped
// accordingly.
func (h *Handler) recordAnswerSources(ctx context.Context, assistantMessage *types.Message) {
if len(assistantMessage.KnowledgeReferences) == 0 {
return
}
seen := make(map[string]struct{}, len(assistantMessage.KnowledgeReferences))
refs := make([]types.MemoryDocAffinity, 0, len(assistantMessage.KnowledgeReferences))
for _, ref := range assistantMessage.KnowledgeReferences {
if ref.KnowledgeID == "" {
continue
}
if _, dup := seen[ref.KnowledgeID]; dup {
continue
}
seen[ref.KnowledgeID] = struct{}{}
refs = append(refs, types.MemoryDocAffinity{
KnowledgeID: ref.KnowledgeID,
KnowledgeBaseID: ref.KnowledgeBaseID,
Title: ref.KnowledgeTitle,
})
}
h.memoryService.RecordAnswerSources(ctx, refs)
}