From 277d6ee851c1891d00c0c6596669d16e443bcde1 Mon Sep 17 00:00:00 2001 From: nullptr-error <104547331+nullptr-error@users.noreply.github.com> Date: Tue, 8 Sep 2026 17:43:15 +0800 Subject: [PATCH] feat(sandbox): add an interactive terminal and files tab beside chat (#3110) * feat(sandbox): stream interactive PTYs from Cube and E2B Give session sandboxes a provider-neutral terminal capability so a later WebSocket layer can attach without knowing Cube vs E2B. Long-lived streams use a timeout-free client; idle terminals keep the sandbox alive by refreshing TTL, and a workspace can set how long to wait before disconnect. * feat(session): bridge browser terminals to the session sandbox Mint a short-lived ticket over a normal authenticated POST so the browser WebSocket never puts the access JWT in the query string. After upgrade, recheck the bound token, membership, and session ownership so logout or revocation tears the PTY down. Provisioning stays opt-in: a GET handshake only creates a sandbox when the client sends provision=1. * feat(chat): add a sandbox terminal panel beside the conversation Open a side panel with an xterm attached to the session sandbox. Starting the terminal is an explicit click so merely opening the panel does not create or resume a microVM; reconnects stay lookup-only until the user confirms create-and-start. Persist the remote shell PID in sessionStorage so a refresh reattaches instead of spawning an orphan. * feat(sandbox): let workspaces set terminal idle disconnect Expose the idle-disconnect duration in the sandbox config editor so an operator can close unused terminals and let the provider TTL pause the sandbox, instead of leaving PTYs open for the built-in 15 minutes. * feat(chat): show generated files in the sandbox side panel Move the per-message artifact list into the first tab of the right-hand panel so generated files stay in view with the terminal. Keep the old drawer only for embedded chat. * fix(sandbox-terminal): keep tickets out of logs and live PTYs across refresh Gin was copying the handshake JWT into response_body logs, silent access-token rotation dropped open terminals as AUTH_REVOKED, and first-use provisioning missed shared agents. Local echo now skips password prompts. --------- Co-authored-by: hailongzhao Co-authored-by: wizardchen --- frontend/Dockerfile | 1 + frontend/nginx-http.conf | 8 + frontend/nginx.conf | 19 + frontend/package-lock.json | 17 + frontend/package.json | 2 + frontend/src/api/system/index.ts | 1 + .../components/SandboxConfigEditorDrawer.vue | 8 + .../components/chat/SandboxSidePanel.test.mjs | 17 + .../src/components/chat/SandboxSidePanel.vue | 362 ++++++++++++++ .../src/composables/useChatSandboxPanel.ts | 95 ++++ .../src/composables/useSandboxTerminal.ts | 382 +++++++++++++++ frontend/src/i18n/locales/en-US.ts | 23 + frontend/src/i18n/locales/ja-JP.ts | 23 + frontend/src/i18n/locales/ko-KR.ts | 23 + frontend/src/i18n/locales/ru-RU.ts | 23 + frontend/src/i18n/locales/zh-CN.ts | 23 + frontend/src/utils/ptyEchoPredictor.test.ts | 89 ++++ frontend/src/utils/ptyEchoPredictor.ts | 123 +++++ frontend/src/utils/sandboxArtifactRefs.ts | 2 +- frontend/src/utils/sandboxPtyId.test.ts | 44 ++ frontend/src/utils/sandboxPtyId.ts | 43 ++ frontend/src/utils/sessionArtifacts.test.ts | 66 +++ frontend/src/utils/sessionArtifacts.ts | 64 +++ .../chat/components/AgentStreamDisplay.vue | 17 +- .../chat/components/ChatArtifactsPanel.vue | 445 ++++++++++++++++++ .../views/chat/components/SandboxTerminal.vue | 344 ++++++++++++++ .../answerToolbarCompletion.test.mjs | 7 + frontend/src/views/chat/components/botmsg.vue | 23 +- frontend/src/views/chat/index.vue | 108 ++++- frontend/vite.config.ts | 4 + internal/application/repository/user.go | 12 + .../service/sandbox_terminal_auth.go | 188 ++++++++ .../service/sandbox_terminal_auth_test.go | 283 +++++++++++ .../service/sandbox_terminal_service.go | 256 ++++++++++ .../service/sandbox_terminal_service_test.go | 26 + .../service/sandbox_terminal_ticket.go | 92 ++++ .../service/sandbox_terminal_ticket_test.go | 79 ++++ .../application/service/tenant_member_test.go | 3 + internal/application/service/user.go | 44 ++ .../service/user_auth_token_test.go | 59 +++ internal/container/container.go | 5 + internal/handler/session/handler.go | 15 + .../handler/session/resolve_agent_test.go | 33 ++ .../session/sandbox_terminal_bridge.go | 340 +++++++++++++ .../session/sandbox_terminal_bridge_test.go | 150 ++++++ .../session/sandbox_terminal_idle_test.go | 50 ++ .../handler/session/sandbox_terminal_ws.go | 422 +++++++++++++++++ internal/middleware/logger.go | 16 +- internal/middleware/logger_test.go | 25 +- internal/middleware/ws_auth.go | 47 ++ internal/router/router.go | 6 + internal/router/routes_chat.go | 18 + internal/sandbox/capabilities.go | 21 + internal/sandbox/cube_mock_test.go | 95 ++++ internal/sandbox/cube_remote_client.go | 7 +- internal/sandbox/cube_remote_client_test.go | 1 + internal/sandbox/cube_terminal.go | 183 +++++++ internal/sandbox/cube_terminal_test.go | 176 +++++++ internal/sandbox/e2b_remote_client.go | 2 + internal/sandbox/e2b_remote_client_test.go | 1 + internal/sandbox/e2b_terminal.go | 208 ++++++++ internal/sandbox/langfuse.go | 28 ++ internal/sandbox/langfuse_test.go | 45 ++ internal/sandbox/pty_input_coalesce.go | 96 ++++ internal/sandbox/pty_input_coalesce_test.go | 70 +++ internal/sandbox/remote_client.go | 6 + internal/sandbox/sandbox.go | 15 + internal/sandbox/session_manager.go | 50 ++ internal/sandbox/session_manager_test.go | 11 + internal/sandbox/tenant_config.go | 6 + internal/sandbox/tenant_config_test.go | 12 + internal/sandbox/terminal.go | 277 +++++++++++ internal/sandbox/terminal_test.go | 39 ++ internal/sandbox/terminal_ttl_test.go | 52 ++ internal/types/interfaces/user.go | 9 + internal/types/tenant.go | 6 + 76 files changed, 5967 insertions(+), 24 deletions(-) create mode 100644 frontend/nginx-http.conf create mode 100644 frontend/src/components/chat/SandboxSidePanel.test.mjs create mode 100644 frontend/src/components/chat/SandboxSidePanel.vue create mode 100644 frontend/src/composables/useChatSandboxPanel.ts create mode 100644 frontend/src/composables/useSandboxTerminal.ts create mode 100644 frontend/src/utils/ptyEchoPredictor.test.ts create mode 100644 frontend/src/utils/ptyEchoPredictor.ts create mode 100644 frontend/src/utils/sandboxPtyId.test.ts create mode 100644 frontend/src/utils/sandboxPtyId.ts create mode 100644 frontend/src/utils/sessionArtifacts.test.ts create mode 100644 frontend/src/utils/sessionArtifacts.ts create mode 100644 frontend/src/views/chat/components/ChatArtifactsPanel.vue create mode 100644 frontend/src/views/chat/components/SandboxTerminal.vue create mode 100644 internal/application/service/sandbox_terminal_auth.go create mode 100644 internal/application/service/sandbox_terminal_auth_test.go create mode 100644 internal/application/service/sandbox_terminal_service.go create mode 100644 internal/application/service/sandbox_terminal_service_test.go create mode 100644 internal/application/service/sandbox_terminal_ticket.go create mode 100644 internal/application/service/sandbox_terminal_ticket_test.go create mode 100644 internal/handler/session/sandbox_terminal_bridge.go create mode 100644 internal/handler/session/sandbox_terminal_bridge_test.go create mode 100644 internal/handler/session/sandbox_terminal_idle_test.go create mode 100644 internal/handler/session/sandbox_terminal_ws.go create mode 100644 internal/middleware/ws_auth.go create mode 100644 internal/sandbox/cube_terminal.go create mode 100644 internal/sandbox/cube_terminal_test.go create mode 100644 internal/sandbox/e2b_terminal.go create mode 100644 internal/sandbox/pty_input_coalesce.go create mode 100644 internal/sandbox/pty_input_coalesce_test.go create mode 100644 internal/sandbox/terminal.go create mode 100644 internal/sandbox/terminal_test.go create mode 100644 internal/sandbox/terminal_ttl_test.go diff --git a/frontend/Dockerfile b/frontend/Dockerfile index 2aa94eab..342ba7e3 100644 --- a/frontend/Dockerfile +++ b/frontend/Dockerfile @@ -66,6 +66,7 @@ COPY nginx.conf /etc/nginx/templates/default.conf.template # Copied outside templates/ on purpose: envsubst would eat $host and the other # nginx variables in it. COPY nginx-api-proxy.conf /etc/nginx/api-proxy.conf +COPY nginx-http.conf /etc/nginx/conf.d/00-weknora-http.conf COPY docker-entrypoint.sh /docker-entrypoint.sh RUN chmod +x /docker-entrypoint.sh diff --git a/frontend/nginx-http.conf b/frontend/nginx-http.conf new file mode 100644 index 00000000..1134d9f2 --- /dev/null +++ b/frontend/nginx-http.conf @@ -0,0 +1,8 @@ +# HTTP-context nginx snippets for the frontend image. +# Included from conf.d (http {}), not from the server template. + +# $uri is the path without the query string, so handshake tickets (and any +# leftover secrets) never land in access logs. +log_format api_no_query '$remote_addr - $remote_user [$time_local] ' + '"$request_method $uri $server_protocol" $status ' + '$body_bytes_sent "$http_referer" "$http_user_agent"'; diff --git a/frontend/nginx.conf b/frontend/nginx.conf index a086c655..6224f5ae 100644 --- a/frontend/nginx.conf +++ b/frontend/nginx.conf @@ -112,6 +112,25 @@ server { proxy_set_header X-Forwarded-Proto $scheme; } + # Interactive sandbox terminal: WebSocket upgrade + query-stripped logs + # (the handshake carries a short-lived ticket in the query string). + location ~ ^/api/v1/sessions/[^/]+/sandbox/terminal$ { + proxy_pass ${APP_SCHEME}://${APP_HOST}:${APP_PORT}; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_read_timeout 3600s; + proxy_send_timeout 3600s; + proxy_buffering off; + proxy_cache off; + proxy_request_buffering off; + access_log /var/log/nginx/access.log api_no_query; + } + # 技能 zip 上传的两条集合路由,body 上限放宽到 MAX_SKILL_BUNDLE_SIZE。 # 单独成一个 location 而不是抬高全站上限:client_max_body_size 是按 # location 生效的,写在 server 级会让知识库上传等端点也能收到技能包大小的 diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 4c467ea7..d618f470 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -12,6 +12,8 @@ "@types/dompurify": "^3.2.0", "@types/papaparse": "^5.5.2", "@vue-office/pptx": "^1.0.1", + "@xterm/addon-fit": "^0.10.0", + "@xterm/xterm": "^5.5.0", "axios": "^1.16.0", "docx-preview": "^0.3.7", "dompurify": "^3.4.11", @@ -2329,6 +2331,21 @@ "@xtuc/long": "4.2.2" } }, + "node_modules/@xterm/addon-fit": { + "version": "0.10.0", + "resolved": "https://mirrors.tencent.com/npm/@xterm/addon-fit/-/addon-fit-0.10.0.tgz", + "integrity": "sha512-UFYkDm4HUahf2lnEyHvio51TNGiLK66mqP2JoATy7hRZeXaGMRDr00JiSF7m63vR5WKATF605yEggJKsw0JpMQ==", + "license": "MIT", + "peerDependencies": { + "@xterm/xterm": "^5.0.0" + } + }, + "node_modules/@xterm/xterm": { + "version": "5.5.0", + "resolved": "https://mirrors.tencent.com/npm/@xterm/xterm/-/xterm-5.5.0.tgz", + "integrity": "sha512-hqJHYaQb5OptNunnyAnkHyM8aCjZ1MEIDTQu1iIbbTD/xops91NB5yq1ZK/dC2JDbVWtF23zUtl9JE2NqwT87A==", + "license": "MIT" + }, "node_modules/@xtuc/ieee754": { "version": "1.2.0", "resolved": "https://mirrors.tencent.com/npm/@xtuc/ieee754/-/ieee754-1.2.0.tgz", diff --git a/frontend/package.json b/frontend/package.json index 954eba56..9cac8cf9 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -20,6 +20,8 @@ "@types/dompurify": "^3.2.0", "@types/papaparse": "^5.5.2", "@vue-office/pptx": "^1.0.1", + "@xterm/addon-fit": "^0.10.0", + "@xterm/xterm": "^5.5.0", "axios": "^1.16.0", "docx-preview": "^0.3.7", "dompurify": "^3.4.11", diff --git a/frontend/src/api/system/index.ts b/frontend/src/api/system/index.ts index 7cc0c6e9..528e1444 100644 --- a/frontend/src/api/system/index.ts +++ b/frontend/src/api/system/index.ts @@ -770,6 +770,7 @@ export interface SandboxSkillImage { export interface SandboxConfig { sandbox_type?: string default_timeout_sec?: number + terminal_idle_disconnect_sec?: number allow_private_endpoints?: boolean env_vars?: Record volume_mount?: SandboxVolumeMountConfig diff --git a/frontend/src/components/SandboxConfigEditorDrawer.vue b/frontend/src/components/SandboxConfigEditorDrawer.vue index 88d5c736..660bef87 100644 --- a/frontend/src/components/SandboxConfigEditorDrawer.vue +++ b/frontend/src/components/SandboxConfigEditorDrawer.vue @@ -421,6 +421,11 @@ :tips="$t('settings.sandbox.defaultTimeoutHelp')"> + + + @@ -817,6 +822,7 @@ const backend = ref('') // undefined rather than 0 so the input renders empty and shows its placeholder, // matching the HTTP timeout / TTL fields. A literal 0 would read as a real value. const defaultTimeoutSec = ref(undefined) +const terminalIdleDisconnectSec = ref(undefined) const allowPrivateEndpoints = ref(false) const cube = reactive({}) const e2b = reactive({}) @@ -1121,6 +1127,7 @@ function reset() { ? cfg.sandbox_type! : defaultBackendType() defaultTimeoutSec.value = cfg.default_timeout_sec || undefined + terminalIdleDisconnectSec.value = cfg.terminal_idle_disconnect_sec || undefined allowPrivateEndpoints.value = cfg.allow_private_endpoints === true // Replace rather than merge: a reused reactive object would otherwise carry // the previously edited config's fields into the next one opened. @@ -1459,6 +1466,7 @@ function collectPayload(): SandboxConfig { const payload: SandboxConfig = { sandbox_type: backend.value, default_timeout_sec: defaultTimeoutSec.value || undefined, + terminal_idle_disconnect_sec: terminalIdleDisconnectSec.value || undefined, allow_private_endpoints: allowPrivateEndpoints.value || undefined, env_vars: envVars, skill_rollout: skillRollout.value, diff --git a/frontend/src/components/chat/SandboxSidePanel.test.mjs b/frontend/src/components/chat/SandboxSidePanel.test.mjs new file mode 100644 index 00000000..672239c6 --- /dev/null +++ b/frontend/src/components/chat/SandboxSidePanel.test.mjs @@ -0,0 +1,17 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { readFileSync } from 'node:fs' + +const panel = readFileSync(new URL('./SandboxSidePanel.vue', import.meta.url), 'utf8') + +test('artifacts is the first sandbox panel tab', () => { + const artifacts = panel.indexOf("id: 'artifacts' as SandboxPanelTab") + const terminal = panel.indexOf("id: 'terminal' as SandboxPanelTab") + const desktop = panel.indexOf("id: 'desktop' as SandboxPanelTab") + assert.notEqual(artifacts, -1) + assert.ok(artifacts < terminal) + assert.ok(terminal < desktop) + assert.match(panel, / + + + + + + + + diff --git a/frontend/src/composables/useChatSandboxPanel.ts b/frontend/src/composables/useChatSandboxPanel.ts new file mode 100644 index 00000000..9c313a49 --- /dev/null +++ b/frontend/src/composables/useChatSandboxPanel.ts @@ -0,0 +1,95 @@ +import { inject, provide, ref, type InjectionKey, type Ref } from 'vue' + +export type SandboxPanelTab = 'artifacts' | 'terminal' | 'desktop' + +export type ArtifactPanelFocus = { + messageId: string + previewIndex?: number | null +} + +export type ArtifactPanelFocusState = ArtifactPanelFocus & { + nonce: number +} + +// 面板宽度可拖拽调整,持久化到 localStorage。 +export const SANDBOX_PANEL_MIN_WIDTH = 320 +export const SANDBOX_PANEL_MAX_WIDTH = 1200 +export const SANDBOX_PANEL_DEFAULT_WIDTH = 420 + +function clampPanelWidth(width: number): number { + if (typeof window === 'undefined') return SANDBOX_PANEL_DEFAULT_WIDTH + const viewportCap = Math.max(SANDBOX_PANEL_MIN_WIDTH, window.innerWidth - 480) + return Math.min( + SANDBOX_PANEL_MAX_WIDTH, + viewportCap, + Math.max(SANDBOX_PANEL_MIN_WIDTH, Math.round(width)), + ) +} + +function initialPanelWidth(): number { + const raw = Number(localStorage.getItem('sandbox_panel_width')) + return Number.isFinite(raw) && raw > 0 ? clampPanelWidth(raw) : SANDBOX_PANEL_DEFAULT_WIDTH +} + +export type ChatSandboxPanelContext = { + visible: Ref + activeTab: Ref + width: Ref + setWidth: (width: number) => void + artifactFocus: Ref + open: (tab?: SandboxPanelTab, focus?: ArtifactPanelFocus) => void + close: () => void + clearArtifactFocus: () => void +} + +const CHAT_SANDBOX_PANEL_KEY: InjectionKey = Symbol( + 'chatSandboxPanel', +) + +export function provideChatSandboxPanel(): ChatSandboxPanelContext { + const visible = ref(false) + const activeTab = ref('artifacts') + const width = ref(initialPanelWidth()) + const artifactFocus = ref(null) + let focusNonce = 0 + + const setWidth = (next: number) => { + width.value = clampPanelWidth(next) + localStorage.setItem('sandbox_panel_width', String(width.value)) + } + + const open = (tab?: SandboxPanelTab, focus?: ArtifactPanelFocus) => { + if (tab) activeTab.value = tab + if (focus) { + artifactFocus.value = { ...focus, nonce: ++focusNonce } + } + visible.value = true + } + + const close = () => { + visible.value = false + artifactFocus.value = null + } + + const clearArtifactFocus = () => { + artifactFocus.value = null + } + + const ctx: ChatSandboxPanelContext = { + visible, + activeTab, + width, + setWidth, + artifactFocus, + open, + close, + clearArtifactFocus, + } + + provide(CHAT_SANDBOX_PANEL_KEY, ctx) + return ctx +} + +export function useChatSandboxPanel(): ChatSandboxPanelContext | null { + return inject(CHAT_SANDBOX_PANEL_KEY, null) +} diff --git a/frontend/src/composables/useSandboxTerminal.ts b/frontend/src/composables/useSandboxTerminal.ts new file mode 100644 index 00000000..31fc1f57 --- /dev/null +++ b/frontend/src/composables/useSandboxTerminal.ts @@ -0,0 +1,382 @@ +import { onUnmounted, ref, type Ref } from 'vue' +import { post } from '@/utils/request' +import { readStoredPtyId, writeStoredPtyId } from '@/utils/sandboxPtyId' + +export type SandboxTerminalStatus = + /** 尚未连接:打开面板不会碰后端,等用户显式启动。 */ + | 'not_started' + | 'connecting' + | 'ready' + /** 查到会话没有运行中的沙箱;创建需要用户确认。 */ + | 'needs_provision' + | 'exited' + /** 用户已确认创建,但后端无处可建(智能体没配沙箱后端)。 */ + | 'no_sandbox' + | 'unsupported' + | 'idle' + | 'unauthorized' + | 'error' + +export type SandboxTerminalControlFrame = { + type: string + code?: string + message?: string + pty_id?: number + backend?: string + exit_code?: number | null + cols?: number + rows?: number +} + +const RECONNECT_BASE_DELAY_MS = 1000 +const RECONNECT_MAX_DELAY_MS = 30000 +const APP_PING_INTERVAL_MS = 25000 +const PENDING_OUTPUT_MAX_BYTES = 1024 * 1024 +// 服务端对单个输入帧设了 4 KiB 上限(terminalMaxInputBytes);gorilla 超限时 +// 直接关闭连接,而 xterm 的 paste 是整段进 onData 的,粘一段脚本就会掉线。 +// 按字节切片后再发:PTY 是字节流,切在多字节字符中间也会被原样按序重组。 +const INPUT_FRAME_MAX_BYTES = 2048 + +function resolveWsBase(): string { + const base = (import.meta.env.BASE_URL || '/').replace(/\/+$/, '') + const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws' + return `${protocol}://${window.location.host}${base}` +} + +async function mintTerminalTicket(sessionId: string): Promise { + const res = await post<{ success?: boolean; data?: { ticket?: string } }>( + `/api/v1/sessions/${encodeURIComponent(sessionId)}/sandbox/terminal-ticket`, + {}, + ) + const ticket = res?.data?.ticket + if (!ticket) { + throw new Error('missing terminal ticket') + } + return ticket +} + +/** + * provisionAttempted 决定 SANDBOX_NOT_BOUND 的含义:没带创建意图时只是"还没 + * 有沙箱,要不要建一个",带了还失败才是真的无处可建。 + */ +function statusFromErrorCode( + code: string | undefined, + provisionAttempted: boolean, +): SandboxTerminalStatus { + if (code === 'SANDBOX_NOT_BOUND') { + return provisionAttempted ? 'no_sandbox' : 'needs_provision' + } + if (code === 'TERMINAL_UNSUPPORTED') return 'unsupported' + if (code === 'IDLE_DISCONNECTED') return 'idle' + if (code === 'AUTH_REVOKED') return 'unauthorized' + return 'error' +} + +export type SandboxTerminalSession = { + status: Ref + /** + * 由 SandboxTerminal.vue 注入:PTY 输出写入 xterm。 + * 在 handler 注册前到达的二进制帧会先入队,避免 bash 提示符在 xterm + * 挂载前被丢弃。传入 null 可在卸载时重新开始缓冲。 + */ + onOutput: (handler: ((data: Uint8Array) => void) | null) => void + /** + * 连接并打开终端;已在连接中时幂等。 + * + * provision 表示"这是用户的显式动作,允许后端创建或重建沙箱"。只有点击 + * 按钮才应该传 true:创建沙箱是要计费的真实基础设施,不能是打开面板的副 + * 作用。自动重连一律不带,查不到沙箱就退回让用户确认。 + */ + connect: (options?: { provision?: boolean }) => void + /** 发送键盘输入(xterm onData 的原始字符串)。 */ + sendInput: (data: string) => void + /** 同步终端尺寸;ready 后调用。 */ + resize: (cols: number, rows: number) => void + /** 断开并停止重连(组件卸载 / 会话切换时调用)。 */ + dispose: () => void +} + +/** + * 三个参数都必须是活的 ref(`toRef(props, …)`),不能是 `ref(props.x)` 那样的 + * 快照:每次 openSocket 都会重读它们,用户切换 agent(含共享来源空间)后的 + * 下一次连接才能按新 agent 的沙箱配置去创建沙箱。 + */ +export function useSandboxTerminal( + sessionId: Ref, + agentId: Ref, + agentSourceTenantId: Ref = ref(undefined), +): SandboxTerminalSession { + const status = ref('not_started') + + let ws: WebSocket | null = null + let opening = false + let outputHandler: ((data: Uint8Array) => void) | null = null + let pendingOutput: Uint8Array[] = [] + let pendingOutputBytes = 0 + let disposed = false + let reconnectAttempt = 0 + let reconnectTimer: ReturnType | null = null + let pingTimer: ReturnType | null = null + let pendingResize: { cols: number; rows: number } | null = null + // 刷新 / 关面板会拆掉这个闭包;PID 写在 sessionStorage,重挂时才能带 pty_id。 + let lastPid: number | null = readStoredPtyId(sessionId.value) + // 当前这次连接是否带创建意图。只由 connect({ provision: true }) 置真。 + let allowProvision = false + + const textEncoder = new TextEncoder() + + function rememberPid(next: number | null) { + lastPid = next + writeStoredPtyId(sessionId.value, next) + } + + function clearReconnectTimer() { + if (reconnectTimer !== null) { + clearTimeout(reconnectTimer) + reconnectTimer = null + } + } + + function clearPingTimer() { + if (pingTimer !== null) { + clearInterval(pingTimer) + pingTimer = null + } + } + + function scheduleReconnect() { + if (disposed) return + clearReconnectTimer() + // 自动重连不得复活已被回收的沙箱:只有用户点击才携带创建意图。掉线期间 + // 沙箱如果被回收,重连会拿到 needs_provision,由用户决定是否重建。 + allowProvision = false + const delay = Math.min( + RECONNECT_BASE_DELAY_MS * 2 ** reconnectAttempt, + RECONNECT_MAX_DELAY_MS, + ) + reconnectAttempt += 1 + reconnectTimer = setTimeout(() => { + reconnectTimer = null + void openSocket() + }, delay) + } + + async function openSocket() { + if (disposed || opening || ws) return + const sid = sessionId.value + if (!sid) return + + opening = true + status.value = 'connecting' + try { + const ticket = await mintTerminalTicket(sid) + if (disposed) return + const query = new URLSearchParams({ ticket }) + if (allowProvision) { + query.set('provision', '1') + // agent_id 只在允许创建时才有意义:它是首次创建沙箱所用的配置来源。 + const agent = agentId.value + if (agent && agent !== 'builtin-quick-answer') { + query.set('agent_id', agent) + } + const sourceTenant = agentSourceTenantId.value + if (sourceTenant != null && String(sourceTenant).trim() !== '') { + query.set('agent_source_tenant_id', String(sourceTenant).trim()) + } + } + if (lastPid && lastPid > 0) { + query.set('pty_id', String(lastPid)) + } + const socket = new WebSocket( + `${resolveWsBase()}/api/v1/sessions/${encodeURIComponent(sid)}/sandbox/terminal?${query.toString()}`, + ) + if (disposed) { + socket.close() + return + } + ws = socket + } catch { + ws = null + if (disposed) return + status.value = 'error' + scheduleReconnect() + return + } finally { + opening = false + } + if (!ws) return + ws.binaryType = 'arraybuffer' + + ws.onopen = () => { + clearPingTimer() + pingTimer = setInterval(() => { + if (ws && ws.readyState === WebSocket.OPEN) { + ws.send(JSON.stringify({ type: 'ping' })) + } + }, APP_PING_INTERVAL_MS) + } + + ws.onmessage = (event) => { + if (typeof event.data === 'string') { + handleControlFrame(event.data) + return + } + const data = + event.data instanceof ArrayBuffer ? new Uint8Array(event.data) : new Uint8Array(0) + deliverOutput(data) + } + + ws.onclose = (event) => { + clearPingTimer() + ws = null + if (disposed) return + const reason = typeof event.reason === 'string' ? event.reason : '' + if ( + event.code === 1008 + || reason === 'SANDBOX_NOT_BOUND' + || reason === 'TERMINAL_UNSUPPORTED' + || reason === 'IDLE_DISCONNECTED' + || reason === 'AUTH_REVOKED' + ) { + if (reason) { + status.value = statusFromErrorCode(reason, allowProvision) + } else if (status.value === 'ready' || status.value === 'connecting') { + status.value = 'error' + } + // idle / unauthorized:shell 还在沙箱里,PID 必须留下才能重挂。 + // 沙箱没了或后端不支持:PID 已无效,清掉以免下次 Create 撞上死进程。 + if (status.value !== 'idle' && status.value !== 'unauthorized') { + rememberPid(null) + } + return + } + if ( + status.value !== 'needs_provision' + && status.value !== 'no_sandbox' + && status.value !== 'unsupported' + && status.value !== 'exited' + && status.value !== 'idle' + && status.value !== 'unauthorized' + ) { + status.value = 'error' + scheduleReconnect() + } + } + + ws.onerror = () => { + // onclose 会随后触发,统一在那里处理。 + } + } + + function handleControlFrame(raw: string) { + let frame: SandboxTerminalControlFrame + try { + frame = JSON.parse(raw) + } catch { + return + } + switch (frame.type) { + case 'ready': + status.value = 'ready' + rememberPid(typeof frame.pty_id === 'number' ? frame.pty_id : null) + reconnectAttempt = 0 + // 创建意图到此为止。它只用来解释 SANDBOX_NOT_BOUND:连上之前是"还没 + // 有沙箱,要不要建",连上之后再收到就一定是"沙箱被回收了"。不复位会 + // 把回收误判成 no_sandbox("智能体没配后端"),文案和真实原因无关。 + allowProvision = false + if (pendingResize) { + sendResize(pendingResize.cols, pendingResize.rows) + pendingResize = null + } + break + case 'exited': { + status.value = 'exited' + rememberPid(null) + break + } + case 'error': { + status.value = statusFromErrorCode(frame.code, allowProvision) + if (status.value !== 'idle' && status.value !== 'unauthorized') { + rememberPid(null) + } + break + } + default: + break + } + } + + function deliverOutput(data: Uint8Array) { + if (data.length === 0) return + if (outputHandler) { + outputHandler(data) + return + } + pendingOutput.push(data) + pendingOutputBytes += data.length + while (pendingOutputBytes > PENDING_OUTPUT_MAX_BYTES && pendingOutput.length > 0) { + const dropped = pendingOutput.shift() + if (dropped) pendingOutputBytes -= dropped.length + } + } + + function sendRaw(frame: SandboxTerminalControlFrame) { + ws?.send(JSON.stringify(frame)) + } + + function sendResize(cols: number, rows: number) { + if (!ws || ws.readyState !== WebSocket.OPEN) { + pendingResize = { cols, rows } + return + } + sendRaw({ type: 'resize', cols, rows }) + } + + const session: SandboxTerminalSession = { + status, + onOutput(handler) { + outputHandler = handler + if (!handler) return + const queued = pendingOutput + pendingOutput = [] + pendingOutputBytes = 0 + for (const chunk of queued) { + handler(chunk) + } + }, + connect(options) { + if (disposed || ws || opening) return + // 丢掉待触发的自动重连,否则它稍后会带着 provision=false 再拨一次, + // 和用户这次点击抢连接。 + clearReconnectTimer() + allowProvision = options?.provision === true + reconnectAttempt = 0 + void openSocket() + }, + sendInput(data) { + if (!ws || ws.readyState !== WebSocket.OPEN) return + const bytes = textEncoder.encode(data) + for (let offset = 0; offset < bytes.length; offset += INPUT_FRAME_MAX_BYTES) { + ws.send(bytes.subarray(offset, offset + INPUT_FRAME_MAX_BYTES)) + } + }, + resize: sendResize, + dispose() { + disposed = true + clearReconnectTimer() + clearPingTimer() + if (ws) { + const socket = ws + ws = null + socket.onclose = null + socket.onerror = null + socket.onmessage = null + socket.close() + } + }, + } + + onUnmounted(() => session.dispose()) + + return session +} diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index c2829cbc..bb8cc49e 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -29,6 +29,7 @@ export default { }, chatHeader: { moreActions: 'More conversation actions', + toggleSandboxPanel: 'Sandbox terminal', copySessionId: 'Copy Session ID', copyLink: 'Copy Conversation Link', copyMarkdown: 'Copy as Markdown', @@ -1321,6 +1322,8 @@ export default { dockerNetworkNone: 'none (no egress)', defaultTimeout: 'Execution timeout (s)', defaultTimeoutHelp: 'Longest a single skill script may run before it is killed. Empty means 60 seconds.', + terminalIdleDisconnect: 'Terminal idle disconnect (s)', + terminalIdleDisconnectHelp: 'After the terminal is open, close it if there is no keyboard input or PTY output for this long so the sandbox can pause on its TTL. Empty means 900 seconds; minimum 60 seconds, maximum 24 hours.', envVars: 'Environment variables', envKey: 'Name', envValue: 'Value', @@ -3387,6 +3390,26 @@ export default { referencesDrawerDocsSection: 'Documents', referencesDrawerToolsSection: 'Tools', referencesDrawerEmpty: 'No sources available', + sandbox: { + panelTitle: 'Sandbox', + tabArtifacts: 'Files', + tabTerminal: 'Terminal', + tabDesktop: 'Desktop', + artifactsEmpty: 'No generated files in this conversation yet.', + desktopPlaceholder: 'Desktop visualization coming soon', + notStarted: 'The terminal is not running yet. Starting it connects to this conversation\'s sandbox, creating or resuming one if none is available.', + start: 'Start terminal', + connecting: 'Connecting to sandbox…', + needsProvision: 'This conversation has no running sandbox. Creating one starts a new sandbox, billed according to your workspace configuration.', + createAndStart: 'Create and start', + noSandbox: 'No sandbox yet, and the current agent has no sandbox backend configured, so there is nowhere to create one. Switch to an agent with a sandbox configured, or send a message that runs code.', + unsupported: 'The current sandbox backend does not support interactive terminals', + disconnected: 'Connection lost', + retry: 'Reconnect', + sessionEnded: 'Terminal session ended', + idleDisconnected: 'The terminal disconnected after being idle. The sandbox will pause on its own TTL. You can reconnect.', + authRevoked: 'Your session is no longer valid, so the terminal was disconnected. Sign in again, then reconnect.', + }, questionMinimapTitle: 'Q&A', questionMinimapAriaLabel: 'Question outline', questionMinimapAttachmentPlaceholder: '(Attachment)', diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts index 8ee9aff5..06f817b5 100644 --- a/frontend/src/i18n/locales/ja-JP.ts +++ b/frontend/src/i18n/locales/ja-JP.ts @@ -29,6 +29,7 @@ export default { }, chatHeader: { moreActions: 'その他の会話操作', + toggleSandboxPanel: 'サンドボックスターミナル', copySessionId: 'セッションIDをコピー', copyLink: '会話リンクをコピー', copyMarkdown: 'Markdownとしてコピー', @@ -1321,6 +1322,8 @@ export default { dockerNetworkNone: 'none(外向き通信なし)', defaultTimeout: '実行タイムアウト(秒)', defaultTimeoutHelp: 'スキルスクリプト1回あたりの最長実行時間です。これを超えると強制終了されます。空欄の場合は60秒です。', + terminalIdleDisconnect: 'ターミナルのアイドル切断(秒)', + terminalIdleDisconnectHelp: 'ターミナルを開いた後、この時間だけキーボード入力もPTY出力もなければ接続を切断し、サンドボックスはTTLに従って一時停止します。空欄の場合は900秒、最短60秒、最長24時間です。', envVars: '環境変数', envKey: '名前', envValue: '値', @@ -3387,6 +3390,26 @@ export default { referencesDrawerDocsSection: 'ドキュメント', referencesDrawerToolsSection: 'ツール', referencesDrawerEmpty: '出典はありません', + sandbox: { + panelTitle: 'サンドボックス', + tabArtifacts: 'ファイル', + tabTerminal: 'ターミナル', + tabDesktop: 'デスクトップ', + artifactsEmpty: 'この会話で生成されたファイルはまだありません', + desktopPlaceholder: 'デスクトップの可視化は近日対応予定です', + notStarted: 'ターミナルはまだ起動していません。起動するとこの会話のサンドボックスに接続し、存在しないか一時停止中の場合は作成または再開します。', + start: 'ターミナルを起動', + connecting: 'サンドボックスに接続中…', + needsProvision: 'この会話には実行中のサンドボックスがありません。作成すると新しいサンドボックスが起動し、ワークスペースの設定に従って課金されます。', + createAndStart: '作成して起動', + noSandbox: 'サンドボックスがまだなく、現在のエージェントにサンドボックスバックエンドが設定されていないため、作成先を決められません。サンドボックスが設定されたエージェントに切り替えるか、コードを実行するメッセージを送信してください。', + unsupported: '現在のサンドボックスバックエンドは対話型ターミナルに対応していません', + disconnected: '接続が切断されました', + retry: '再接続', + sessionEnded: 'ターミナルセッションが終了しました', + idleDisconnected: 'アイドル状態のためターミナルが切断されました。サンドボックスは自身のTTLで一時停止します。再接続できます。', + authRevoked: 'ログイン状態が無効になったため、ターミナルが切断されました。再度サインインしてから接続してください。', + }, questionMinimapTitle: 'Q&A', questionMinimapAriaLabel: '質問一覧', questionMinimapAttachmentPlaceholder: '(添付ファイル)', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 9580ff8c..6a51ea0c 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -3373,6 +3373,26 @@ export default { referencesDrawerDocsSection: '지식베이스 문서', referencesDrawerToolsSection: '도구', referencesDrawerEmpty: '참고 출처가 없습니다', + sandbox: { + panelTitle: '샌드박스', + tabArtifacts: '파일', + tabTerminal: '터미널', + tabDesktop: '데스크톱', + artifactsEmpty: '이 대화에서 생성된 파일이 없습니다', + desktopPlaceholder: '데스크톱 시각화는 곧 지원될 예정입니다', + notStarted: '터미널이 아직 실행되지 않았습니다. 시작하면 이 대화의 샌드박스에 연결하며, 샌드박스가 없거나 일시 중지된 경우 생성하거나 다시 시작합니다.', + start: '터미널 시작', + connecting: '샌드박스에 연결하는 중…', + needsProvision: '이 대화에는 실행 중인 샌드박스가 없습니다. 생성하고 시작하면 새 샌드박스가 만들어지며 워크스페이스 설정에 따라 요금이 부과됩니다.', + createAndStart: '생성 후 시작', + noSandbox: '아직 샌드박스가 없고 현재 에이전트에 샌드박스 백엔드가 구성되지 않아 만들 위치를 정할 수 없습니다. 샌드박스가 구성된 에이전트로 전환하거나 코드 실행이 필요한 메시지를 보내세요.', + unsupported: '현재 샌드박스 백엔드는 대화형 터미널을 지원하지 않습니다', + disconnected: '연결이 끊어졌습니다', + retry: '다시 연결', + sessionEnded: '터미널 세션이 종료되었습니다', + idleDisconnected: '터미널이 유휴 상태로 연결이 끊어졌습니다. 샌드박스는 TTL에 따라 일시 중지됩니다. 다시 연결할 수 있습니다.', + authRevoked: '로그인 상태가 더 이상 유효하지 않아 터미널 연결이 끊어졌습니다. 다시 로그인한 뒤 재연결하세요.', + }, questionMinimapTitle: '질문', questionMinimapAriaLabel: '질문 목차', questionMinimapAttachmentPlaceholder: '(첨부)', @@ -5331,6 +5351,8 @@ export default { dockerNetworkNone: 'none (no egress)', defaultTimeout: 'Execution timeout (s)', defaultTimeoutHelp: '스킬 스크립트 한 번이 실행될 수 있는 최대 시간이며, 초과하면 강제 종료됩니다. 비워 두면 60초입니다.', + terminalIdleDisconnect: '터미널 유휴 해제 (초)', + terminalIdleDisconnectHelp: '터미널을 연 뒤 키보드 입력이나 PTY 출력이 이 시간 동안 없으면 연결을 끊어 샌드박스가 TTL에 따라 일시 중지되도록 합니다. 비워 두면 900초이며, 최소 60초, 최대 24시간입니다.', envVars: 'Environment variables', envKey: 'Name', envValue: 'Value', @@ -6789,6 +6811,7 @@ export default { }, chatHeader: { moreActions: '대화 추가 작업', + toggleSandboxPanel: '샌드박스 터미널', copySessionId: '세션 ID 복사', copyLink: '대화 링크 복사', copyMarkdown: 'Markdown으로 복사', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index f54a6995..9b1c459d 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -3373,6 +3373,26 @@ export default { referencesDrawerDocsSection: 'Документы базы знаний', referencesDrawerToolsSection: 'Инструменты', referencesDrawerEmpty: 'Источники отсутствуют', + sandbox: { + panelTitle: 'Песочница', + tabArtifacts: 'Файлы', + tabTerminal: 'Терминал', + tabDesktop: 'Рабочий стол', + artifactsEmpty: 'В этом диалоге пока нет созданных файлов', + desktopPlaceholder: 'Визуализация рабочего стола скоро появится', + notStarted: 'Терминал ещё не запущен. Запуск подключит его к песочнице этого диалога, создав или возобновив её при необходимости.', + start: 'Запустить терминал', + connecting: 'Подключение к песочнице…', + needsProvision: 'В этом диалоге нет работающей песочницы. Создание запустит новую песочницу — она тарифицируется согласно настройкам рабочего пространства.', + createAndStart: 'Создать и запустить', + noSandbox: 'Песочницы ещё нет, а у текущего агента не настроен бэкенд песочницы — непонятно, где её создавать. Переключитесь на агента с настроенной песочницей или отправьте сообщение с выполнением кода.', + unsupported: 'Текущий бэкенд песочницы не поддерживает интерактивный терминал', + disconnected: 'Соединение потеряно', + retry: 'Переподключиться', + sessionEnded: 'Сеанс терминала завершён', + idleDisconnected: 'Терминал отключён из‑за простоя. Песочница приостановится по своему TTL. Можно подключиться снова.', + authRevoked: 'Сессия больше не действительна, терминал отключён. Войдите снова и переподключитесь.', + }, questionMinimapTitle: 'Вопросы', questionMinimapAriaLabel: 'Содержание вопросов', questionMinimapAttachmentPlaceholder: '(Вложение)', @@ -5331,6 +5351,8 @@ export default { dockerNetworkNone: 'none (no egress)', defaultTimeout: 'Execution timeout (s)', defaultTimeoutHelp: 'Максимальное время одного запуска скрипта навыка; по истечении он прерывается. Пусто — 60 секунд.', + terminalIdleDisconnect: 'Отключение простоя терминала (с)', + terminalIdleDisconnectHelp: 'После открытия терминала соединение закрывается, если столько времени нет ввода с клавиатуры и вывода PTY, чтобы песочница могла приостановиться по TTL. Пусто — 900 секунд; минимум 60 секунд, максимум 24 часа.', envVars: 'Environment variables', envKey: 'Name', envValue: 'Value', @@ -6789,6 +6811,7 @@ export default { }, chatHeader: { moreActions: 'Другие действия с диалогом', + toggleSandboxPanel: 'Терминал песочницы', copySessionId: 'Копировать ID сессии', copyLink: 'Копировать ссылку на диалог', copyMarkdown: 'Копировать как Markdown', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index ce1f47e6..0aa80915 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -3375,6 +3375,26 @@ export default { referencesDrawerDocsSection: '知识库文档', referencesDrawerToolsSection: '工具', referencesDrawerEmpty: '暂无参考来源', + sandbox: { + panelTitle: '沙箱可视化', + tabArtifacts: '产物', + tabTerminal: '终端', + tabDesktop: '桌面', + artifactsEmpty: '本会话尚未生成可下载的文件', + desktopPlaceholder: '桌面可视化即将支持', + notStarted: '终端尚未启动。启动后会连接本会话的沙箱环境;若沙箱不存在或已暂停,将为你创建或唤醒它。', + start: '启动终端', + connecting: '正在连接沙箱…', + needsProvision: '本会话当前没有运行中的沙箱环境。创建并启动会新建一个沙箱,并按工作区配置计费。', + createAndStart: '创建并启动', + noSandbox: '会话尚未创建沙箱,且当前智能体未配置沙箱后端,无法确定在哪个后端创建。请切换到配置了沙箱的智能体,或发送一条需要执行代码的消息。', + unsupported: '当前沙箱后端不支持交互终端', + disconnected: '连接已断开', + retry: '重新连接', + sessionEnded: '终端会话已结束', + idleDisconnected: '终端空闲已断开,沙箱将按工作区 TTL 自行暂停。可重新连接。', + authRevoked: '登录状态已失效,终端已断开。请重新登录后再连接。', + }, questionMinimapTitle: '问答', questionMinimapAriaLabel: '提问目录', questionMinimapAttachmentPlaceholder: '(附件)', @@ -5333,6 +5353,8 @@ export default { dockerNetworkNone: 'none(禁止出网)', defaultTimeout: '执行超时(秒)', defaultTimeoutHelp: '单次技能脚本允许运行的最长时间,超时会被强制终止。留空按 60 秒。', + terminalIdleDisconnect: '交互式终端空闲断开(秒)', + terminalIdleDisconnectHelp: '打开终端后,这段时间内没有键盘输入或终端输出就断开连接,沙箱随后按 TTL 自行暂停。留空按 900 秒;最短 60 秒,最长 24 小时。', envVars: '环境变量', envKey: '变量名', envValue: '变量值', @@ -6791,6 +6813,7 @@ export default { }, chatHeader: { moreActions: '更多对话操作', + toggleSandboxPanel: '沙箱终端', copySessionId: '复制会话 ID', copyLink: '复制对话链接', copyMarkdown: '复制为 Markdown', diff --git a/frontend/src/utils/ptyEchoPredictor.test.ts b/frontend/src/utils/ptyEchoPredictor.test.ts new file mode 100644 index 00000000..5c9992fb --- /dev/null +++ b/frontend/src/utils/ptyEchoPredictor.test.ts @@ -0,0 +1,89 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { createPtyEchoPredictor, looksLikeSecretPrompt } from './ptyEchoPredictor' + +function collect() { + const written: string[] = [] + const predictor = createPtyEchoPredictor((chunk) => { + written.push(typeof chunk === 'string' ? chunk : new TextDecoder().decode(chunk)) + }) + return { + predictor, + text: () => written.join(''), + } +} + +test('echoes printable keystrokes locally and strips matching PTY echo in chunks', () => { + const { predictor, text } = collect() + predictor.onLocal('h') + predictor.onLocal('i') + assert.equal(text(), 'hi') + predictor.onRemote(new TextEncoder().encode('h')) + predictor.onRemote(new TextEncoder().encode('i')) + assert.equal(text(), 'hi') +}) + +test('keeps the predicted line across Enter so the remote echo does not flash', () => { + const { predictor, text } = collect() + predictor.onLocal('h') + predictor.onLocal('i') + predictor.onLocal('\r') + assert.equal(text(), 'hi') + predictor.onRemote(new TextEncoder().encode('hi\r\n')) + assert.equal(text(), 'hi\r\n') +}) + +test('rewinds the prediction when the PTY echo does not match', () => { + const { predictor, text } = collect() + predictor.onLocal('a') + predictor.onRemote(new TextEncoder().encode('\x1b[32mready\x1b[0m\n')) + const got = text() + assert.match(got, /\ba|[\b]/) + assert.equal(got.includes('ready'), true) +}) + +test('does not locally echo control sequences', () => { + const { predictor, text } = collect() + predictor.onLocal('\x1b[A') + predictor.onLocal('\r') + predictor.onLocal('\t') + assert.equal(text(), '') +}) + +test('echoes CJK locally and strips the matching remote bytes', () => { + const { predictor, text } = collect() + predictor.onLocal('你') + assert.equal(text(), '你') + predictor.onRemote(new TextEncoder().encode('你')) + assert.equal(text(), '你') +}) + +test('locally erases a predicted character on backspace', () => { + const { predictor, text } = collect() + predictor.onLocal('ab') + predictor.onLocal('\x7f') + assert.equal(text(), 'ab\b \b') +}) + +test('looksLikeSecretPrompt detects sudo and localized prompts', () => { + assert.equal(looksLikeSecretPrompt('[sudo] password for alice: '), true) + assert.equal(looksLikeSecretPrompt('Password:'), true) + assert.equal(looksLikeSecretPrompt('请输入密码:'), true) + assert.equal(looksLikeSecretPrompt('user@host:~$ '), false) +}) + +test('does not locally echo keystrokes after a password prompt', () => { + const { predictor, text } = collect() + predictor.onRemote(new TextEncoder().encode('[sudo] password for alice: ')) + predictor.onLocal('s') + predictor.onLocal('e') + predictor.onLocal('c') + predictor.onLocal('r') + predictor.onLocal('e') + predictor.onLocal('t') + assert.equal(text(), '[sudo] password for alice: ') + predictor.onLocal('\r') + predictor.onRemote(new TextEncoder().encode('\r\nalice@host:~$ ')) + predictor.onLocal('l') + assert.equal(text().endsWith('l'), true) +}) diff --git a/frontend/src/utils/ptyEchoPredictor.ts b/frontend/src/utils/ptyEchoPredictor.ts new file mode 100644 index 00000000..7f0a81b9 --- /dev/null +++ b/frontend/src/utils/ptyEchoPredictor.ts @@ -0,0 +1,123 @@ +/** + * Optimistic local echo for a high-latency PTY. + * + * xterm does not echo keystrokes; it waits for the remote shell. E2B's + * SendInput is a unary RPC, so that wait is one data-plane RTT per key. + * Printable input is drawn immediately and later stripped from the PTY + * stream when the real echo arrives, so characters do not double. + * + * Password prompts must not be locally echoed: sudo / read -s / login + * typically send no echo, and predicted characters would stay on screen. + */ + +export type PtyEchoWrite = (chunk: string | Uint8Array) => void + +export function looksLikeSecretPrompt(text: string): boolean { + const line = (text.split(/\r\n|\n|\r/).pop() ?? '').trimEnd() + if (/(?:password|passphrase|密码)/i.test(line)) { + return true + } + return /\bpin\s*:?\s*$/i.test(line) +} + +function cellWidth(ch: string): number { + const cp = ch.codePointAt(0) ?? 0 + if (cp === 0) return 0 + if (cp <= 0x7f) return 1 + return 2 +} + +function displayCells(s: string): number { + let n = 0 + for (const ch of s) n += cellWidth(ch) + return n +} + +function popChar(s: string): { rest: string; ch: string } { + const chars = [...s] + const ch = chars.pop() ?? '' + return { rest: chars.join(''), ch } +} + +export function createPtyEchoPredictor(write: PtyEchoWrite) { + let predicted = '' + let secretPrompt = false + let recentRemote = '' + const decoder = new TextDecoder() + + function eraseCells(n: number) { + if (n <= 0) return + write('\b'.repeat(n) + ' '.repeat(n) + '\b'.repeat(n)) + } + + function rewindAll() { + eraseCells(displayCells(predicted)) + predicted = '' + } + + function noteRemote(text: string) { + recentRemote = (recentRemote + text).slice(-400) + if (looksLikeSecretPrompt(recentRemote)) { + secretPrompt = true + rewindAll() + return + } + if (!secretPrompt) return + const line = recentRemote.split(/\r\n|\n|\r/).pop() ?? '' + if (line.trim() !== '') { + secretPrompt = false + } + } + + return { + onLocal(data: string) { + if (secretPrompt) { + return + } + if (data === '\x7f' || data === '\b') { + if (!predicted) return + const { rest, ch } = popChar(predicted) + predicted = rest + eraseCells(cellWidth(ch)) + return + } + // Enter must keep the predicted line so the shell's echo of those + // characters is stripped instead of flashing (draw, wipe, redraw). + if (data === '\r' || data === '\n') { + return + } + if (data === '\t' || data.startsWith('\x1b')) { + rewindAll() + return + } + if (data.length === 0) return + for (const ch of data) { + if (ch < ' ') { + rewindAll() + return + } + } + predicted += data + write(data) + }, + + onRemote(bytes: Uint8Array) { + if (bytes.length === 0) return + const text = decoder.decode(bytes, { stream: true }) + if (!text) return + noteRemote(text) + + const predChars = [...predicted] + const textChars = [...text] + let i = 0 + while (i < predChars.length && i < textChars.length && predChars[i] === textChars[i]) { + i++ + } + predicted = predChars.slice(i).join('') + const rest = textChars.slice(i).join('') + if (!rest) return + if (predicted) rewindAll() + write(rest) + }, + } +} diff --git a/frontend/src/utils/sandboxArtifactRefs.ts b/frontend/src/utils/sandboxArtifactRefs.ts index 62a0b5cb..793d1d38 100644 --- a/frontend/src/utils/sandboxArtifactRefs.ts +++ b/frontend/src/utils/sandboxArtifactRefs.ts @@ -14,7 +14,7 @@ * 交回默认的受保护图片渲染,而不是显示「文件不可用」。 * * 图片类产物内联显示(带鉴权拉取后换成 blob),其余类型(HTML 图表、CSV、 - * 文档等)渲染成一张卡片,点击后交给 ChatArtifactsDrawer 预览——正文里塞一个 + * 文档等)渲染成一张卡片,点击后交给右侧沙箱面板的产物页预览——正文里塞一个 * 1MB 的自包含 HTML iframe 既慢又不安全。 */ diff --git a/frontend/src/utils/sandboxPtyId.test.ts b/frontend/src/utils/sandboxPtyId.test.ts new file mode 100644 index 00000000..312cee1a --- /dev/null +++ b/frontend/src/utils/sandboxPtyId.test.ts @@ -0,0 +1,44 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { readStoredPtyId, sandboxPtyStorageKey, writeStoredPtyId } from './sandboxPtyId' + +const memory = new Map() + +function installFakeStorage() { + const fake = { + getItem(key: string) { + return memory.has(key) ? memory.get(key)! : null + }, + setItem(key: string, value: string) { + memory.set(key, value) + }, + removeItem(key: string) { + memory.delete(key) + }, + } + Object.defineProperty(globalThis, 'sessionStorage', { + configurable: true, + value: fake, + }) +} + +test('round-trips a pid keyed by session', () => { + memory.clear() + installFakeStorage() + writeStoredPtyId('sess-a', 4321) + assert.equal(readStoredPtyId('sess-a'), 4321) + assert.equal(readStoredPtyId('sess-b'), null) + assert.equal(sandboxPtyStorageKey('sess-a'), 'weknora_sandbox_pty:sess-a') +}) + +test('forgets the pid when cleared or invalid', () => { + memory.clear() + installFakeStorage() + writeStoredPtyId('sess-a', 4321) + writeStoredPtyId('sess-a', null) + assert.equal(readStoredPtyId('sess-a'), null) + + writeStoredPtyId('sess-a', 7) + memory.set(sandboxPtyStorageKey('sess-a'), 'nope') + assert.equal(readStoredPtyId('sess-a'), null) +}) diff --git a/frontend/src/utils/sandboxPtyId.ts b/frontend/src/utils/sandboxPtyId.ts new file mode 100644 index 00000000..f5df3187 --- /dev/null +++ b/frontend/src/utils/sandboxPtyId.ts @@ -0,0 +1,43 @@ +/** + * Persist the remote shell PID across a tab refresh / panel remount. + * + * Close() on the server only disconnects the stream; the bash stays in the + * sandbox so Pty.Connect can reattach. lastPid used to live only in the + * composable closure, so a refresh created a new shell and left the old + * one orphaned. sessionStorage is tab-scoped: a new tab starts clean, this + * tab's F5 does not. + */ + +const KEY_PREFIX = 'weknora_sandbox_pty:' + +export function sandboxPtyStorageKey(sessionId: string): string { + return `${KEY_PREFIX}${sessionId.trim()}` +} + +export function readStoredPtyId(sessionId: string): number | null { + const sid = sessionId.trim() + if (!sid || typeof sessionStorage === 'undefined') return null + try { + const raw = sessionStorage.getItem(sandboxPtyStorageKey(sid)) + const pid = Number(raw) + if (!Number.isInteger(pid) || pid <= 0) return null + return pid + } catch { + return null + } +} + +export function writeStoredPtyId(sessionId: string, pid: number | null): void { + const sid = sessionId.trim() + if (!sid || typeof sessionStorage === 'undefined') return + try { + const key = sandboxPtyStorageKey(sid) + if (pid == null || pid <= 0) { + sessionStorage.removeItem(key) + return + } + sessionStorage.setItem(key, String(pid)) + } catch { + // Private mode can throw; reattach then degrades to Create. + } +} diff --git a/frontend/src/utils/sessionArtifacts.test.ts b/frontend/src/utils/sessionArtifacts.test.ts new file mode 100644 index 00000000..6eb98c76 --- /dev/null +++ b/frontend/src/utils/sessionArtifacts.test.ts @@ -0,0 +1,66 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { + collectSessionArtifacts, + formatArtifactDateTime, + formatArtifactSize, +} from './sessionArtifacts.ts' + +test('collectSessionArtifacts keeps per-message download indexes', () => { + const items = collectSessionArtifacts([ + { role: 'user', id: 'u1', content: 'hi' }, + { + role: 'assistant', + id: 'a1', + artifacts: [{ file_name: 'a.csv', file_size: 12 }], + }, + { + role: 'assistant', + id: 'a2', + artifacts: [ + { index: 0, file_name: 'chart.html' }, + { index: 1, file_name: 'plot.png' }, + ], + }, + ]) + assert.deepEqual( + items.map((item) => ({ messageId: item.messageId, index: item.index, file_name: item.file_name })), + [ + { messageId: 'a1', index: 0, file_name: 'a.csv' }, + { messageId: 'a2', index: 0, file_name: 'chart.html' }, + { messageId: 'a2', index: 1, file_name: 'plot.png' }, + ], + ) +}) + +test('collectSessionArtifacts falls back to request_id before the row is persisted', () => { + const items = collectSessionArtifacts([ + { request_id: 'req-9', artifacts: [{ file_name: 'out.md' }] }, + ]) + assert.equal(items[0]?.messageId, 'req-9') + assert.equal(items[0]?.index, 0) +}) + +test('collectSessionArtifacts skips empty or unidentifiable rows', () => { + assert.deepEqual( + collectSessionArtifacts([ + { id: 'a1', artifacts: [] }, + { artifacts: [{ file_name: 'ghost.txt' }] }, + null, + 'nope', + ]), + [], + ) +}) + +test('formatArtifactSize matches the former drawer copy', () => { + assert.equal(formatArtifactSize(0), '0 B') + assert.equal(formatArtifactSize(512), '512 B') + assert.equal(formatArtifactSize(2048), '2.0 KB') +}) + +test('formatArtifactDateTime renders a stable local timestamp', () => { + assert.equal(formatArtifactDateTime(''), '—') + assert.equal(formatArtifactDateTime('not-a-date'), 'not-a-date') + assert.match(formatArtifactDateTime('2026-09-08T04:05:00Z'), /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/) +}) diff --git a/frontend/src/utils/sessionArtifacts.ts b/frontend/src/utils/sessionArtifacts.ts new file mode 100644 index 00000000..fbc24cfe --- /dev/null +++ b/frontend/src/utils/sessionArtifacts.ts @@ -0,0 +1,64 @@ +import type { ArtifactMeta } from '@/api/chat' + +/** Artifact metadata plus the assistant message that owns the download index. */ +export type SessionArtifactItem = ArtifactMeta & { + messageId: string +} + +function asRecord(value: unknown): Record | null { + if (!value || typeof value !== 'object' || Array.isArray(value)) return null + return value as Record +} + +function readMessageId(message: Record): string { + return String(message.id || message.request_id || '') +} + +/** + * Flatten every assistant message's artifacts in list order. Download still + * uses the per-message index (not a session-wide offset), so each row keeps + * the owning message id. + */ +export function collectSessionArtifacts(messages: unknown): SessionArtifactItem[] { + if (!Array.isArray(messages)) return [] + const items: SessionArtifactItem[] = [] + for (const raw of messages) { + const message = asRecord(raw) + if (!message) continue + const list = Array.isArray(message.artifacts) ? message.artifacts : [] + if (!list.length) continue + const messageId = readMessageId(message) + if (!messageId) continue + for (let i = 0; i < list.length; i++) { + const art = asRecord(list[i]) + if (!art) continue + const index = Number.isInteger(art.index) ? (art.index as number) : i + items.push({ + ...(art as unknown as ArtifactMeta), + index, + messageId, + }) + } + } + return items +} + +export function formatArtifactSize(size: number | undefined | null): string { + if (!size || size < 0) return '0 B' + const units = ['B', 'KB', 'MB', 'GB'] + let value = size + let unit = 0 + while (value >= 1024 && unit < units.length - 1) { + value /= 1024 + unit++ + } + return unit === 0 ? `${value} ${units[unit]}` : `${value.toFixed(1)} ${units[unit]}` +} + +export function formatArtifactDateTime(raw: string | undefined | null): string { + if (!raw) return '—' + const parsed = new Date(raw) + if (Number.isNaN(parsed.getTime())) return String(raw) + const pad = (n: number) => String(n).padStart(2, '0') + return `${parsed.getFullYear()}-${pad(parsed.getMonth() + 1)}-${pad(parsed.getDate())} ${pad(parsed.getHours())}:${pad(parsed.getMinutes())}` +} diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vue index 0f1852c9..26431205 100644 --- a/frontend/src/views/chat/components/AgentStreamDisplay.vue +++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue @@ -577,7 +577,7 @@ { const list = ((props.session?.artifacts as any[]) || []); return list.map((a, i) => ({ index: i, ...a })); @@ -1027,6 +1027,13 @@ const messageIdForArtifacts = computed(() => const artifactPreviewIndex = ref(null); function openArtifactDrawer(previewIndex: number | null = null) { if (!hasArtifacts.value) return; + if (sandboxPanel && !props.embeddedMode) { + sandboxPanel.open('artifacts', { + messageId: messageIdForArtifacts.value, + previewIndex, + }); + return; + } artifactPreviewIndex.value = previewIndex; showArtifactDrawer.value = true; } diff --git a/frontend/src/views/chat/components/ChatArtifactsPanel.vue b/frontend/src/views/chat/components/ChatArtifactsPanel.vue new file mode 100644 index 00000000..59c1bfe9 --- /dev/null +++ b/frontend/src/views/chat/components/ChatArtifactsPanel.vue @@ -0,0 +1,445 @@ + + + + + diff --git a/frontend/src/views/chat/components/SandboxTerminal.vue b/frontend/src/views/chat/components/SandboxTerminal.vue new file mode 100644 index 00000000..d2679d66 --- /dev/null +++ b/frontend/src/views/chat/components/SandboxTerminal.vue @@ -0,0 +1,344 @@ + + + + + diff --git a/frontend/src/views/chat/components/answerToolbarCompletion.test.mjs b/frontend/src/views/chat/components/answerToolbarCompletion.test.mjs index f54cdd49..5d8f5ec9 100644 --- a/frontend/src/views/chat/components/answerToolbarCompletion.test.mjs +++ b/frontend/src/views/chat/components/answerToolbarCompletion.test.mjs @@ -40,6 +40,13 @@ test('artifact count is a top-right overlay instead of t-badge', () => { assert.doesNotMatch(agentStream, / { + assert.match(botMessage, /sandboxPanel.open\('artifacts'/) + assert.match(agentStream, /sandboxPanel.open\('artifacts'/) + assert.match(botMessage, /v-if="hasArtifacts && embeddedMode"/) + assert.match(agentStream, /v-if="hasArtifacts && embeddedMode/) +}) + test('artifact toolbar uses a folder icon and replaces it while collecting', () => { assert.match(botMessage, /answer-toolbar__artifact[\s\S]{0,800}name="folder"/) assert.match(agentStream, /answer-toolbar__artifact[\s\S]{0,800}name="folder"/) diff --git a/frontend/src/views/chat/components/botmsg.vue b/frontend/src/views/chat/components/botmsg.vue index a708708d..529f3fbb 100644 --- a/frontend/src/views/chat/components/botmsg.vue +++ b/frontend/src/views/chat/components/botmsg.vue @@ -92,7 +92,7 @@ :on-leave="scheduleCitationClose" /> !!(props.session?.request_id || props.session?.id)); // ----------------------------------------------------------------------------- -// Skill artifact download (drawer) +// Skill artifact download (drawer in embedded mode; sandbox panel otherwise) // ----------------------------------------------------------------------------- -// The download button and drawer are opt-in per message: the toolbar checks +// The download button is opt-in per message: the toolbar checks // `hasArtifacts` and only renders when the assistant message actually -// recorded a file. `messageIdForArtifacts` resolves to whichever field the -// caller uses to identify the row on the server (session.id from the SSE -// hydration path, request_id when the caller pre-populated it). +// recorded a file. In the main app this opens the sandbox panel's artifacts +// tab. Embedded chat still uses ChatArtifactsDrawer. // // NOTE: this file's