Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(sandbox): add an interactive terminal and files tab beside chat (#3110)
nullptr-error277d6ee851c1
diff --git a/frontend/Dockerfile b/frontend/Dockerfileindex 2aa94eaba..342ba7e30 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.confCOPY docker-entrypoint.sh /docker-entrypoint.shRUN chmod +x /docker-entrypoint.shdiff --git a/frontend/nginx-http.conf b/frontend/nginx-http.confnew file mode 100644index 000000000..1134d9f21--- /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.confindex a086c6557..6224f5ae1 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.jsonindex 4c467ea71..d618f470e 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.jsonindex 954eba56d..9cac8cf9c 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.tsindex 7cc0c6e9a..528e14445 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?: stringdefault_timeout_sec?: number+ terminal_idle_disconnect_sec?: numberallow_private_endpoints?: booleanenv_vars?: Record<string, string>volume_mount?: SandboxVolumeMountConfigdiff --git a/frontend/src/components/SandboxConfigEditorDrawer.vue b/frontend/src/components/SandboxConfigEditorDrawer.vueindex 88d5c7368..660bef872 100644--- a/frontend/src/components/SandboxConfigEditorDrawer.vue+++ b/frontend/src/components/SandboxConfigEditorDrawer.vue@@ -421,6 +421,11 @@:tips="$t('settings.sandbox.defaultTimeoutHelp')"><t-input-number v-model="defaultTimeoutSec" :min="0" theme="column" placeholder="60" /></t-form-item>+ <t-form-item :label="$t('settings.sandbox.terminalIdleDisconnect')"+ :tips="$t('settings.sandbox.terminalIdleDisconnectHelp')">+ <t-input-number v-model="terminalIdleDisconnectSec" :min="0" :max="86400"+ theme="column" placeholder="900" />+ </t-form-item></div></div></section>@@ -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<number | undefined>(undefined)+const terminalIdleDisconnectSec = ref<number | undefined>(undefined)const allowPrivateEndpoints = ref(false)const cube = reactive<SandboxCubeConfig>({})const e2b = reactive<SandboxE2BConfig>({})@@ -1121,6 +1127,7 @@ function reset() {? cfg.sandbox_type!: defaultBackendType()defaultTimeoutSec.value = cfg.default_timeout_sec || undefined+ terminalIdleDisconnectSec.value = cfg.terminal_idle_disconnect_sec || undefinedallowPrivateEndpoints.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.mjsnew file mode 100644index 000000000..672239c67--- /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, /<ChatArtifactsPanel/)+ assert.doesNotMatch(panel, /chat-sandbox-panel__title/)+ assert.doesNotMatch(panel, /<h3/)+})diff --git a/frontend/src/components/chat/SandboxSidePanel.vue b/frontend/src/components/chat/SandboxSidePanel.vuenew file mode 100644index 000000000..ab491edf8--- /dev/null+++ b/frontend/src/components/chat/SandboxSidePanel.vue@@ -0,0 +1,362 @@+<template>+ <Transition name="sandbox-panel">+ <aside+ v-if="panel?.visible.value"+ class="chat-sandbox-panel"+ :class="{ 'is-shifted': shifted, 'is-resizing': resizing }"+ :style="{ width: `${panel?.width.value ?? 420}px` }"+ role="complementary"+ :aria-label="t('chat.sandbox.panelTitle')"+ >+ <!-- 左缘拖拽把手:按住向左/右拖动调整面板宽度。 -->+ <div+ class="chat-sandbox-panel__resize-handle"+ :aria-hidden="true"+ @mousedown.prevent="startResize"+ />+ <div class="chat-sandbox-panel__tabs">+ <div class="chat-sandbox-panel__tablist" role="tablist">+ <button+ v-for="tab in tabs"+ :key="tab.id"+ type="button"+ class="chat-sandbox-panel__tab"+ :class="{ 'is-active': panel?.activeTab.value === tab.id }"+ role="tab"+ :aria-selected="panel?.activeTab.value === tab.id"+ @click="panel?.open(tab.id)"+ >+ <t-icon :name="tab.icon" size="16px" />+ <span>{{ tab.label }}</span>+ <span+ v-if="tab.id === 'artifacts' && artifacts.length"+ class="chat-sandbox-panel__tab-count"+ aria-hidden="true"+ >{{ artifacts.length }}</span>+ </button>+ </div>+ <button+ type="button"+ class="chat-sandbox-panel__close"+ :aria-label="t('common.close')"+ @click="panel?.close()"+ >+ <t-icon name="close" size="20px" />+ </button>+ </div>++ <div+ class="chat-sandbox-panel__body"+ :class="{ 'is-flush': panel?.activeTab.value === 'artifacts' }"+ >+ <ChatArtifactsPanel+ v-show="panel?.activeTab.value === 'artifacts'"+ class="chat-sandbox-panel__artifacts"+ :session-id="sessionId"+ :items="artifacts"+ :collecting="artifactsCollecting"+ :active="panel?.activeTab.value === 'artifacts'"+ />++ <!-- 终端:首次激活时惰性挂载;切 tab 用 v-show 保留实例(不丢 PTY)。 -->+ <SandboxTerminal+ v-if="terminalMounted"+ v-show="panel?.activeTab.value === 'terminal'"+ :key="sessionId"+ ref="terminalRef"+ :session-id="sessionId"+ :agent-id="agentId"+ :agent-source-tenant-id="agentSourceTenantId"+ class="chat-sandbox-panel__terminal"+ />+ <div v-else-if="panel?.activeTab.value === 'terminal'" class="chat-sandbox-panel__placeholder">+ <t-skeleton animation="gradient" :row-col="[{ width: '100%', height: '100%', type: 'rect' }]" />+ </div>++ <div v-if="panel?.activeTab.value === 'desktop'" class="chat-sandbox-panel__placeholder">+ <t-icon name="desktop" size="28px" />+ <p>{{ t('chat.sandbox.desktopPlaceholder') }}</p>+ </div>+ </div>+ </aside>+ </Transition>+</template>++<script setup lang="ts">+import { computed, nextTick, ref, watch } from 'vue'+import { useI18n } from 'vue-i18n'+import {+ useChatSandboxPanel,+ SANDBOX_PANEL_MIN_WIDTH,+ SANDBOX_PANEL_MAX_WIDTH,+ type SandboxPanelTab,+} from '@/composables/useChatSandboxPanel'+import SandboxTerminal from '@/views/chat/components/SandboxTerminal.vue'+import ChatArtifactsPanel from '@/views/chat/components/ChatArtifactsPanel.vue'+import type { SessionArtifactItem } from '@/utils/sessionArtifacts'++const props = withDefaults(+ defineProps<{+ sessionId: string+ /** 当前会话选中的 agent(首次连接时按其配置自动创建沙箱)。 */+ agentId?: string+ /** 共享智能体来源空间,缺省表示本空间自有 agent。 */+ agentSourceTenantId?: string | number | null+ /** 参考来源面板同开时整体左移,避免两块 fixed 面板重叠。 */+ shifted?: boolean+ artifacts?: SessionArtifactItem[]+ artifactsCollecting?: boolean+ }>(),+ {+ artifacts: () => [],+ artifactsCollecting: false,+ },+)++const { t } = useI18n()+const panel = useChatSandboxPanel()++const tabs = computed(() => [+ { id: 'artifacts' as SandboxPanelTab, icon: 'folder', label: t('chat.sandbox.tabArtifacts') },+ { id: 'terminal' as SandboxPanelTab, icon: 'terminal', label: t('chat.sandbox.tabTerminal') },+ { id: 'desktop' as SandboxPanelTab, icon: 'desktop', label: t('chat.sandbox.tabDesktop') },+])++// 终端实例惰性挂载(首次切到终端 tab 时),面板关闭即销毁(v-if),+// 与 ChatReferencesDrawer 的开合行为一致;会话切换时由 :key 重建。+const terminalMounted = ref(false)+const terminalRef = ref<{ focus?: () => void } | null>(null)++watch(+ () => [panel?.visible.value, panel?.activeTab.value] as const,+ ([visible, tab]) => {+ if (visible && tab === 'terminal') {+ terminalMounted.value = true+ void nextTick(() => terminalRef.value?.focus?.())+ }+ },+ { immediate: true },+)++watch(+ () => props.sessionId,+ () => {+ panel?.clearArtifactFocus()+ },+)++// --- 左缘拖拽调宽 -------------------------------------------------------+const resizing = ref(false)+// 与面板样式一致:仅宽视口(≥1400px)且参考面板同开时才整体左移 420px。+const dragBaseOffset = () =>+ props.shifted && typeof window !== 'undefined' && window.innerWidth >= 1400 ? 420 : 0++function startResize(event: MouseEvent) {+ if (!panel) return+ resizing.value = true+ // 拖拽期间禁用全局文本选择,避免 mousemove 命中 iframe / 文本。+ document.body.style.userSelect = 'none'+ document.body.style.cursor = 'col-resize'++ const onMove = (moveEvent: MouseEvent) => {+ const next = window.innerWidth - moveEvent.clientX - dragBaseOffset()+ panel.setWidth(Math.min(SANDBOX_PANEL_MAX_WIDTH, Math.max(SANDBOX_PANEL_MIN_WIDTH, next)))+ }+ const cleanup = () => {+ document.removeEventListener('mousemove', onMove)+ document.removeEventListener('mouseup', cleanup)+ document.body.style.userSelect = ''+ document.body.style.cursor = ''+ resizing.value = false+ }+ document.addEventListener('mousemove', onMove)+ document.addEventListener('mouseup', cleanup)+}+</script>++<style scoped lang="less">+.chat-sandbox-panel {+ position: fixed;+ top: 0;+ right: 0;+ bottom: 0;+ width: min(420px, 100vw);+ max-width: 100vw;+ z-index: 1201;+ display: flex;+ flex-direction: column;+ background: var(--td-bg-color-container);+ border-left: 1px solid var(--td-component-stroke);+ box-shadow: -8px 0 24px rgba(0, 0, 0, 0.06);++ &.is-shifted {+ @media (min-width: 1400px) {+ right: 420px;+ }+ }++ // 拖拽调宽期间关闭过渡与文本选择,保证跟手。+ &.is-resizing {+ transition: none;+ user-select: none;++ .chat-sandbox-panel__body,+ .chat-sandbox-panel__tabs {+ pointer-events: none;+ }+ }+}++// 左缘拖拽把手:一条贴边的窄热区,hover 时显示视觉提示。+.chat-sandbox-panel__resize-handle {+ position: absolute;+ top: 0;+ left: -3px;+ bottom: 0;+ width: 7px;+ z-index: 3;+ cursor: col-resize;++ &::after {+ content: '';+ position: absolute;+ top: 0;+ left: 3px;+ bottom: 0;+ width: 1px;+ background: transparent;+ transition: background-color 0.15s ease;+ }++ &:hover::after,+ .is-resizing &::after {+ background: var(--td-brand-color);+ }+}++.chat-sandbox-panel__close {+ border: 0;+ background: var(--td-bg-color-secondarycontainer);+ color: var(--td-text-color-secondary);+ width: 32px;+ height: 32px;+ border-radius: 8px;+ cursor: pointer;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ flex-shrink: 0;+ transition: background 0.15s ease, color 0.15s ease;++ &:hover {+ background: color-mix(in srgb, var(--td-text-color-primary) 8%, var(--td-bg-color-secondarycontainer));+ color: var(--td-text-color-primary);+ }+}++.chat-sandbox-panel__tabs {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 8px 12px;+ border-bottom: 1px solid var(--td-component-stroke);+ flex-shrink: 0;+}++.chat-sandbox-panel__tablist {+ display: flex;+ gap: 4px;+ min-width: 0;+ flex: 1;+ overflow-x: auto;+}++.chat-sandbox-panel__tab {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 6px 10px;+ border: 0;+ border-radius: 6px;+ background: transparent;+ color: var(--td-text-color-secondary);+ font-size: 13px;+ cursor: pointer;+ white-space: nowrap;+ transition: background-color 0.15s ease, color 0.15s ease;++ &:hover {+ color: var(--td-text-color-primary);+ background: var(--td-bg-color-container-hover);+ }++ &.is-active {+ color: var(--td-brand-color);+ background: var(--td-brand-color-light);+ }+}++.chat-sandbox-panel__tab-count {+ min-width: 16px;+ height: 16px;+ padding: 0 5px;+ border-radius: 8px;+ background: var(--td-brand-color);+ color: #fff;+ font-size: 11px;+ line-height: 16px;+ text-align: center;+}++.chat-sandbox-panel__body {+ flex: 1;+ min-height: 0;+ display: flex;+ flex-direction: column;+ padding: 8px;++ &.is-flush {+ padding: 0;+ }+}++.chat-sandbox-panel__terminal,+.chat-sandbox-panel__artifacts {+ flex: 1;+ min-height: 0;+ min-width: 0;+}++.chat-sandbox-panel__placeholder {+ flex: 1;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 10px;+ color: var(--td-text-color-placeholder);+ font-size: 13px;++ p {+ margin: 0;+ }+}++.sandbox-panel-enter-active {+ transition:+ transform 0.24s cubic-bezier(0.22, 0.61, 0.36, 1),+ opacity 0.24s cubic-bezier(0.22, 0.61, 0.36, 1);+}++.sandbox-panel-leave-active {+ transition:+ transform 0.3s cubic-bezier(0.22, 0.61, 0.36, 1),+ opacity 0.3s cubic-bezier(0.22, 0.61, 0.36, 1);+}++.sandbox-panel-enter-from,+.sandbox-panel-leave-to {+ transform: translateX(100%);+ opacity: 0.6;+}+</style>diff --git a/frontend/src/composables/useChatSandboxPanel.ts b/frontend/src/composables/useChatSandboxPanel.tsnew file mode 100644index 000000000..9c313a491--- /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<boolean>+ activeTab: Ref<SandboxPanelTab>+ width: Ref<number>+ setWidth: (width: number) => void+ artifactFocus: Ref<ArtifactPanelFocusState | null>+ open: (tab?: SandboxPanelTab, focus?: ArtifactPanelFocus) => void+ close: () => void+ clearArtifactFocus: () => void+}++const CHAT_SANDBOX_PANEL_KEY: InjectionKey<ChatSandboxPanelContext> = Symbol(+ 'chatSandboxPanel',+)++export function provideChatSandboxPanel(): ChatSandboxPanelContext {+ const visible = ref(false)+ const activeTab = ref<SandboxPanelTab>('artifacts')+ const width = ref(initialPanelWidth())+ const artifactFocus = ref<ArtifactPanelFocusState | null>(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.tsnew file mode 100644index 000000000..31fc1f572--- /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<string> {+ 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<SandboxTerminalStatus>+ /**+ * 由 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<string>,+ agentId: Ref<string | undefined>,+ agentSourceTenantId: Ref<string | number | null | undefined> = ref(undefined),+): SandboxTerminalSession {+ const status = ref<SandboxTerminalStatus>('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<typeof setTimeout> | null = null+ let pingTimer: ReturnType<typeof setInterval> | 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.tsindex c2829cbc8..bb8cc49e6 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.tsindex 8ee9aff57..06f817b53 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.tsindex 9580ff8c0..6a51ea0ce 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.tsindex f54a69959..9b1c459d6 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.tsindex ce1f47e66..0aa80915e 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.tsnew file mode 100644index 000000000..5c9992fb5--- /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.tsnew file mode 100644index 000000000..7f0a81b90--- /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.tsindex 62a0b5cb5..793d1d386 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.tsnew file mode 100644index 000000000..312cee1a6--- /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<string, string>()++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.tsnew file mode 100644index 000000000..f5df31875--- /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.tsnew file mode 100644index 000000000..6eb98c76f--- /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.tsnew file mode 100644index 000000000..fbc24cfe0--- /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<string, unknown> | null {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null+ return value as Record<string, unknown>+}++function readMessageId(message: Record<string, unknown>): 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.vueindex 0f1852c98..26431205c 100644--- a/frontend/src/views/chat/components/AgentStreamDisplay.vue+++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue@@ -577,7 +577,7 @@</template></t-drawer><ChatArtifactsDrawer- v-if="hasArtifacts && sessionIdForArtifacts && messageIdForArtifacts"+ v-if="hasArtifacts && embeddedMode && sessionIdForArtifacts && messageIdForArtifacts"v-model:visible="showArtifactDrawer":session-id="sessionIdForArtifacts":message-id="messageIdForArtifacts"@@ -600,6 +600,7 @@ import picturePreview from '@/components/picture-preview.vue';import ChatArtifactsDrawer from './ChatArtifactsDrawer.vue';import { isCollectingSkillArtifacts } from '@/utils/skillArtifacts';import { useArtifactArriveMotion } from '@/composables/useArtifactArriveMotion';+import { useChatSandboxPanel } from '@/composables/useChatSandboxPanel';import ChatMemoryStep from './ChatMemoryStep.vue';import { useChatMemoryRow, type UsedMemory } from '@/composables/useChatMemoryRow';import { countGrepDocuments, groupGrepChunkResults } from '@/utils/grepResultsGroup';@@ -1004,11 +1005,10 @@ watch(// Skill artifact download drawer (Agent path)// -----------------------------------------------------------------------------// Same contract as botmsg.vue: only render the button when the persisted-// assistant message actually recorded files, then let ChatArtifactsDrawer-// resolve names/sizes/mtimes and stream downloads via the /artifacts-// endpoint. Agent mode is the primary path for skills, so this button will-// appear more often here than in the RAG path.+// assistant message actually recorded files, then open the sandbox panel's+// artifacts tab (or ChatArtifactsDrawer in embedded mode).const showArtifactDrawer = ref(false);+const sandboxPanel = useChatSandboxPanel();const artifactList = computed(() => {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<number | null>(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.vuenew file mode 100644index 000000000..59c1bfe98--- /dev/null+++ b/frontend/src/views/chat/components/ChatArtifactsPanel.vue@@ -0,0 +1,445 @@+<template>+ <div class="chat-artifacts-panel">+ <div v-if="previewItem" class="artifact-panel-header">+ <t-button+ class="artifact-back"+ variant="text"+ shape="square"+ size="small"+ :title="$t('agent.artifactDrawer.previewBack')"+ :aria-label="$t('agent.artifactDrawer.previewBack')"+ @click="closePreview"+ >+ <template #icon>+ <t-icon name="chevron-left" size="18px" />+ </template>+ </t-button>+ <div class="artifact-panel-header-icon">+ <t-icon :name="getFileIcon(previewItem.file_name)" />+ </div>+ <div class="artifact-panel-header-title" :title="previewItem.file_name">{{ previewItem.file_name }}</div>+ <t-button+ class="artifact-download"+ variant="text"+ shape="square"+ size="small"+ :title="$t('agent.artifactDrawer.download')"+ :loading="isDownloading(previewItem)"+ @click="handleDownload(previewItem)"+ >+ <template #icon>+ <t-icon name="download" size="16px" />+ </template>+ </t-button>+ </div>++ <div v-if="previewItem" class="artifact-preview-body">+ <DocumentPreview+ :session-id="sessionId"+ :message-id="previewItem.messageId"+ :artifact-index="previewItem.index"+ :file-type="previewFileType"+ :file-name="previewItem.file_name"+ :active="active"+ fill-height+ />+ </div>++ <div v-else-if="collecting && !items.length" class="artifact-panel-empty">+ <t-loading size="small" />+ <span>{{ $t('agent.artifactDrawer.collecting') }}</span>+ </div>+ <div v-else-if="!items.length" class="artifact-panel-empty">+ <t-icon name="folder-open" size="32px" />+ <span>{{ $t('chat.sandbox.artifactsEmpty') }}</span>+ </div>+ <template v-else>+ <div v-if="collecting" class="artifact-panel-banner">+ <t-icon name="loading" class="artifact-panel-banner-spin" />+ <span>{{ $t('agent.artifactDrawer.collecting') }}</span>+ </div>+ <ul ref="listRef" class="artifact-list">+ <li+ v-for="item in items"+ :key="`${item.messageId}:${item.index}-${item.file_name}`"+ class="artifact-item is-previewable"+ :class="{ 'is-focused': isFocused(item) }"+ :data-message-id="item.messageId"+ :data-artifact-index="item.index"+ @click="openPreview(item)"+ >+ <span class="artifact-icon">+ <t-icon :name="getFileIcon(item.file_name)" />+ </span>+ <div class="artifact-body">+ <div class="artifact-name" :title="item.file_name">{{ item.file_name }}</div>+ <div class="artifact-meta">+ <span>{{ formatArtifactSize(item.file_size) }}</span>+ <span class="artifact-meta-sep">·</span>+ <span>{{ formatArtifactDateTime(item.created_at) }}</span>+ </div>+ </div>+ <t-button+ class="artifact-preview-btn"+ variant="text"+ shape="square"+ size="small"+ :title="$t('agent.artifactDrawer.preview')"+ @click.stop="openPreview(item)"+ >+ <template #icon>+ <t-icon name="browse" size="16px" />+ </template>+ </t-button>+ <t-button+ class="artifact-download"+ variant="text"+ shape="square"+ size="small"+ :title="$t('agent.artifactDrawer.download')"+ :loading="isDownloading(item)"+ @click.stop="handleDownload(item)"+ >+ <template #icon>+ <t-icon name="download" size="16px" />+ </template>+ </t-button>+ </li>+ </ul>+ </template>+ </div>+</template>++<script setup lang="ts">+import { computed, nextTick, reactive, ref, watch } from 'vue'+import { useI18n } from 'vue-i18n'+import { MessagePlugin } from 'tdesign-vue-next'+import { downloadArtifact } from '@/api/chat'+import { getFileIcon } from '@/utils/files'+import { resolveFilePreviewExt } from '@/utils/filePreview'+import {+ formatArtifactDateTime,+ formatArtifactSize,+ type SessionArtifactItem,+} from '@/utils/sessionArtifacts'+import { useChatSandboxPanel, type ArtifactPanelFocusState } from '@/composables/useChatSandboxPanel'+import DocumentPreview from '@/components/document-preview.vue'++const props = withDefaults(+ defineProps<{+ sessionId: string+ items: SessionArtifactItem[]+ collecting?: boolean+ active?: boolean+ }>(),+ {+ collecting: false,+ active: true,+ },+)++const { t } = useI18n()+const panel = useChatSandboxPanel()+const listRef = ref<HTMLElement | null>(null)+const previewItem = ref<SessionArtifactItem | null>(null)+const downloading = reactive<Record<string, boolean>>({})+const focusedMessageId = ref<string | null>(null)++const previewFileType = computed(() => {+ const item = previewItem.value+ if (!item) return ''+ return resolveFilePreviewExt(item.file_name, item.file_type)+})++function downloadKey(item: SessionArtifactItem): string {+ return `${item.messageId}:${item.index}`+}++function isDownloading(item: SessionArtifactItem): boolean {+ return !!downloading[downloadKey(item)]+}++function isFocused(item: SessionArtifactItem): boolean {+ return !!focusedMessageId.value && item.messageId === focusedMessageId.value+}++function findItem(messageId: string, previewIndex?: number | null): SessionArtifactItem | undefined {+ if (previewIndex != null && Number.isInteger(previewIndex)) {+ return props.items.find((item) => item.messageId === messageId && item.index === previewIndex)+ }+ return props.items.find((item) => item.messageId === messageId)+}++function applyFocus(focus: ArtifactPanelFocusState | null | undefined) {+ if (!focus?.messageId) return+ focusedMessageId.value = focus.messageId+ const wantsPreview = focus.previewIndex != null && Number.isInteger(focus.previewIndex)+ if (wantsPreview) {+ const target = findItem(focus.messageId, focus.previewIndex)+ if (target) previewItem.value = target+ return+ }+ previewItem.value = null+ void nextTick(() => {+ const rows = listRef.value?.querySelectorAll<HTMLElement>('[data-message-id]')+ if (!rows) return+ for (const row of rows) {+ if (row.getAttribute('data-message-id') === focus.messageId) {+ row.scrollIntoView({ block: 'nearest' })+ break+ }+ }+ })+}++watch(+ () => panel?.artifactFocus.value,+ (focus) => applyFocus(focus),+ { immediate: true },+)++watch(+ () => props.sessionId,+ () => {+ previewItem.value = null+ focusedMessageId.value = null+ panel?.clearArtifactFocus()+ },+)++watch(+ () => props.items,+ (items) => {+ const current = previewItem.value+ if (current) {+ const next = items.find(+ (item) => item.messageId === current.messageId && item.index === current.index,+ )+ if (!next) previewItem.value = null+ return+ }+ applyFocus(panel?.artifactFocus.value)+ },+)++function openPreview(item: SessionArtifactItem) {+ previewItem.value = item+}++function closePreview() {+ previewItem.value = null+}++async function handleDownload(item: SessionArtifactItem) {+ if (!props.sessionId || !item.messageId) {+ MessagePlugin.error(t('agent.artifactDrawer.downloadFailed'))+ return+ }+ const key = downloadKey(item)+ downloading[key] = true+ try {+ const blob = await downloadArtifact(props.sessionId, item.messageId, item.index)+ const url = URL.createObjectURL(blob)+ const a = document.createElement('a')+ a.href = url+ a.download = item.file_name || 'artifact'+ document.body.appendChild(a)+ a.click()+ document.body.removeChild(a)+ setTimeout(() => URL.revokeObjectURL(url), 1000)+ } catch (err) {+ console.error('[ChatArtifactsPanel] download failed:', err)+ MessagePlugin.error(t('agent.artifactDrawer.downloadFailed'))+ } finally {+ downloading[key] = false+ }+}+</script>++<style scoped lang="less">+.chat-artifacts-panel {+ flex: 1;+ min-height: 0;+ width: 100%;+ display: flex;+ flex-direction: column;+ overflow: hidden;+}++.artifact-panel-header {+ display: flex;+ align-items: center;+ gap: 8px;+ min-width: 0;+ padding: 8px 12px;+ border-bottom: 1px solid var(--td-component-stroke);+ flex-shrink: 0;+}++.artifact-back {+ flex-shrink: 0;+ color: var(--td-text-color-secondary);++ :deep(.t-button__icon) {+ margin: 0;+ }+}++.artifact-panel-header-icon {+ flex-shrink: 0;+ width: 28px;+ height: 28px;+ border-radius: 8px;+ display: flex;+ align-items: center;+ justify-content: center;+ background: rgba(7, 192, 95, 0.1);+ color: var(--td-brand-color);+ font-size: 15px;+}++.artifact-panel-header-title {+ min-width: 0;+ flex: 1;+ font-size: 13px;+ font-weight: 600;+ line-height: 1.4;+ color: var(--td-text-color-primary);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.artifact-preview-body {+ flex: 1;+ min-height: 0;+ display: flex;+ flex-direction: column;+ padding: 8px;+}++.artifact-panel-empty {+ flex: 1;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 8px;+ padding: 32px 16px;+ color: var(--td-text-color-placeholder);+ font-size: 13px;+ text-align: center;+}++.artifact-panel-banner {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 8px 14px;+ font-size: 12px;+ color: var(--td-text-color-secondary);+ border-bottom: 1px solid var(--td-component-stroke);+}++.artifact-panel-banner-spin {+ animation: artifact-panel-spin 0.8s linear infinite;+}++@keyframes artifact-panel-spin {+ to {+ transform: rotate(360deg);+ }+}++.artifact-list {+ margin: 0;+ padding: 4px 8px 12px;+ list-style: none;+ overflow: auto;+ flex: 1;+ min-height: 0;+}++.artifact-item {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 10px 6px;+ border-bottom: 1px solid var(--td-component-stroke);+ border-radius: 8px;++ &:last-child {+ border-bottom: none;+ }++ &.is-previewable {+ cursor: pointer;+ }++ &:hover {+ background: var(--td-bg-color-container-hover);+ }++ &:hover .artifact-icon {+ color: var(--td-brand-color);+ }++ &.is-focused {+ background: color-mix(in srgb, var(--td-brand-color) 10%, transparent);+ }+}++.artifact-icon {+ flex-shrink: 0;+ width: 28px;+ height: 28px;+ border-radius: 6px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ font-size: 16px;+ background: var(--td-bg-color-secondarycontainer);+ color: var(--td-text-color-secondary);+ transition: color 0.15s ease;+}++.artifact-body {+ flex: 1;+ min-width: 0;+}++.artifact-name {+ font-size: 13px;+ font-weight: 600;+ letter-spacing: 0.01em;+ line-height: 1.35;+ color: var(--td-text-color-primary);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.artifact-meta {+ margin-top: 2px;+ font-size: 12px;+ line-height: 1.3;+ color: var(--td-text-color-placeholder);+ display: flex;+ align-items: center;+ gap: 4px;+}++.artifact-meta-sep {+ opacity: 0.6;+}++.artifact-preview-btn,+.artifact-download {+ flex-shrink: 0;+ color: var(--td-text-color-secondary);++ :deep(.t-button__icon) {+ margin: 0;+ }+}+</style>diff --git a/frontend/src/views/chat/components/SandboxTerminal.vue b/frontend/src/views/chat/components/SandboxTerminal.vuenew file mode 100644index 000000000..d2679d66b--- /dev/null+++ b/frontend/src/views/chat/components/SandboxTerminal.vue@@ -0,0 +1,344 @@+<template>+ <div ref="containerRef" class="sandbox-terminal" :class="{ 'is-dark': isDarkTheme }"+ @mousedown="focusTerminal">+ <div v-if="status !== 'ready'" class="sandbox-terminal__overlay">+ <div class="sandbox-terminal__overlay-card">+ <t-icon v-if="status === 'connecting'" name="loading" size="24px"+ class="sandbox-terminal__spinner" />+ <t-icon+ v-else-if="status === 'not_started' || status === 'needs_provision' || status === 'no_sandbox'"+ name="terminal" size="28px" />+ <t-icon v-else-if="status === 'unsupported'" name="error-circle" size="28px" />+ <t-icon v-else-if="status === 'idle'" name="time" size="28px" />+ <t-icon v-else name="cloud" size="28px" />+ <p class="sandbox-terminal__overlay-text">{{ statusText }}</p>+ <t-button v-if="actionLabel" size="small"+ :theme="status === 'needs_provision' ? 'primary' : 'default'" variant="outline"+ @click.stop="start">+ {{ actionLabel }}+ </t-button>+ </div>+ </div>+ <div ref="terminalHost" class="sandbox-terminal__host"></div>+ </div>+</template>++<script setup lang="ts">+import { computed, nextTick, onBeforeUnmount, ref, toRef, watch } from 'vue';+import { useI18n } from 'vue-i18n';+import { Terminal } from '@xterm/xterm';+import { FitAddon } from '@xterm/addon-fit';+import '@xterm/xterm/css/xterm.css';+import { useSandboxTerminal, type SandboxTerminalStatus } from '@/composables/useSandboxTerminal';+import { useTheme } from '@/composables/useTheme';+import { createPtyEchoPredictor } from '@/utils/ptyEchoPredictor';++const props = defineProps<{+ sessionId: string;+ /** 当前会话选中的 agent:首次连接时后端按其配置自动创建沙箱。 */+ agentId?: string;+ /** 共享智能体的来源空间,与聊天请求的 agent_source_tenant_id 一致。 */+ agentSourceTenantId?: string | number | null;+}>();++const { t } = useI18n();++const containerRef = ref<HTMLElement | null>(null);+const terminalHost = ref<HTMLElement | null>(null);++// 主题必须从 useTheme 的共享 ref 派生,不能读 `theme-mode` DOM 属性:DOM 属性+// 不是响应式数据源,那样写出来的 computed 没有任何依赖,求值一次就永久缓存,+// 下面的 watch 永远不会触发,终端配色会一直停在首次挂载时的样子。+const { currentTheme } = useTheme();+const systemPrefersDark = ref(prefersDarkQuery()?.matches === true);+const isDarkTheme = computed(() =>+ currentTheme.value === 'system' ? systemPrefersDark.value : currentTheme.value === 'dark',+);++function prefersDarkQuery(): MediaQueryList | null {+ if (typeof window === 'undefined' || !window.matchMedia) return null;+ return window.matchMedia('(prefers-color-scheme: dark)');+}++// `system` 模式下还要跟随操作系统的实时切换;useTheme 的全局监听只写 DOM+// 属性,不暴露生效后的明暗值,所以这里自己订阅一份。+const prefersDark = prefersDarkQuery();+const onSystemThemeChange = (event: MediaQueryListEvent) => {+ systemPrefersDark.value = event.matches;+};+prefersDark?.addEventListener('change', onSystemThemeChange);++function xtermTheme(dark: boolean) {+ return dark+ ? {+ background: '#1a1a1a',+ foreground: '#e6e6e6',+ cursor: '#e6e6e6',+ cursorAccent: '#1a1a1a',+ selectionBackground: '#3a3a3a',+ }+ : {+ background: '#ffffff',+ foreground: '#242424',+ cursor: '#242424',+ cursorAccent: '#ffffff',+ selectionBackground: '#d0d7de',+ };+}++// toRef 而非 ref(props.x):后者是快照,切换 agent 后重连仍会沿用旧 agent 的+// 沙箱配置去创建沙箱。sessionId 由父组件的 :key 重建兜住,agentId 不会。+const terminal = useSandboxTerminal(+ toRef(props, 'sessionId'),+ toRef(props, 'agentId'),+ toRef(props, 'agentSourceTenantId'),+);+const { status } = terminal;++const statusText = computed(() => {+ switch (status.value as SandboxTerminalStatus) {+ case 'not_started':+ return t('chat.sandbox.notStarted');+ case 'connecting':+ return t('chat.sandbox.connecting');+ case 'needs_provision':+ return t('chat.sandbox.needsProvision');+ case 'no_sandbox':+ return t('chat.sandbox.noSandbox');+ case 'unsupported':+ return t('chat.sandbox.unsupported');+ case 'exited':+ return t('chat.sandbox.sessionEnded');+ case 'idle':+ return t('chat.sandbox.idleDisconnected');+ case 'unauthorized':+ return t('chat.sandbox.authRevoked');+ default:+ return t('chat.sandbox.disconnected');+ }+});++// 覆盖层上那颗按钮的文案;空串表示这个状态没有可执行的动作。+// 每次点击都视为"用户确认",因此允许后端创建或唤醒沙箱——面板本身永远不会。+const actionLabel = computed(() => {+ switch (status.value as SandboxTerminalStatus) {+ case 'not_started':+ return t('chat.sandbox.start');+ case 'needs_provision':+ return t('chat.sandbox.createAndStart');+ case 'error':+ case 'exited':+ case 'idle':+ case 'unauthorized':+ // no_sandbox 说的是"智能体没配沙箱后端,无处可建"。用户去配好后应该能+ // 直接重试,而不是只能关掉面板再打开——那是个没有任何操作入口的死角。+ case 'no_sandbox':+ return t('chat.sandbox.retry');+ default:+ return '';+ }+});++// xterm 实例只在 ready 后挂载一次;overlay 覆盖在其上展示状态。+let xterm: Terminal | null = null;+let fitAddon: FitAddon | null = null;+let echo: ReturnType<typeof createPtyEchoPredictor> | null = null;+let resizeObserver: ResizeObserver | null = null;+let resizeDebounce: ReturnType<typeof setTimeout> | null = null;+let unmounted = false;++function writeToXterm(chunk: string | Uint8Array) {+ xterm?.write(chunk);+}++function focusTerminal() {+ if (status.value !== 'ready') return;+ xterm?.focus();+}++function mountTerminal() {+ if (!terminalHost.value || xterm) return;+ xterm = new Terminal({+ cursorBlink: true,+ cursorStyle: 'bar',+ cursorInactiveStyle: 'outline',+ fontSize: 13,+ fontFamily: "'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace",+ theme: xtermTheme(isDarkTheme.value),+ scrollback: 5000,+ });+ echo = createPtyEchoPredictor(writeToXterm);+ fitAddon = new FitAddon();+ xterm.loadAddon(fitAddon);+ xterm.open(terminalHost.value);+ xterm.onData((data) => {+ echo?.onLocal(data);+ terminal.sendInput(data);+ });+ // 必须在 connect 之后、但在有输出要展示时注册;composable 会先冲出缓冲的提示符。+ terminal.onOutput((data) => echo?.onRemote(data));++ resizeObserver = new ResizeObserver(() => {+ if (resizeDebounce) clearTimeout(resizeDebounce);+ resizeDebounce = setTimeout(() => {+ if (!fitAddon || !xterm) return;+ try {+ fitAddon.fit();+ terminal.resize(xterm.cols, xterm.rows);+ } catch {+ // fit 在容器尺寸为 0 时会抛错,忽略即可。+ }+ }, 100);+ });+ resizeObserver.observe(containerRef.value || terminalHost.value);+ try {+ fitAddon.fit();+ } catch {+ // 首帧布局未就绪时忽略。+ }+ terminal.resize(xterm.cols, xterm.rows);+ void nextTick(() => {+ requestAnimationFrame(() => fitAndFocus());+ });+}++function unmountTerminal() {+ terminal.onOutput(null);+ echo = null;+ resizeObserver?.disconnect();+ resizeObserver = null;+ if (resizeDebounce) clearTimeout(resizeDebounce);+ resizeDebounce = null;+ xterm?.dispose();+ xterm = null;+ fitAddon = null;+}++// 覆盖层上唯一的连接入口。provision: true 表示这是用户的显式确认,允许后端+// 创建或唤醒沙箱;组件挂载本身不连接,所以打开面板不会产生任何计费副作用。+function start() {+ unmountTerminal();+ terminal.connect({ provision: true });+}++watch(isDarkTheme, (dark) => {+ if (xterm) xterm.options.theme = xtermTheme(dark);+});++// ready 后挂载 xterm;离开非 ready 状态重置实例(重连 = 新 PTY)。+watch(status, (next, prev) => {+ if (next === 'ready' && prev !== 'ready') {+ requestAnimationFrame(() => {+ // 组件可能在 ready 与下一帧之间就被卸载(关面板 / 切会话)。不校验+ // 就会在已销毁的组件上新建 Terminal 并 observe 一个游离节点,那个+ // 实例连 watch 都救不回来。+ if (unmounted) return;+ mountTerminal();+ });+ } else if (prev === 'ready' && next !== 'ready') {+ unmountTerminal();+ }+});++// watch(status) 只覆盖"状态离开 ready",覆盖不到组件本身被销毁:关面板走+// SandboxSidePanel 的 v-if、切会话走 :key 重建,两条路径下 status 全程不变,+// watch 不触发。少了这个钩子,每次开关面板都会漏掉一个 xterm 实例+// (渲染器 + 5000 行 scrollback)和一个 ResizeObserver。+onBeforeUnmount(() => {+ unmounted = true;+ prefersDark?.removeEventListener('change', onSystemThemeChange);+ unmountTerminal();+});++function fitAndFocus() {+ try {+ fitAddon?.fit();+ } catch {+ // 容器尚未完成布局时忽略。+ }+ if (xterm) terminal.resize(xterm.cols, xterm.rows);+ xterm?.focus();+}++defineExpose({+ focus: fitAndFocus,+});+</script>++<style scoped lang="less">+.sandbox-terminal {+ position: relative;+ height: 100%;+ min-height: 0;+ display: flex;+ flex-direction: column;+ background: var(--td-bg-color-container);+ border-radius: 8px;+ overflow: hidden;+ cursor: text;+}++.sandbox-terminal__host {+ flex: 1;+ min-height: 0;+ padding: 8px;+ cursor: text;++ :deep(.xterm) {+ height: 100%;+ cursor: text;+ }++ :deep(.xterm-viewport) {+ overflow-y: auto;+ }++ :deep(.xterm-helper-textarea) {+ // xterm 用隐藏 textarea 接收键盘;必须能获得焦点光标才会闪。+ pointer-events: auto;+ }+}++.sandbox-terminal__overlay {+ position: absolute;+ inset: 0;+ z-index: 2;+ display: flex;+ align-items: center;+ justify-content: center;+ background: var(--td-bg-color-container);+ cursor: default;+}++.sandbox-terminal__overlay-card {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 10px;+ max-width: 280px;+ padding: 20px;+ text-align: center;+ color: var(--td-text-color-placeholder);+}++.sandbox-terminal__overlay-text {+ margin: 0;+ font-size: 13px;+ line-height: 1.6;+ white-space: pre-line;+}++.sandbox-terminal__spinner {+ animation: sandbox-terminal-spin 0.9s linear infinite;+}++@keyframes sandbox-terminal-spin {+ from {+ transform: rotate(0deg);+ }++ to {+ transform: rotate(360deg);+ }+}+</style>diff --git a/frontend/src/views/chat/components/answerToolbarCompletion.test.mjs b/frontend/src/views/chat/components/answerToolbarCompletion.test.mjsindex f54cdd493..5d8f5ec98 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, /<t-badge/)})+test('artifact toolbar opens the sandbox panel artifacts tab', () => {+ 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.vueindex a708708df..529f3fbb8 100644--- a/frontend/src/views/chat/components/botmsg.vue+++ b/frontend/src/views/chat/components/botmsg.vue@@ -92,7 +92,7 @@:on-leave="scheduleCitationClose" /></Teleport><ChatArtifactsDrawer- v-if="hasArtifacts"+ v-if="hasArtifacts && embeddedMode"v-model:visible="showArtifactDrawer":session-id="sessionId":message-id="messageIdForArtifacts"@@ -114,6 +114,7 @@ import picturePreview from '@/components/picture-preview.vue';import ChatArtifactsDrawer from './ChatArtifactsDrawer.vue';import { isCollectingSkillArtifacts } from '@/utils/skillArtifacts';import { useArtifactArriveMotion } from '@/composables/useArtifactArriveMotion';+import { useChatSandboxPanel } from '@/composables/useChatSandboxPanel';import { sanitizeMarkdownHTML, safeMarkdownToHTML, createSafeImage, isValidImageURL, hydrateProtectedFileImages } from '@/utils/security';import {artifactIndexFromEventTarget,@@ -206,18 +207,17 @@ const props = defineProps({const showRequestInfo = computed(() => !!(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 <script setup> block is plain JS (no lang="ts"), so we-// stay away from TypeScript-only syntax like `as any[]` — the vite Vue-// plugin routes non-TS blocks through babel which rejects those tokens.+// stay away from TypeScript-only syntax like `as any[]`.const showArtifactDrawer = ref(false);+const sandboxPanel = useChatSandboxPanel();const artifactList = computed(() => {const raw = props.session && props.session.artifacts;const list = Array.isArray(raw) ? raw : [];@@ -242,6 +242,13 @@ const messageIdForArtifacts = computed(() => {const artifactPreviewIndex = ref(null);function openArtifactDrawer(previewIndex = 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/index.vue b/frontend/src/views/chat/index.vueindex 2ceeb78c8..a428e325a 100644--- a/frontend/src/views/chat/index.vue+++ b/frontend/src/views/chat/index.vue@@ -3,8 +3,25 @@'is-embedded': embeddedMode,'is-sidebar-collapsed': uiStore.sidebarCollapsed,'has-references-panel': referencesDrawerVisible,- }">+ 'has-sandbox-panel': sandboxPanel.visible.value,+ }" :style="{ '--sandbox-panel-width': `${sandboxPanel.width.value}px` }"><ChatHeader v-if="!embeddedMode" :session="currentSession" :has-references-panel="referencesDrawerVisible" />+ <!-- 沙箱面板收起时:图标与左侧栏展开按钮同一套,位置镜像会话左上角三个点。 -->+ <div v-if="!embeddedMode && !sandboxPanel.visible.value" class="sandbox-header-toggle">+ <t-tooltip placement="bottom">+ <template #content>{{ t('chatHeader.toggleSandboxPanel') }}</template>+ <button type="button" class="sandbox-header-toggle__btn"+ :aria-label="t('chatHeader.toggleSandboxPanel')" @click="sandboxPanel.open()">+ <svg viewBox="0 0 20 20" width="18" height="18" fill="none" xmlns="http://www.w3.org/2000/svg"+ aria-hidden="true">+ <rect x="1.5" y="1.5" width="17" height="17" rx="3" stroke="currentColor" stroke-width="1.2" />+ <line x1="12.5" y1="1.5" x2="12.5" y2="18.5" stroke="currentColor" stroke-width="1.2" />+ <line x1="16" y1="7.5" x2="16" y2="12.5" stroke="currentColor" stroke-width="1.2"+ stroke-linecap="round" />+ </svg>+ </button>+ </t-tooltip>+ </div><div class="chat_thread"><div ref="scrollContainer" class="chat_scroll_box" @scroll="handleScroll"><div class="msg_list" :class="{ 'is-embedded': embeddedMode }">@@ -136,6 +153,11 @@@update:visible="(val) => val ? null : uiStore.closeKBEditor()" @success="handleKBEditorSuccess" /><ChatReferencesDrawer /><ChatAttachmentPreviewDrawer />+ <SandboxSidePanel v-if="!embeddedMode" :session-id="session_id"+ :agent-id="useSettingsStoreInstance.selectedAgentId"+ :agent-source-tenant-id="useSettingsStoreInstance.selectedAgentSourceTenantId"+ :shifted="referencesDrawerVisible"+ :artifacts="sessionArtifacts" :artifacts-collecting="sessionArtifactsCollecting" /></template><script setup>import { storeToRefs } from 'pinia';@@ -177,8 +199,13 @@ import {import { provideChatReferencesDrawer } from '@/composables/useChatReferencesDrawer';import { provideChatAttachmentPreviewDrawer } from '@/composables/useChatAttachmentPreviewDrawer';import { useSessionActivityStore } from '@/stores/sessionActivity';+import { provideChatSandboxPanel } from '@/composables/useChatSandboxPanel';+import SandboxSidePanel from '@/components/chat/SandboxSidePanel.vue';+import { collectSessionArtifacts } from '@/utils/sessionArtifacts';+import { isCollectingSkillArtifacts } from '@/utils/skillArtifacts';const referencesDrawer = provideChatReferencesDrawer();provideChatAttachmentPreviewDrawer();+const sandboxPanel = provideChatSandboxPanel();const { visible: referencesDrawerVisible } = referencesDrawer;const props = defineProps({@@ -258,6 +285,10 @@ const inputFieldRef = ref();const created_at = ref('');const limit = ref(20);const messagesList = reactive([]);+const sessionArtifacts = computed(() => collectSessionArtifacts(messagesList));+const sessionArtifactsCollecting = computed(() =>+ messagesList.some((message) => isCollectingSkillArtifacts(message)),+);const isReplying = ref(false);const currentAssistantMessageId = ref(''); // 当前正在生成的 assistant message ID// True only while attaching to an in-flight *IM-originated* reply via continue-stream.@@ -1096,6 +1127,8 @@ onBeforeRouteUpdate((to, from, next) => {font-size: 20px;// 右侧不留 padding,滚动条贴到内容区最右缘padding: 0 0 20px 20px;+ // 右侧抽屉让出的宽度。回到底部按钮按「剩余聊天列」居中,而不是整页 50%。+ --chat-right-inset: 0px;box-sizing: border-box;flex: 1;// The parent .platform-route-outlet is a flex column with min-height:0@@ -1129,12 +1162,39 @@ onBeforeRouteUpdate((to, from, next) => {&.has-references-panel:not(.is-embedded) {@media (min-width: 960px) {+ --chat-right-inset: 420px;padding-right: 420px;box-sizing: border-box;.chat_scroll_box {padding-top: 0;}++ .sandbox-header-toggle {+ right: 432px;+ }+ }+ }++ // 沙箱可视化右侧面板:宽度可拖拽调整(--sandbox-panel-width 由+ // composable 持久化),聊天区 padding 跟随面板宽度让位。+ &.has-sandbox-panel:not(.is-embedded) {+ @media (min-width: 960px) {+ --chat-right-inset: var(--sandbox-panel-width, 420px);+ padding-right: var(--sandbox-panel-width, 420px);+ box-sizing: border-box;+ }+ }++ &.has-sandbox-panel.has-references-panel:not(.is-embedded) {+ @media (min-width: 1400px) {+ --chat-right-inset: calc(420px + var(--sandbox-panel-width, 420px));+ padding-right: calc(420px + var(--sandbox-panel-width, 420px));+ }++ @media (max-width: 1399.98px) and (min-width: 960px) {+ --chat-right-inset: var(--sandbox-panel-width, 420px);+ padding-right: var(--sandbox-panel-width, 420px);}}@@ -1178,6 +1238,48 @@ onBeforeRouteUpdate((to, from, next) => {overflow: hidden;}+// 沙箱面板入口:chrome 对齐会话左上角三个点(毛玻璃底 + 24px 图标按钮),+// 图标是左侧栏 sidebar-toggle 的水平镜像(栏在右侧)。+.sandbox-header-toggle {+ position: absolute;+ top: 10px;+ right: 12px;+ z-index: 6;+ display: inline-flex;+ align-items: center;+ padding: 2px;+ border-radius: 8px;+ box-sizing: border-box;+ background: color-mix(in srgb, var(--td-bg-color-container) 88%, transparent);+ backdrop-filter: blur(8px);+ -webkit-backdrop-filter: blur(8px);+ pointer-events: auto;+}++.sandbox-header-toggle__btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 24px;+ height: 24px;+ padding: 0;+ border: 0;+ border-radius: 5px;+ color: var(--td-text-color-placeholder);+ background: transparent;+ cursor: pointer;+ transition: background-color 0.15s ease, color 0.15s ease;++ &:hover {+ color: var(--td-text-color-primary);+ background: var(--td-bg-color-container-hover);+ }++ &:active {+ background: var(--td-bg-color-container-active);+ }+}+.chat_scroll_box {flex: 1;min-height: 0;@@ -1207,7 +1309,7 @@ onBeforeRouteUpdate((to, from, next) => {.scroll-to-bottom-btn {position: absolute;- left: 50%;+ left: calc((100% - var(--chat-right-inset, 0px)) / 2);transform: translateX(-50%);bottom: 140px;z-index: 10;@@ -1222,7 +1324,7 @@ onBeforeRouteUpdate((to, from, next) => {justify-content: center;cursor: pointer;color: var(--td-text-color-secondary);- transition: all 0.2s ease;+ transition: left 0.3s cubic-bezier(0.22, 0.61, 0.36, 1), background-color 0.2s ease, color 0.2s ease, box-shadow 0.2s ease;&:hover {background: var(--td-bg-color-container-hover);diff --git a/frontend/vite.config.ts b/frontend/vite.config.tsindex 7b9a7bbc9..5c39b94d3 100644--- a/frontend/vite.config.ts+++ b/frontend/vite.config.ts@@ -136,6 +136,9 @@ export default defineConfig({target: DEV_PROXY_TARGET,changeOrigin: true,secure: false,+ // 沙箱终端等 WebSocket 升级请求也走 /api,必须开启 WS 转发,+ // 否则浏览器侧握手失败、前端表现为"一直正在连接"。+ ws: true,},'/files': {target: DEV_PROXY_TARGET,@@ -155,6 +158,7 @@ export default defineConfig({target: DEV_PROXY_TARGET,changeOrigin: true,secure: false,+ ws: true,},'/files': {target: DEV_PROXY_TARGET,diff --git a/internal/application/repository/user.go b/internal/application/repository/user.goindex b52740c60..ba8081e20 100644--- a/internal/application/repository/user.go+++ b/internal/application/repository/user.go@@ -305,6 +305,18 @@ func (r *authTokenRepository) GetTokenByValue(ctx context.Context, tokenValue streturn &token, nil}+// GetTokenByID gets a token by its primary key+func (r *authTokenRepository) GetTokenByID(ctx context.Context, id string) (*types.AuthToken, error) {+ var token types.AuthToken+ if err := r.db.WithContext(ctx).Where("id = ?", id).First(&token).Error; err != nil {+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return nil, ErrTokenNotFound+ }+ return nil, err+ }+ return &token, nil+}+// GetTokensByUserID gets all tokens for a userfunc (r *authTokenRepository) GetTokensByUserID(ctx context.Context, userID string) ([]*types.AuthToken, error) {var tokens []*types.AuthTokendiff --git a/internal/application/service/sandbox_terminal_auth.go b/internal/application/service/sandbox_terminal_auth.gonew file mode 100644index 000000000..b4bb84388--- /dev/null+++ b/internal/application/service/sandbox_terminal_auth.go@@ -0,0 +1,188 @@+package service++import (+ "context"+ "errors"+ "strings"+ "time"++ apprepo "github.com/Tencent/WeKnora/internal/application/repository"+ apperrors "github.com/Tencent/WeKnora/internal/errors"+ "github.com/Tencent/WeKnora/internal/types"+ "github.com/Tencent/WeKnora/internal/types/interfaces"+)++// ErrTerminalAuthDenied is a definite authorization failure for an open+// sandbox terminal: the minting access token is gone or revoked, the user+// is inactive or deleted, membership was removed, or the session is no+// longer owned.+//+// Every other error is a lookup failure and is returned as-is. The+// distinction matters: this runs on a timer against every open terminal, so+// treating a database hiccup as "denied" would disconnect the whole fleet at+// once and then have it all reconnect together. The middleware takes the+// same stance (see resolveTenantRole's membership lookup).+var ErrTerminalAuthDenied = errors.New("terminal authorization no longer valid")++// CheckSandboxTerminalAuth re-validates the identity that opened a PTY and+// returns the resolved user, so the handshake can install the auth session+// without looking the user up a second time.+//+// Call it before the upgrade and periodically on the live bridge; using the+// one function for both is deliberate, so a live terminal is held to exactly+// the checks that admitted it — except token expiry. Handshake minting and+// the upgrade still require a non-expired access token; the live recheck+// does not, because axios silently rotates access tokens without revoking+// the row the ticket was bound to. Logout / password reset still revoke+// every row and tear the PTY down.+//+// rejectExpired is true for the handshake and false for the open-PTY timer.+func CheckSandboxTerminalAuth(+ ctx context.Context,+ users interfaces.UserService,+ members interfaces.TenantMemberService,+ sessions interfaces.SessionService,+ claims SandboxTerminalTicketClaims,+ rbacEnforced bool,+ rejectExpired bool,+) (*types.User, error) {+ if users == nil || members == nil || sessions == nil {+ return nil, ErrTerminalAuthDenied+ }+ userID := strings.TrimSpace(claims.UserID)+ sessionID := strings.TrimSpace(claims.SessionID)+ tokenID := strings.TrimSpace(claims.TokenID)+ if userID == "" || sessionID == "" || tokenID == "" || claims.TenantID == 0 {+ return nil, ErrTerminalAuthDenied+ }++ token, err := users.GetAccessTokenByID(ctx, tokenID)+ if err != nil {+ if errors.Is(err, apprepo.ErrTokenNotFound) {+ return nil, ErrTerminalAuthDenied+ }+ return nil, err+ }+ if token == nil {+ return nil, ErrTerminalAuthDenied+ }+ if err := AssertAccessTokenNotRevoked(token, userID); err != nil {+ return nil, err+ }+ if rejectExpired {+ if err := assertAccessTokenNotExpired(token, time.Now()); err != nil {+ return nil, err+ }+ }++ user, err := users.GetUserByID(ctx, userID)+ if err != nil {+ if errors.Is(err, apprepo.ErrUserNotFound) {+ return nil, ErrTerminalAuthDenied+ }+ return nil, err+ }+ if user == nil || !user.IsActive {+ return nil, ErrTerminalAuthDenied+ }++ if err := terminalMembershipStillValid(ctx, members, user, claims.TenantID, rbacEnforced); err != nil {+ return nil, err+ }++ ownedCtx := sandboxTerminalAuthContext(ctx, userID, claims.TenantID)+ if _, err := sessions.GetOwnedSession(ownedCtx, sessionID); err != nil {+ if errors.Is(err, apperrors.ErrSessionNotFound) {+ return nil, ErrTerminalAuthDenied+ }+ return nil, err+ }+ return user, nil+}++// AssertAccessTokenNotRevoked reports whether a stored access-token row is+// still the minting credential for userID (right owner and type, not+// revoked). Expiry is checked separately: a live PTY must survive silent+// access-token rotation, while minting a new ticket still requires a+// current token.+func AssertAccessTokenNotRevoked(token *types.AuthToken, userID string) error {+ if token == nil {+ return ErrTerminalAuthDenied+ }+ if strings.TrimSpace(token.UserID) != userID {+ return ErrTerminalAuthDenied+ }+ if token.TokenType != "access_token" {+ return ErrTerminalAuthDenied+ }+ if token.IsRevoked {+ return ErrTerminalAuthDenied+ }+ return nil+}++func assertAccessTokenNotExpired(token *types.AuthToken, now time.Time) error {+ if token == nil {+ return ErrTerminalAuthDenied+ }+ if !token.ExpiresAt.IsZero() && !token.ExpiresAt.After(now) {+ return ErrTerminalAuthDenied+ }+ return nil+}++// AssertAccessTokenStillActive is the minting check: not revoked and not+// expired. The handshake ticket POST uses this so a stale Bearer token+// cannot open a new PTY.+func AssertAccessTokenStillActive(token *types.AuthToken, userID string, now time.Time) error {+ if err := AssertAccessTokenNotRevoked(token, userID); err != nil {+ return err+ }+ return assertAccessTokenNotExpired(token, now)+}++// terminalMembershipStillValid answers "may this user still act in this+// workspace", the recheck counterpart to middleware.resolveTenantRole.+//+// The two are deliberately NOT shared. resolveTenantRole derives a role for a+// fresh request and self-heals (it can auto-promote the owner of an orphan+// workspace, writing a tenant_members row); a recheck on a live socket must+// only observe, never grant. What the two do share — active membership,+// superuser bypass, and the RBAC fail-open switch — is kept in step here on+// purpose, so change both if that policy moves.+//+// Where they differ, this one is the more permissive: the handshake already+// passed the middleware, so a recheck that is stricter would kill sessions+// the middleware just admitted.+func terminalMembershipStillValid(+ ctx context.Context,+ members interfaces.TenantMemberService,+ user *types.User,+ tenantID uint64,+ rbacEnforced bool,+) error {+ member, err := members.GetMembership(ctx, user.ID, tenantID)+ if err != nil {+ return err+ }+ if member != nil && member.Status == types.TenantMemberStatusActive {+ return nil+ }+ if user.CanAccessAllTenants {+ return nil+ }+ if !rbacEnforced {+ return nil+ }+ return ErrTerminalAuthDenied+}++func sandboxTerminalAuthContext(parent context.Context, userID string, tenantID uint64) context.Context {+ ctx := parent+ if ctx == nil {+ ctx = context.Background()+ }+ ctx = context.WithValue(ctx, types.UserIDContextKey, userID)+ ctx = context.WithValue(ctx, types.TenantIDContextKey, tenantID)+ return types.WithPrincipal(ctx, types.Principal{Type: types.PrincipalWebUser, ID: userID})+}diff --git a/internal/application/service/sandbox_terminal_auth_test.go b/internal/application/service/sandbox_terminal_auth_test.gonew file mode 100644index 000000000..e98fac060--- /dev/null+++ b/internal/application/service/sandbox_terminal_auth_test.go@@ -0,0 +1,283 @@+package service++import (+ "context"+ "errors"+ "testing"+ "time"++ "github.com/stretchr/testify/require"++ apprepo "github.com/Tencent/WeKnora/internal/application/repository"+ apperrors "github.com/Tencent/WeKnora/internal/errors"+ "github.com/Tencent/WeKnora/internal/types"+ "github.com/Tencent/WeKnora/internal/types/interfaces"+)++type terminalAuthUserStub struct {+ interfaces.UserService+ user *types.User+ token *types.AuthToken+ // userFail / tokenFail stand in for a database that is momentarily+ // unreachable, as opposed to a row that is genuinely gone.+ userFail error+ tokenFail error+}++func (s *terminalAuthUserStub) GetUserByID(context.Context, string) (*types.User, error) {+ if s.userFail != nil {+ return nil, s.userFail+ }+ if s.user == nil {+ return nil, apprepo.ErrUserNotFound+ }+ return s.user, nil+}++func (s *terminalAuthUserStub) GetAccessTokenByID(context.Context, string) (*types.AuthToken, error) {+ if s.tokenFail != nil {+ return nil, s.tokenFail+ }+ if s.token == nil {+ return nil, apprepo.ErrTokenNotFound+ }+ return s.token, nil+}++type terminalAuthMemberStub struct {+ interfaces.TenantMemberService+ member *types.TenantMember+ fail error+}++func (s *terminalAuthMemberStub) GetMembership(context.Context, string, uint64) (*types.TenantMember, error) {+ if s.fail != nil {+ return nil, s.fail+ }+ return s.member, nil+}++type terminalAuthSessionStub struct {+ interfaces.SessionService+ err error+}++func (s *terminalAuthSessionStub) GetOwnedSession(context.Context, string) (*types.Session, error) {+ if s.err != nil {+ return nil, s.err+ }+ return &types.Session{ID: "sess-9"}, nil+}++func validTerminalAuthInputs() (+ *terminalAuthUserStub,+ *terminalAuthMemberStub,+ *terminalAuthSessionStub,+ SandboxTerminalTicketClaims,+) {+ users := &terminalAuthUserStub{+ user: &types.User{ID: "user-1", IsActive: true},+ token: &types.AuthToken{+ ID: "tok-abc",+ UserID: "user-1",+ TokenType: "access_token",+ ExpiresAt: time.Now().Add(time.Hour),+ },+ }+ members := &terminalAuthMemberStub{+ member: &types.TenantMember{+ UserID: "user-1",+ TenantID: 42,+ Status: types.TenantMemberStatusActive,+ },+ }+ sessions := &terminalAuthSessionStub{}+ claims := SandboxTerminalTicketClaims{+ UserID: "user-1",+ TenantID: 42,+ SessionID: "sess-9",+ TokenID: "tok-abc",+ }+ return users, members, sessions, claims+}++func handshakeAuth(+ users interfaces.UserService,+ members interfaces.TenantMemberService,+ sessions interfaces.SessionService,+ claims SandboxTerminalTicketClaims,+ rbacEnforced bool,+) (*types.User, error) {+ return CheckSandboxTerminalAuth(context.Background(), users, members, sessions, claims, rbacEnforced, true)+}++func TestCheckSandboxTerminalAuthAllowsCurrentIdentity(t *testing.T) {+ users, members, sessions, claims := validTerminalAuthInputs()+ user, err := handshakeAuth(users, members, sessions, claims, true)+ require.NoError(t, err)+ // The handshake installs its auth session from this user rather than+ // looking it up again.+ require.NotNil(t, user)+ require.Equal(t, "user-1", user.ID)+}++func TestCheckSandboxTerminalAuthDeniesRevokedToken(t *testing.T) {+ users, members, sessions, claims := validTerminalAuthInputs()+ users.token.IsRevoked = true+ _, err := handshakeAuth(users, members, sessions, claims, true)+ require.ErrorIs(t, err, ErrTerminalAuthDenied)+}++func TestCheckSandboxTerminalAuthDeniesExpiredToken(t *testing.T) {+ users, members, sessions, claims := validTerminalAuthInputs()+ users.token.ExpiresAt = time.Now().Add(-time.Minute)+ _, err := handshakeAuth(users, members, sessions, claims, true)+ require.ErrorIs(t, err, ErrTerminalAuthDenied)+}++// Silent access-token rotation leaves the minting row expired but unrevoked.+// The open PTY must not treat that as logout.+func TestCheckSandboxTerminalAuthRecheckAllowsExpiredUnrevokedToken(t *testing.T) {+ users, members, sessions, claims := validTerminalAuthInputs()+ users.token.ExpiresAt = time.Now().Add(-time.Minute)+ user, err := CheckSandboxTerminalAuth(context.Background(), users, members, sessions, claims, true, false)+ require.NoError(t, err)+ require.Equal(t, "user-1", user.ID)+}++func TestCheckSandboxTerminalAuthRecheckStillDeniesRevokedToken(t *testing.T) {+ users, members, sessions, claims := validTerminalAuthInputs()+ users.token.IsRevoked = true+ users.token.ExpiresAt = time.Now().Add(-time.Minute)+ _, err := CheckSandboxTerminalAuth(context.Background(), users, members, sessions, claims, true, false)+ require.ErrorIs(t, err, ErrTerminalAuthDenied)+}++func TestCheckSandboxTerminalAuthDeniesTokenOwnedBySomeoneElse(t *testing.T) {+ users, members, sessions, claims := validTerminalAuthInputs()+ users.token.UserID = "other-user"+ _, err := handshakeAuth(users, members, sessions, claims, true)+ require.ErrorIs(t, err, ErrTerminalAuthDenied)+}++func TestCheckSandboxTerminalAuthDeniesRefreshToken(t *testing.T) {+ users, members, sessions, claims := validTerminalAuthInputs()+ users.token.TokenType = "refresh_token"+ _, err := handshakeAuth(users, members, sessions, claims, true)+ require.ErrorIs(t, err, ErrTerminalAuthDenied)+}++func TestCheckSandboxTerminalAuthDeniesMissingToken(t *testing.T) {+ users, members, sessions, claims := validTerminalAuthInputs()+ users.token = nil+ _, err := handshakeAuth(users, members, sessions, claims, true)+ require.ErrorIs(t, err, ErrTerminalAuthDenied)+}++func TestCheckSandboxTerminalAuthDeniesDeletedUser(t *testing.T) {+ users, members, sessions, claims := validTerminalAuthInputs()+ users.user = nil+ _, err := handshakeAuth(users, members, sessions, claims, true)+ require.ErrorIs(t, err, ErrTerminalAuthDenied)+}++// A database that is briefly unreachable must not read as "access revoked":+// the recheck runs on a timer against every open terminal, so a fail-closed+// lookup would disconnect all of them at once.+func TestCheckSandboxTerminalAuthPropagatesTokenLookupError(t *testing.T) {+ users, members, sessions, claims := validTerminalAuthInputs()+ lookupErr := errors.New("auth_tokens db down")+ users.tokenFail = lookupErr+ _, err := handshakeAuth(users, members, sessions, claims, true)+ require.ErrorIs(t, err, lookupErr)+ require.False(t, errors.Is(err, ErrTerminalAuthDenied))+}++func TestCheckSandboxTerminalAuthPropagatesUserLookupError(t *testing.T) {+ users, members, sessions, claims := validTerminalAuthInputs()+ lookupErr := errors.New("users db down")+ users.userFail = lookupErr+ _, err := handshakeAuth(users, members, sessions, claims, true)+ require.ErrorIs(t, err, lookupErr)+ require.False(t, errors.Is(err, ErrTerminalAuthDenied))+}++func TestCheckSandboxTerminalAuthPropagatesSessionLookupError(t *testing.T) {+ users, members, sessions, claims := validTerminalAuthInputs()+ lookupErr := errors.New("sessions db down")+ sessions.err = lookupErr+ _, err := handshakeAuth(users, members, sessions, claims, true)+ require.ErrorIs(t, err, lookupErr)+ require.False(t, errors.Is(err, ErrTerminalAuthDenied))+}++func TestCheckSandboxTerminalAuthDeniesInactiveUser(t *testing.T) {+ users, members, sessions, claims := validTerminalAuthInputs()+ users.user.IsActive = false+ _, err := handshakeAuth(users, members, sessions, claims, true)+ require.ErrorIs(t, err, ErrTerminalAuthDenied)+}++func TestCheckSandboxTerminalAuthDeniesMissingMembershipWhenRBACOn(t *testing.T) {+ users, members, sessions, claims := validTerminalAuthInputs()+ members.member = nil+ _, err := handshakeAuth(users, members, sessions, claims, true)+ require.ErrorIs(t, err, ErrTerminalAuthDenied)+}++func TestCheckSandboxTerminalAuthAllowsMissingMembershipWhenRBACOff(t *testing.T) {+ users, members, sessions, claims := validTerminalAuthInputs()+ members.member = nil+ _, err := handshakeAuth(users, members, sessions, claims, false)+ require.NoError(t, err)+}++func TestCheckSandboxTerminalAuthAllowsSuperuserWithoutMembership(t *testing.T) {+ users, members, sessions, claims := validTerminalAuthInputs()+ users.user.CanAccessAllTenants = true+ members.member = nil+ _, err := handshakeAuth(users, members, sessions, claims, true)+ require.NoError(t, err)+}++func TestCheckSandboxTerminalAuthDeniesSuspendedMembership(t *testing.T) {+ users, members, sessions, claims := validTerminalAuthInputs()+ members.member.Status = types.TenantMemberStatusSuspended+ _, err := handshakeAuth(users, members, sessions, claims, true)+ require.ErrorIs(t, err, ErrTerminalAuthDenied)+}++func TestCheckSandboxTerminalAuthPropagatesMembershipLookupError(t *testing.T) {+ users, members, sessions, claims := validTerminalAuthInputs()+ lookupErr := errors.New("membership db down")+ members.fail = lookupErr+ _, err := handshakeAuth(users, members, sessions, claims, true)+ require.ErrorIs(t, err, lookupErr)+ require.False(t, errors.Is(err, ErrTerminalAuthDenied))+}++func TestCheckSandboxTerminalAuthDeniesDeletedSession(t *testing.T) {+ users, members, sessions, claims := validTerminalAuthInputs()+ sessions.err = apperrors.ErrSessionNotFound+ _, err := handshakeAuth(users, members, sessions, claims, true)+ require.ErrorIs(t, err, ErrTerminalAuthDenied)+}++func TestAccessTokenStillActive(t *testing.T) {+ now := time.Date(2026, 9, 4, 12, 0, 0, 0, time.UTC)+ live := &types.AuthToken{+ ID: "tok-1",+ UserID: "user-1",+ TokenType: "access_token",+ ExpiresAt: now.Add(time.Hour),+ }+ require.NoError(t, AssertAccessTokenStillActive(live, "user-1", now))++ revoked := *live+ revoked.IsRevoked = true+ require.ErrorIs(t, AssertAccessTokenStillActive(&revoked, "user-1", now), ErrTerminalAuthDenied)++ expired := *live+ expired.ExpiresAt = now+ require.ErrorIs(t, AssertAccessTokenStillActive(&expired, "user-1", now), ErrTerminalAuthDenied)+}diff --git a/internal/application/service/sandbox_terminal_service.go b/internal/application/service/sandbox_terminal_service.gonew file mode 100644index 000000000..e8dc98ade--- /dev/null+++ b/internal/application/service/sandbox_terminal_service.go@@ -0,0 +1,256 @@+// Package service: session sandbox terminal.+//+// The interactive terminal is a lookup-only entry point into the sandbox+// bound to a session: it resolves the session's pinned config exactly like+// artifact collection does (never "whatever the agent points at today"),+// refuses to provision when no live sandbox exists, and hands a provider-+// neutral PTY handle to the WebSocket layer.+package service++import (+ "context"+ "errors"+ "strings"+ "time"++ "github.com/Tencent/WeKnora/internal/logger"+ "github.com/Tencent/WeKnora/internal/sandbox"+ "github.com/Tencent/WeKnora/internal/types"+)++// SessionTerminal bundles an opened PTY with the backend that serves it, so+// the WebSocket layer can include the backend in its ready frame.+type SessionTerminal struct {+ Session sandbox.RemoteTerminalSession+ Backend string+ // IdleDisconnect is how long the bridge should wait without PTY+ // activity before closing the socket. Always a positive duration.+ IdleDisconnect time.Duration+}++// SandboxTerminalService opens interactive terminals on session sandboxes.+type SandboxTerminalService struct {+ pinner *SessionSandboxPinner+ resolver sandbox.TenantSandboxResolver+ fallback sandbox.Manager+ policy WorkspaceSandboxPolicy+}++// NewSandboxTerminalService wires the terminal service. All dependencies+// are optional individually; with no pinner the service reports "no live+// sandbox" for every session.+func NewSandboxTerminalService(+ pinner *SessionSandboxPinner,+ resolver sandbox.TenantSandboxResolver,+ fallback sandbox.Manager,+ policy WorkspaceSandboxPolicy,+) *SandboxTerminalService {+ return &SandboxTerminalService{+ pinner: pinner,+ resolver: resolver,+ fallback: fallback,+ policy: policy,+ }+}++// OpenSessionTerminal attaches to the session's currently bound sandbox+// without ever creating or rebuilding one. This is the path a page load and+// an automatic reconnect take: opening a panel must not conjure a microVM.+//+// When the session has no live sandbox it reports+// sandbox.ErrNoLiveSessionSandbox, which the WebSocket handler turns into+// the SANDBOX_NOT_BOUND frame the UI answers with an explicit "create and+// start" button. That confirmed click is what calls EnsureSessionTerminal.+//+// Error contract (the WebSocket handler maps these onto protocol error+// frames):+// - sandbox.ErrNoLiveSessionSandbox — the session has no bound sandbox.+// - ErrTerminalUnsupported — the resolved backend cannot stream PTYs+// (Docker, disabled manager).+// - any other error — resolution or provider failure.+func (s *SandboxTerminalService) OpenSessionTerminal(+ ctx context.Context,+ sessionID string,+ opts sandbox.RemoteTerminalOptions,+) (*SessionTerminal, error) {+ mgr, _, err := s.resolveSessionManager(ctx, sessionID)+ if err != nil {+ return nil, err+ }+ return s.openOnManager(ctx, mgr, sessionID, opts)+}++// resolveSessionManager mirrors ArtifactCollector.sessionSource: pin first,+// never the agent's current choice.+func (s *SandboxTerminalService) resolveSessionManager(+ ctx context.Context,+ sessionID string,+) (sandbox.Manager, string, error) {+ if s.pinner == nil {+ return nil, "", sandbox.ErrNoLiveSessionSandbox+ }+ configID, err := s.pinner.Read(ctx, sessionID)+ if err != nil {+ return nil, "", err+ }+ if configID == "" {+ return nil, "", sandbox.ErrNoLiveSessionSandbox+ }+ tenantID, _ := types.TenantIDFromContext(ctx)+ mgr, err := resolveTenantSandboxForConfig(+ ctx, s.resolver, s.fallback, tenantID, configID, s.policy,+ )+ if err != nil {+ return nil, configID, err+ }+ if mgr == nil {+ return nil, configID, sandbox.ErrNoLiveSessionSandbox+ }+ return mgr, configID, nil+}++// EnsureSessionTerminal opens a PTY on the session's sandbox, provisioning+// one when the session has none and the caller supplies a sandbox config ID.+//+// Only call this for a confirmed user action. It creates and bills real+// infrastructure, so the lookup-only OpenSessionTerminal is what a page load+// or a background reconnect must use.+//+// Provisioning reuses the exact chat-flow path — the resolved agent's sandbox+// config, the workspace kill switch, and the pin claim in+// resolveSandboxForExecution — so a terminal-created sandbox is+// indistinguishable from one created by a conversation turn. The WebSocket+// handler must resolve the agent the same way a chat turn does (own agent+// or shared agent from another workspace) and pass that config ID here.+// A no-op shell command drives the lazy creation, which also seeds the+// workspace layout.+//+// With no sandboxConfigID the call stays lookup-only and reports+// sandbox.ErrNoLiveSessionSandbox, which the WebSocket handler maps onto+// the SANDBOX_NOT_BOUND guidance frame.+func (s *SandboxTerminalService) EnsureSessionTerminal(+ ctx context.Context,+ sessionID string,+ sandboxConfigID string,+ opts sandbox.RemoteTerminalOptions,+) (*SessionTerminal, error) {+ mgr, _, err := s.resolveSessionManager(ctx, sessionID)+ if err == nil {+ terminal, terr := s.openOnManager(ctx, mgr, sessionID, opts)+ if terr == nil {+ return terminal, nil+ }+ // The pin names the config but the sandbox itself is gone+ // (reclaimed or paused out of band). The config context is right+ // here, so rebuild on it instead of treating the session as+ // sandbox-less and asking the caller for an agent.+ if errors.Is(terr, sandbox.ErrNoLiveSessionSandbox) {+ if perr := s.provisionOnManager(ctx, mgr, sessionID); perr == nil {+ if terminal, retryErr := s.openOnManager(ctx, mgr, sessionID, opts); retryErr == nil {+ return terminal, nil+ } else {+ terr = retryErr+ }+ }+ }+ return nil, terr+ }+ if !errors.Is(err, sandbox.ErrNoLiveSessionSandbox) || strings.TrimSpace(sandboxConfigID) == "" {+ return nil, err+ }++ tenantID, _ := types.TenantIDFromContext(ctx)+ mgr, _, err = resolveSandboxForExecution(+ ctx, s.resolver, s.fallback, s.pinner, tenantID, sessionID, strings.TrimSpace(sandboxConfigID), s.policy,+ )+ if err != nil {+ return nil, err+ }+ if mgr == nil || mgr.GetType() == sandbox.SandboxTypeDisabled {+ return nil, sandbox.ErrNoLiveSessionSandbox+ }++ // Drive the lazy session-sandbox creation with a no-op command. This+ // provisions the sandbox AND pins it, exactly like the first agent turn+ // would.+ if err := s.provisionOnManager(ctx, mgr, sessionID); err != nil {+ return nil, err+ }++ return s.openOnManager(ctx, mgr, sessionID, opts)+}++// provisionOnManager drives the manager's lazy session-sandbox creation with+// a no-op shell command. The command both provisions the sandbox and seeds the+// workspace layout, matching what the first agent turn does.+func (s *SandboxTerminalService) provisionOnManager(+ ctx context.Context,+ mgr sandbox.Manager,+ sessionID string,+) error {+ executor, ok := mgr.(sandbox.SessionShellExecutor)+ if !ok {+ // No shell executor means the backend cannot provision (Docker as a+ // session backend, disabled manager): report "no live sandbox"+ // rather than a confusing provisioning failure.+ return sandbox.ErrNoLiveSessionSandbox+ }+ if _, err := executor.ExecShellCommand(ctx, sessionID, "true", "", 60*time.Second, nil); err != nil {+ logger.Warnf(ctx, "[sandbox-terminal] provision sandbox for session %s failed: %v", sessionID, err)+ return err+ }+ return nil+}++// openOnManager opens a terminal on an already-resolved manager.+func (s *SandboxTerminalService) openOnManager(+ ctx context.Context,+ mgr sandbox.Manager,+ sessionID string,+ opts sandbox.RemoteTerminalOptions,+) (*SessionTerminal, error) {+ terminal, ok := terminalManagerFromManager(mgr)+ if !ok {+ logger.Warnf(ctx,+ "[sandbox-terminal] backend %s does not support terminals (session %s)",+ mgr.GetType(), sessionID)+ return nil, ErrTerminalUnsupported+ }+ session, err := terminal.OpenSessionTerminal(ctx, sessionID, opts)+ if err != nil {+ return nil, err+ }+ return &SessionTerminal{+ Session: session,+ Backend: string(mgr.GetType()),+ IdleDisconnect: terminalIdleDisconnectFromManager(mgr),+ }, nil+}++func terminalIdleDisconnectFromManager(mgr sandbox.Manager) time.Duration {+ type idleSource interface {+ TerminalIdleDisconnect() time.Duration+ }+ if src, ok := mgr.(idleSource); ok {+ return src.TerminalIdleDisconnect()+ }+ return sandbox.DefaultTerminalIdleDisconnect+}++// terminalManagerFromManager narrows a manager to its terminal capability.+func terminalManagerFromManager(mgr sandbox.Manager) (sandbox.SessionTerminalManager, bool) {+ provider, ok := mgr.(sandbox.SessionTerminalProvider)+ if !ok {+ return nil, false+ }+ terminal := provider.SessionTerminalManager()+ if terminal == nil {+ return nil, false+ }+ return terminal, true+}++// ErrTerminalUnsupported reports that the session's sandbox backend cannot+// serve interactive terminals. Same sentinel as sandbox.ErrTerminalUnsupported+// so errors.Is matches either name.+var ErrTerminalUnsupported = sandbox.ErrTerminalUnsupporteddiff --git a/internal/application/service/sandbox_terminal_service_test.go b/internal/application/service/sandbox_terminal_service_test.gonew file mode 100644index 000000000..6c67715ba--- /dev/null+++ b/internal/application/service/sandbox_terminal_service_test.go@@ -0,0 +1,26 @@+package service++import (+ "context"+ "testing"++ "github.com/stretchr/testify/require"++ "github.com/Tencent/WeKnora/internal/sandbox"+ "github.com/Tencent/WeKnora/internal/types"+)++// Opening the terminal panel issues a GET, and a GET must not create billable+// infrastructure. OpenSessionTerminal is the path a page load and a background+// reconnect take, so it must stop at "no live sandbox". A confirmed click+// without a resolved sandbox config ID stays lookup-only as well.+func TestOpenSessionTerminalNeverReachesProvisioning(t *testing.T) {+ svc := NewSandboxTerminalService(nil, nil, nil, nil)+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(42))++ _, err := svc.OpenSessionTerminal(ctx, "sess-1", sandbox.RemoteTerminalOptions{})+ require.ErrorIs(t, err, sandbox.ErrNoLiveSessionSandbox)++ _, err = svc.EnsureSessionTerminal(ctx, "sess-1", "", sandbox.RemoteTerminalOptions{})+ require.ErrorIs(t, err, sandbox.ErrNoLiveSessionSandbox)+}diff --git a/internal/application/service/sandbox_terminal_ticket.go b/internal/application/service/sandbox_terminal_ticket.gonew file mode 100644index 000000000..a4c86a591--- /dev/null+++ b/internal/application/service/sandbox_terminal_ticket.go@@ -0,0 +1,92 @@+package service++import (+ "errors"+ "fmt"+ "strings"+ "time"++ "github.com/golang-jwt/jwt/v5"+)++const (+ sandboxTerminalTicketType = "sandbox_terminal"+ // DefaultSandboxTerminalTicketTTL is long enough for the WebSocket+ // handshake, short enough that a leaked query string is not a 24h+ // session. After upgrade the ticket itself is discarded; the open PTY+ // rechecks the bound access-token id instead.+ DefaultSandboxTerminalTicketTTL = 2 * time.Minute+)++// SandboxTerminalTicketClaims is the handshake identity bound to one session.+// TokenID is the auth_tokens.id of the access JWT that minted the ticket;+// the open PTY rechecks that row so logout / revocation tear the bridge down.+type SandboxTerminalTicketClaims struct {+ UserID string+ TenantID uint64+ SessionID string+ TokenID string+}++// IssueSandboxTerminalTicket mints a short-lived JWT for the browser+// WebSocket handshake. It is not an access token: ValidateToken rejects it.+func IssueSandboxTerminalTicket(userID string, tenantID uint64, sessionID, tokenID string, ttl time.Duration) (string, error) {+ userID = strings.TrimSpace(userID)+ sessionID = strings.TrimSpace(sessionID)+ tokenID = strings.TrimSpace(tokenID)+ if userID == "" || sessionID == "" || tokenID == "" || tenantID == 0 {+ return "", errors.New("sandbox terminal ticket requires user, tenant, session, and access token")+ }+ if ttl <= 0 {+ ttl = DefaultSandboxTerminalTicketTTL+ }+ token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{+ "user_id": userID,+ "tenant_id": tenantID,+ "session_id": sessionID,+ "token_id": tokenID,+ "type": sandboxTerminalTicketType,+ "exp": time.Now().Add(ttl).Unix(),+ "iat": time.Now().Unix(),+ })+ return token.SignedString([]byte(getJwtSecret()))+}++// ParseSandboxTerminalTicket validates a handshake ticket. Access and+// refresh tokens are rejected.+func ParseSandboxTerminalTicket(raw string) (*SandboxTerminalTicketClaims, error) {+ raw = strings.TrimSpace(raw)+ if raw == "" {+ return nil, errors.New("missing terminal ticket")+ }+ token, err := jwt.Parse(raw, func(token *jwt.Token) (interface{}, error) {+ if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {+ return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])+ }+ return []byte(getJwtSecret()), nil+ })+ if err != nil || token == nil || !token.Valid {+ return nil, errors.New("invalid or expired terminal ticket")+ }+ claims, ok := token.Claims.(jwt.MapClaims)+ if !ok {+ return nil, errors.New("invalid terminal ticket claims")+ }+ tokenType, _ := claims["type"].(string)+ if tokenType != sandboxTerminalTicketType {+ return nil, errors.New("not a terminal ticket")+ }+ userID, _ := claims["user_id"].(string)+ sessionID, _ := claims["session_id"].(string)+ tokenID, _ := claims["token_id"].(string)+ tenantID := tenantIDFromClaims(claims, 0)+ if strings.TrimSpace(userID) == "" || strings.TrimSpace(sessionID) == "" || strings.TrimSpace(tokenID) == "" || tenantID == 0 {+ return nil, errors.New("invalid terminal ticket claims")+ }+ return &SandboxTerminalTicketClaims{+ UserID: userID,+ TenantID: tenantID,+ SessionID: sessionID,+ TokenID: tokenID,+ }, nil+}diff --git a/internal/application/service/sandbox_terminal_ticket_test.go b/internal/application/service/sandbox_terminal_ticket_test.gonew file mode 100644index 000000000..cf25aea4f--- /dev/null+++ b/internal/application/service/sandbox_terminal_ticket_test.go@@ -0,0 +1,79 @@+package service++import (+ "testing"+ "time"++ "github.com/golang-jwt/jwt/v5"+ "github.com/stretchr/testify/require"+)++func TestSandboxTerminalTicketRoundTrip(t *testing.T) {+ ticket, err := IssueSandboxTerminalTicket("user-1", 42, "sess-9", "tok-abc", time.Minute)+ require.NoError(t, err)+ require.NotEmpty(t, ticket)++ claims, err := ParseSandboxTerminalTicket(ticket)+ require.NoError(t, err)+ require.Equal(t, "user-1", claims.UserID)+ require.Equal(t, uint64(42), claims.TenantID)+ require.Equal(t, "sess-9", claims.SessionID)+ require.Equal(t, "tok-abc", claims.TokenID)+}++func TestSandboxTerminalTicketRejectsMalformedAndExpired(t *testing.T) {+ _, err := ParseSandboxTerminalTicket("not-a-jwt")+ require.Error(t, err)++ tok := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{+ "user_id": "user-1",+ "tenant_id": 1,+ "session_id": "sess",+ "token_id": "tok-1",+ "type": sandboxTerminalTicketType,+ "exp": time.Now().Add(-time.Minute).Unix(),+ })+ raw, err := tok.SignedString([]byte(getJwtSecret()))+ require.NoError(t, err)+ _, err = ParseSandboxTerminalTicket(raw)+ require.Error(t, err)+}++func TestSandboxTerminalTicketRejectsAccessToken(t *testing.T) {+ tok := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{+ "user_id": "user-1",+ "tenant_id": 1,+ "session_id": "sess",+ "token_id": "tok-1",+ "exp": time.Now().Add(time.Hour).Unix(),+ })+ raw, err := tok.SignedString([]byte(getJwtSecret()))+ require.NoError(t, err)+ _, err = ParseSandboxTerminalTicket(raw)+ require.Error(t, err)+}++func TestSandboxTerminalTicketRejectsEmptyFields(t *testing.T) {+ _, err := IssueSandboxTerminalTicket("", 1, "sess", "tok", time.Minute)+ require.Error(t, err)+ _, err = IssueSandboxTerminalTicket("user", 0, "sess", "tok", time.Minute)+ require.Error(t, err)+ _, err = IssueSandboxTerminalTicket("user", 1, "", "tok", time.Minute)+ require.Error(t, err)+ _, err = IssueSandboxTerminalTicket("user", 1, "sess", "", time.Minute)+ require.Error(t, err)+}++func TestSandboxTerminalTicketRejectsMissingTokenIDClaim(t *testing.T) {+ tok := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{+ "user_id": "user-1",+ "tenant_id": 1,+ "session_id": "sess",+ "type": sandboxTerminalTicketType,+ "exp": time.Now().Add(time.Minute).Unix(),+ })+ raw, err := tok.SignedString([]byte(getJwtSecret()))+ require.NoError(t, err)+ _, err = ParseSandboxTerminalTicket(raw)+ require.Error(t, err)+}diff --git a/internal/application/service/tenant_member_test.go b/internal/application/service/tenant_member_test.goindex ae7643635..fafd285e6 100644--- a/internal/application/service/tenant_member_test.go+++ b/internal/application/service/tenant_member_test.go@@ -314,6 +314,9 @@ func (r *cleanupTokenRepo) CreateToken(context.Context, *types.AuthToken) errorfunc (r *cleanupTokenRepo) GetTokenByValue(context.Context, string) (*types.AuthToken, error) {return nil, errors.New("not found")}+func (r *cleanupTokenRepo) GetTokenByID(context.Context, string) (*types.AuthToken, error) {+ return nil, errors.New("not found")+}func (r *cleanupTokenRepo) GetTokensByUserID(context.Context, string) ([]*types.AuthToken, error) {return nil, nil}diff --git a/internal/application/service/user.go b/internal/application/service/user.goindex d557119bd..77be3caeb 100644--- a/internal/application/service/user.go+++ b/internal/application/service/user.go@@ -1229,6 +1229,9 @@ func (s *userService) ValidateToken(ctx context.Context, tokenString string) (*tif isRefreshTokenClaims(claims) {return nil, 0, errors.New("refresh token cannot be used as access token")}+ if isSandboxTerminalTicketClaims(claims) {+ return nil, 0, errors.New("terminal ticket cannot be used as access token")+ }// Check if token is revokedtokenRecord, err := s.tokenRepo.GetTokenByValue(ctx, tokenString)@@ -1252,11 +1255,52 @@ func (s *userService) ValidateToken(ctx context.Context, tokenString string) (*treturn user, activeTenantID, nil}+func redactAuthToken(token *types.AuthToken) *types.AuthToken {+ if token == nil {+ return nil+ }+ cp := *token+ cp.Token = ""+ return &cp+}++// GetAccessTokenByValue looks up the stored token row for a JWT string.+// The JWT itself is stripped so callers cannot log or re-play it.+func (s *userService) GetAccessTokenByValue(ctx context.Context, tokenString string) (*types.AuthToken, error) {+ tokenString = strings.TrimSpace(tokenString)+ if tokenString == "" {+ return nil, apprepo.ErrTokenNotFound+ }+ token, err := s.tokenRepo.GetTokenByValue(ctx, tokenString)+ if err != nil {+ return nil, err+ }+ return redactAuthToken(token), nil+}++// GetAccessTokenByID looks up a stored token row by primary key.+func (s *userService) GetAccessTokenByID(ctx context.Context, id string) (*types.AuthToken, error) {+ id = strings.TrimSpace(id)+ if id == "" {+ return nil, apprepo.ErrTokenNotFound+ }+ token, err := s.tokenRepo.GetTokenByID(ctx, id)+ if err != nil {+ return nil, err+ }+ return redactAuthToken(token), nil+}+func isRefreshTokenClaims(claims jwt.MapClaims) bool {tokenType, ok := claims["type"].(string)return ok && tokenType == "refresh"}+func isSandboxTerminalTicketClaims(claims jwt.MapClaims) bool {+ tokenType, ok := claims["type"].(string)+ return ok && tokenType == sandboxTerminalTicketType+}+func userIDFromSignedToken(tokenString string) (string, error) {token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {diff --git a/internal/application/service/user_auth_token_test.go b/internal/application/service/user_auth_token_test.goindex 471a12445..4d3a970f6 100644--- a/internal/application/service/user_auth_token_test.go+++ b/internal/application/service/user_auth_token_test.go@@ -30,6 +30,14 @@ func (s *stubAuthTokenRepo) GetTokenByValue(_ context.Context, tokenValue string}return token, nil}+func (s *stubAuthTokenRepo) GetTokenByID(_ context.Context, id string) (*types.AuthToken, error) {+ for _, token := range s.tokens {+ if token != nil && token.ID == id {+ return token, nil+ }+ }+ return nil, errors.New("token not found")+}func (s *stubAuthTokenRepo) GetTokensByUserID(context.Context, string) ([]*types.AuthToken, error) {return nil, nil}@@ -141,6 +149,26 @@ func TestValidateTokenRejectsRefreshToken(t *testing.T) {}}+func TestValidateTokenRejectsSandboxTerminalTicket(t *testing.T) {+ ctx := context.Background()+ tokenRepo := &stubAuthTokenRepo{tokens: map[string]*types.AuthToken{}}+ svc := newAuthTestUserService(tokenRepo)++ ticket := signTestJWT(jwt.MapClaims{+ "user_id": "user-1",+ "tenant_id": 1,+ "session_id": "sess",+ "token_id": "tok-1",+ "type": sandboxTerminalTicketType,+ "exp": time.Now().Add(time.Minute).Unix(),+ })++ _, _, err := svc.ValidateToken(ctx, ticket)+ if err == nil || err.Error() != "terminal ticket cannot be used as access token" {+ t.Fatalf("ValidateToken(terminal ticket) err = %v, want terminal ticket rejection", err)+ }+}+func TestRefreshTokenRejectsAccessTokenRecord(t *testing.T) {ctx := context.Background()tokenRepo := &stubAuthTokenRepo{tokens: map[string]*types.AuthToken{}}@@ -319,3 +347,34 @@ func TestUserIDFromSignedTokenAcceptsExpiredToken(t *testing.T) {t.Fatalf("userIDFromSignedToken(expired) = %q, want user-1", userID)}}++func TestGetAccessTokenLookupsRedactJWT(t *testing.T) {+ ctx := context.Background()+ raw := "jwt-secret-value"+ tokenRepo := &stubAuthTokenRepo{tokens: map[string]*types.AuthToken{+ raw: {+ ID: "tok-1",+ UserID: "user-1",+ Token: raw,+ TokenType: "access_token",+ ExpiresAt: time.Now().Add(time.Hour),+ },+ }}+ svc := newAuthTestUserService(tokenRepo)++ byValue, err := svc.GetAccessTokenByValue(ctx, raw)+ if err != nil {+ t.Fatalf("GetAccessTokenByValue: %v", err)+ }+ if byValue.ID != "tok-1" || byValue.Token != "" {+ t.Fatalf("GetAccessTokenByValue = %+v, want id tok-1 with redacted token", byValue)+ }++ byID, err := svc.GetAccessTokenByID(ctx, "tok-1")+ if err != nil {+ t.Fatalf("GetAccessTokenByID: %v", err)+ }+ if byID.ID != "tok-1" || byID.Token != "" {+ t.Fatalf("GetAccessTokenByID = %+v, want id tok-1 with redacted token", byID)+ }+}diff --git a/internal/container/container.go b/internal/container/container.goindex 143b65bb8..dd6e7eee5 100644--- a/internal/container/container.go+++ b/internal/container/container.go@@ -311,6 +311,11 @@ func BuildContainer(container *dig.Container) *dig.Container {// per-session file inspection; downstream code guards on nil.must(container.Provide(service.NewArtifactCollectorFromSandboxManager))+ // SandboxTerminalService opens interactive PTYs on session sandboxes for+ // the frontend terminal panel. First-use provisioning takes a sandbox+ // config ID already resolved by the WebSocket handler (own or shared agent).+ must(container.Provide(service.NewSandboxTerminalService))+logger.Debugf(ctx, "[Container] Registering task enqueuer...")redisAvailable := os.Getenv("REDIS_ADDR") != ""if redisAvailable {diff --git a/internal/handler/session/handler.go b/internal/handler/session/handler.goindex 779437b39..10a13e4a1 100644--- a/internal/handler/session/handler.go+++ b/internal/handler/session/handler.go@@ -38,6 +38,15 @@ type Handler struct {// not support artifact collection; handlers must check before using.artifactCollector *service.ArtifactCollectormemoryService interfaces.MemoryService // Service for cross-session long-term memory+ // userService / memberService back the sandbox terminal's self-contained+ // handshake (browser WebSocket upgrades cannot send Authorization).+ userService interfaces.UserService+ memberService interfaces.TenantMemberService+ // terminalService opens PTYs on the sandbox bound to a session. It also+ // owns first-use provisioning: the WS handshake carries the chat page's+ // selected agent so the sandbox is created with the same config a+ // conversation turn would use.+ terminalService *service.SandboxTerminalService}// NewHandler creates a new instance of Handler with all necessary dependencies@@ -61,6 +70,9 @@ func NewHandler(temporaryDocuments interfaces.TemporaryDocumentService,artifactCollector *service.ArtifactCollector,memoryService interfaces.MemoryService,+ userService interfaces.UserService,+ memberService interfaces.TenantMemberService,+ terminalService *service.SandboxTerminalService,) *Handler {return &Handler{sessionService: sessionService,@@ -80,6 +92,9 @@ func NewHandler(temporaryDocuments: temporaryDocuments,artifactCollector: artifactCollector,memoryService: memoryService,+ userService: userService,+ memberService: memberService,+ terminalService: terminalService,attachmentProcessor: NewAttachmentProcessor(fileService,documentReader,diff --git a/internal/handler/session/resolve_agent_test.go b/internal/handler/session/resolve_agent_test.goindex ca9757195..540319719 100644--- a/internal/handler/session/resolve_agent_test.go+++ b/internal/handler/session/resolve_agent_test.go@@ -156,3 +156,36 @@ func TestResolveAgent_FallsBackToLocalAgentWithoutSourceSelector(t *testing.T) {require.Equal(t, uint64(0), effectiveTenantID)require.False(t, sharedReadOnly)}++func TestTerminalProvisionConfigID_UsesSharedAgentSandboxConfig(t *testing.T) {+ gin.SetMode(gin.TestMode)+ rec := httptest.NewRecorder()+ c, _ := gin.CreateTestContext(rec)+ c.Request = httptest.NewRequest(+ http.MethodGet,+ "/?agent_id=builtin-smart-reasoning&agent_source_tenant_id=84",+ nil,+ )+ c.Set(types.UserIDContextKey.String(), "user-1")+ c.Set(types.TenantIDContextKey.String(), uint64(7))+ ctx := context.WithValue(c.Request.Context(), types.TenantIDContextKey, uint64(7))+ c.Request = c.Request.WithContext(ctx)++ sharedAgent := &types.CustomAgent{+ ID: "builtin-smart-reasoning",+ TenantID: 84,+ Config: types.CustomAgentConfig{SandboxConfigID: "shared-cfg"},+ }+ h := &Handler{+ agentShareService: &resolveAgentShareStub{agent: sharedAgent},+ customAgentService: &resolveOwnAgentStub{agent: &types.CustomAgent{+ ID: "builtin-smart-reasoning",+ TenantID: 7,+ Config: types.CustomAgentConfig{SandboxConfigID: "local-cfg"},+ }},+ }++ require.Equal(t, "", h.terminalProvisionConfigID(ctx, c, false),+ "lookup-only connects must not resolve an agent config")+ require.Equal(t, "shared-cfg", h.terminalProvisionConfigID(ctx, c, true))+}diff --git a/internal/handler/session/sandbox_terminal_bridge.go b/internal/handler/session/sandbox_terminal_bridge.gonew file mode 100644index 000000000..1de3d3f4a--- /dev/null+++ b/internal/handler/session/sandbox_terminal_bridge.go@@ -0,0 +1,340 @@+// Package session: terminal bridge between the WebSocket and the sandbox+// PTY (see sandbox_terminal_ws.go for the protocol contract).+package session++import (+ "context"+ "encoding/json"+ "errors"+ "sync"+ "sync/atomic"+ "time"++ "github.com/gorilla/websocket"++ "github.com/Tencent/WeKnora/internal/application/service"+ "github.com/Tencent/WeKnora/internal/logger"+)++// terminalBridge owns one upgraded terminal connection. Exactly one of the+// goroutines it starts (output pump, input pump, heartbeat, idle, auth recheck)+// observes termination and drives cleanup; the others exit as a side effect of+// the shared teardown.+type terminalBridge struct {+ conn *websocket.Conn+ ctx context.Context+ cancel context.CancelFunc+ session string+ terminal *service.SessionTerminal+ // idleDisconnect is how long to wait without PTY activity. Zero disables+ // the watcher (should not happen: the service always supplies a default).+ idleDisconnect time.Duration+ lastActivity atomic.Int64+ // authCheck re-validates the handshake identity. It returns+ // service.ErrTerminalAuthDenied when access is definitively gone and any+ // other error for a lookup failure worth retrying. Nil disables the+ // watcher. A closure rather than the Handler: the bridge needs exactly+ // this one capability, and holding the handler would give it the whole+ // dependency graph (and make watchAuth untestable).+ authCheck func(context.Context) error++ // writeMu serialises writes: the output pump streams PTY bytes while+ // control frames (ready/error/exited) come from the pump goroutines.+ writeMu sync.Mutex+ // teardown runs once, from whichever goroutine observes the end.+ teardownOnce sync.Once+ // teardownReason records why the bridge ended, for the closing log line.+ teardownReason string+}++// teardownWith records the reason and tears the bridge down.+func (b *terminalBridge) teardownWith(reason string) {+ b.teardownOnce.Do(func() {+ b.teardownReason = reason+ b.teardownLocked()+ })+}++func (b *terminalBridge) run() {+ b.sendControl(terminalControlFrame{+ Type: "ready",+ PID: b.terminal.Session.PID(),+ Backend: b.terminal.Backend,+ })++ // Liveness defaults; the read loop also refreshes on every frame.+ b.conn.SetReadLimit(terminalMaxInputBytes)+ _ = b.conn.SetReadDeadline(time.Now().Add(terminalReadTimeout))+ b.conn.SetPongHandler(func(string) error {+ return b.conn.SetReadDeadline(time.Now().Add(terminalReadTimeout))+ })+ b.touchActivity()++ done := make(chan struct{})+ go b.pumpOutput(done)+ go b.heartbeat(done)+ go b.watchIdle(done)+ go b.watchAuth(done)+ b.pumpInput()+ b.teardownWith("client_disconnected")+ <-done+}++// sendControl writes one JSON control frame. Safe for concurrent use.+func (b *terminalBridge) sendControl(frame terminalControlFrame) {+ payload, err := json.Marshal(frame)+ if err != nil {+ return+ }+ b.writeMu.Lock()+ defer b.writeMu.Unlock()+ // The deadline is set under the same lock as the write: it is connection+ // state, and the output pump shares this connection.+ _ = b.conn.SetWriteDeadline(time.Now().Add(terminalWriteTimeout))+ if werr := b.conn.WriteMessage(websocket.TextMessage, payload); werr != nil {+ logger.Debugf(b.ctx, "[sandbox-terminal] control write failed session=%s: %v",+ b.session, werr)+ }+}++// pumpOutput streams PTY output to the browser as binary frames. It exits+// when the terminal's output channel closes; teardown has already been+// triggered by then (or triggers now via the closing path in run()).+func (b *terminalBridge) pumpOutput(done chan struct{}) {+ defer close(done)+ // Normal termination: the channel closed because we tore the bridge down+ // from another goroutine. Any other exit path below sets a real reason.+ defer b.teardownWith("stream_closed")+ for event := range b.terminal.Session.Output() {+ switch {+ case event.Err != nil:+ logger.Warnf(b.ctx, "[sandbox-terminal] stream error session=%s: %v",+ b.session, event.Err)+ b.sendControl(terminalControlFrame{+ Type: "error",+ Code: terminalErrInternal,+ Message: "terminal stream failed",+ })+ b.teardownWith("stream_error")+ return+ case event.Exited:+ code := event.ExitCode+ b.sendControl(terminalControlFrame{Type: "exited", ExitCode: &code})+ b.teardownWith("shell_exited")+ return+ case len(event.Data) > 0:+ b.touchActivity()+ b.writeMu.Lock()+ _ = b.conn.SetWriteDeadline(time.Now().Add(terminalWriteTimeout))+ if err := b.conn.WriteMessage(websocket.BinaryMessage, event.Data); err != nil {+ b.writeMu.Unlock()+ logger.Debugf(b.ctx, "[sandbox-terminal] output write failed session=%s: %v",+ b.session, err)+ b.teardownWith("output_write_failed")+ return+ }+ b.writeMu.Unlock()+ }+ }+}++// pumpInput reads browser frames until the connection dies: binary frames+// are keystrokes, text frames are resize/ping control requests.+func (b *terminalBridge) pumpInput() {+ for {+ messageType, payload, err := b.conn.ReadMessage()+ if err != nil {+ // Normal close or transport failure — both end the session.+ return+ }+ _ = b.conn.SetReadDeadline(time.Now().Add(terminalReadTimeout))+ switch messageType {+ case websocket.BinaryMessage:+ b.touchActivity()+ writeCtx, cancel := context.WithTimeout(b.ctx, 5*time.Second)+ werr := b.terminal.Session.Write(writeCtx, payload)+ cancel()+ if werr != nil {+ logger.Debugf(b.ctx, "[sandbox-terminal] input failed session=%s: %v",+ b.session, werr)+ }+ case websocket.TextMessage:+ var frame terminalControlFrame+ if json.Unmarshal(payload, &frame) != nil {+ continue+ }+ switch frame.Type {+ case "resize":+ cols, rows := frame.Cols, frame.Rows+ if cols <= 0 || rows <= 0 || cols > terminalMaxGeometry || rows > terminalMaxGeometry {+ continue+ }+ b.touchActivity()+ resizeCtx, cancel := context.WithTimeout(b.ctx, 5*time.Second)+ rerr := b.terminal.Session.Resize(resizeCtx, uint32(cols), uint32(rows))+ cancel()+ if rerr != nil {+ logger.Debugf(b.ctx, "[sandbox-terminal] resize failed session=%s: %v",+ b.session, rerr)+ }+ case "ping":+ b.sendControl(terminalControlFrame{Type: "pong"})+ }+ }+ }+}++func (b *terminalBridge) touchActivity() {+ b.lastActivity.Store(time.Now().UnixNano())+}++func (b *terminalBridge) lastActivityTime() time.Time {+ n := b.lastActivity.Load()+ if n == 0 {+ return time.Time{}+ }+ return time.Unix(0, n)+}++// terminalIdleExpired reports whether last activity is older than idle.+// A zero last timestamp never expires so the watcher cannot fire before the+// first touchActivity in run().+func terminalIdleExpired(last time.Time, idle time.Duration, now time.Time) bool {+ if idle <= 0 || last.IsZero() {+ return false+ }+ return now.Sub(last) >= idle+}++func (b *terminalBridge) watchIdle(done <-chan struct{}) {+ idle := b.idleDisconnect+ if idle <= 0 {+ return+ }+ tick := idle / 12+ if tick < 200*time.Millisecond {+ tick = 200 * time.Millisecond+ }+ if tick > 5*time.Second {+ tick = 5 * time.Second+ }+ ticker := time.NewTicker(tick)+ defer ticker.Stop()+ for {+ select {+ case <-done:+ return+ case <-b.ctx.Done():+ return+ case <-ticker.C:+ if terminalIdleExpired(b.lastActivityTime(), idle, time.Now()) {+ b.disconnectIdle()+ return+ }+ }+ }+}++func (b *terminalBridge) disconnectIdle() {+ b.sendControl(terminalControlFrame{+ Type: "error",+ Code: terminalErrIdle,+ Message: "terminal idle disconnect",+ })+ _ = b.conn.WriteControl(+ websocket.CloseMessage,+ websocket.FormatCloseMessage(websocket.ClosePolicyViolation, terminalErrIdle),+ time.Now().Add(terminalWriteTimeout),+ )+ b.teardownWith("idle_disconnected")+}++func (b *terminalBridge) watchAuth(done <-chan struct{}) {+ if b.authCheck == nil {+ return+ }+ ticker := time.NewTicker(terminalAuthRecheckInterval)+ defer ticker.Stop()+ for {+ select {+ case <-done:+ return+ case <-b.ctx.Done():+ return+ case <-ticker.C:+ checkCtx, cancel := context.WithTimeout(b.ctx, terminalAuthRecheckTimeout)+ err := b.authCheck(checkCtx)+ cancel()+ if err == nil {+ continue+ }+ if b.ctx.Err() != nil {+ return+ }+ if errors.Is(err, service.ErrTerminalAuthDenied) {+ b.disconnectAuth()+ return+ }+ logger.Warnf(b.ctx, "[sandbox-terminal] auth recheck failed session=%s: %v",+ b.session, err)+ }+ }+}++func (b *terminalBridge) disconnectAuth() {+ b.sendControl(terminalControlFrame{+ Type: "error",+ Code: terminalErrAuth,+ Message: "terminal authorization revoked",+ })+ _ = b.conn.WriteControl(+ websocket.CloseMessage,+ websocket.FormatCloseMessage(websocket.ClosePolicyViolation, terminalErrAuth),+ time.Now().Add(terminalWriteTimeout),+ )+ b.teardownWith("auth_revoked")+}++// heartbeat pings the browser so dead TCP connections surface within+// terminalReadTimeout instead of holding PTYs open forever.+func (b *terminalBridge) heartbeat(done chan struct{}) {+ ticker := time.NewTicker(terminalPingInterval)+ defer ticker.Stop()+ for {+ select {+ case <-done:+ return+ case <-b.ctx.Done():+ return+ case <-ticker.C:+ // WriteControl is the only gorilla write documented as safe+ // concurrently with other writers: pumpOutput streams PTY bytes+ // at the same time, and two concurrent WriteMessage calls would+ // corrupt the connection state (and, once c.writeErr is set,+ // poison every later write — the premature-disconnect symptom).+ if err := b.conn.WriteControl(+ websocket.PingMessage,+ nil,+ time.Now().Add(terminalWriteTimeout),+ ); err != nil {+ b.teardownWith("ping_failed")+ return+ }+ }+ }+}++// teardownLocked disconnects the PTY, closes the socket, and releases the+// session slot. Callers must go through teardownWith so the reason is logged.+func (b *terminalBridge) teardownLocked() {+ b.cancel()+ // Close only disconnects WeKnora from the PTY; the shell keeps running in+ // the sandbox and can be reattached provider-side.+ if err := b.terminal.Session.Close(); err != nil {+ logger.Debugf(b.ctx, "[sandbox-terminal] close failed session=%s: %v",+ b.session, err)+ }+ _ = b.conn.Close()+ logger.Infof(b.ctx, "[sandbox-terminal] closed session=%s reason=%s",+ b.session, b.teardownReason)+}diff --git a/internal/handler/session/sandbox_terminal_bridge_test.go b/internal/handler/session/sandbox_terminal_bridge_test.gonew file mode 100644index 000000000..d98b1eb31--- /dev/null+++ b/internal/handler/session/sandbox_terminal_bridge_test.go@@ -0,0 +1,150 @@+package session++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync/atomic"+ "testing"+ "time"++ "github.com/gorilla/websocket"+ "github.com/stretchr/testify/require"++ "github.com/Tencent/WeKnora/internal/application/service"+ "github.com/Tencent/WeKnora/internal/sandbox"+)++// fakeTerminalSession is a RemoteTerminalSession that never produces output,+// so a test controls exactly when the bridge ends.+type fakeTerminalSession struct {+ out chan sandbox.RemoteTerminalEvent+ closes atomic.Int32+}++func newFakeTerminalSession() *fakeTerminalSession {+ return &fakeTerminalSession{out: make(chan sandbox.RemoteTerminalEvent)}+}++func (s *fakeTerminalSession) Output() <-chan sandbox.RemoteTerminalEvent { return s.out }+func (s *fakeTerminalSession) PID() uint32 { return 4321 }+func (s *fakeTerminalSession) Write(context.Context, []byte) error { return nil }+func (s *fakeTerminalSession) Resize(context.Context, uint32, uint32) error {+ return nil+}++func (s *fakeTerminalSession) Close() error {+ // The real adapters make Close idempotent; mirror that and record the+ // call so a test can assert the PTY was released.+ if s.closes.Add(1) == 1 {+ close(s.out)+ }+ return nil+}++// serveTerminalBridge stands up a real WebSocket endpoint driven by+// terminalBridge and dials it, so tests exercise the actual protocol rather+// than the bridge's internals.+func serveTerminalBridge(+ t *testing.T,+ pty *fakeTerminalSession,+ authCheck func(context.Context) error,+) *websocket.Conn {+ t.Helper()++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ conn, err := terminalUpgrader.Upgrade(w, r, nil)+ if err != nil {+ return+ }+ ctx, cancel := context.WithCancel(context.Background())+ bridge := &terminalBridge{+ conn: conn,+ ctx: ctx,+ cancel: cancel,+ session: "sess-1",+ terminal: &service.SessionTerminal{Session: pty, Backend: "fake"},+ // Idle disconnect off: these tests are about the auth watcher.+ idleDisconnect: 0,+ authCheck: authCheck,+ }+ bridge.run()+ }))+ t.Cleanup(server.Close)++ client, _, err := websocket.DefaultDialer.Dial(+ "ws"+strings.TrimPrefix(server.URL, "http"), nil,+ )+ require.NoError(t, err)+ t.Cleanup(func() { _ = client.Close() })+ return client+}++func readTerminalFrame(t *testing.T, conn *websocket.Conn) terminalControlFrame {+ t.Helper()+ require.NoError(t, conn.SetReadDeadline(time.Now().Add(5*time.Second)))+ _, payload, err := conn.ReadMessage()+ require.NoError(t, err)+ var frame terminalControlFrame+ require.NoError(t, json.Unmarshal(payload, &frame))+ return frame+}++func TestTerminalBridgeTearsDownWhenAuthIsRevoked(t *testing.T) {+ prev := terminalAuthRecheckInterval+ terminalAuthRecheckInterval = 20 * time.Millisecond+ t.Cleanup(func() { terminalAuthRecheckInterval = prev })++ pty := newFakeTerminalSession()+ client := serveTerminalBridge(t, pty, func(context.Context) error {+ return service.ErrTerminalAuthDenied+ })++ require.Equal(t, "ready", readTerminalFrame(t, client).Type)++ errFrame := readTerminalFrame(t, client)+ require.Equal(t, "error", errFrame.Type)+ require.Equal(t, terminalErrAuth, errFrame.Code)++ // The socket must actually close, and the PTY must be released with it.+ require.NoError(t, client.SetReadDeadline(time.Now().Add(5*time.Second)))+ _, _, err := client.ReadMessage()+ require.Error(t, err, "server must close the socket after revoking auth")+ require.Eventually(t, func() bool {+ return pty.closes.Load() > 0+ }, 2*time.Second, 10*time.Millisecond, "PTY must be closed on auth teardown")+}++// The counterpart to the service-level fail-open tests: a lookup that merely+// failed must leave the terminal running so a database hiccup does not+// disconnect every open session at once.+func TestTerminalBridgeSurvivesTransientAuthLookupFailure(t *testing.T) {+ prev := terminalAuthRecheckInterval+ terminalAuthRecheckInterval = 10 * time.Millisecond+ t.Cleanup(func() { terminalAuthRecheckInterval = prev })++ var checks atomic.Int32+ pty := newFakeTerminalSession()+ client := serveTerminalBridge(t, pty, func(context.Context) error {+ checks.Add(1)+ return errors.New("db down")+ })++ require.Equal(t, "ready", readTerminalFrame(t, client).Type)++ require.Eventually(t, func() bool {+ return checks.Load() >= 3+ }, 2*time.Second, 10*time.Millisecond, "watcher must keep retrying")++ // Nothing further should have been sent, and the PTY is still live.+ require.NoError(t, client.SetReadDeadline(time.Now().Add(150*time.Millisecond)))+ _, _, err := client.ReadMessage()+ require.Error(t, err)+ netErr, ok := err.(interface{ Timeout() bool })+ require.True(t, ok && netErr.Timeout(),+ "expected a read timeout (terminal still open), got %v", err)+ require.Zero(t, pty.closes.Load())+}diff --git a/internal/handler/session/sandbox_terminal_idle_test.go b/internal/handler/session/sandbox_terminal_idle_test.gonew file mode 100644index 000000000..33fbf09ff--- /dev/null+++ b/internal/handler/session/sandbox_terminal_idle_test.go@@ -0,0 +1,50 @@+package session++import (+ "testing"+ "time"++ "github.com/stretchr/testify/require"+)++func TestTerminalIdleExpired(t *testing.T) {+ t.Parallel()+ now := time.Date(2026, 9, 4, 12, 0, 0, 0, time.UTC)+ last := now.Add(-15 * time.Minute)++ require.False(t, terminalIdleExpired(time.Time{}, 15*time.Minute, now),+ "no activity timestamp must not expire")+ require.False(t, terminalIdleExpired(last, 0, now),+ "zero idle must disable the watcher")+ require.False(t, terminalIdleExpired(last, 20*time.Minute, now))+ require.True(t, terminalIdleExpired(last, 15*time.Minute, now))+ require.True(t, terminalIdleExpired(last, 10*time.Minute, now))+}++// The provision flag authorises creating a microVM from a GET, so it must be+// opt-in: absent, empty, or malformed all have to read as "do not create".+func TestTerminalFlagParam(t *testing.T) {+ t.Parallel()+ for _, raw := range []string{"1", "true", "TRUE", " yes ", "Yes"} {+ require.True(t, terminalFlagParam(raw), "expected %q to opt in", raw)+ }+ for _, raw := range []string{"", " ", "0", "false", "no", "2", "on", "provision", "1;"} {+ require.False(t, terminalFlagParam(raw), "expected %q to stay opted out", raw)+ }+}++func TestTerminalTenantParam(t *testing.T) {+ t.Parallel()+ require.Equal(t, uint64(0), terminalTenantParam(""))+ require.Equal(t, uint64(0), terminalTenantParam("0"))+ require.Equal(t, uint64(0), terminalTenantParam("-1"))+ require.Equal(t, uint64(84), terminalTenantParam("84"))+ require.Equal(t, uint64(84), terminalTenantParam(" 84 "))+}++func TestTerminalAuthRecheckInterval(t *testing.T) {+ t.Parallel()+ require.GreaterOrEqual(t, terminalAuthRecheckInterval, time.Minute)+ require.LessOrEqual(t, terminalAuthRecheckInterval, 2*time.Minute)+ require.Equal(t, "AUTH_REVOKED", terminalErrAuth)+}diff --git a/internal/handler/session/sandbox_terminal_ws.go b/internal/handler/session/sandbox_terminal_ws.gonew file mode 100644index 000000000..1b2ff399b--- /dev/null+++ b/internal/handler/session/sandbox_terminal_ws.go@@ -0,0 +1,422 @@+// Package session: sandbox terminal WebSocket.+//+// GET /api/v1/sessions/:session_id/sandbox/terminal?ticket=<short-lived JWT>+//+// The route is registered before the global auth middleware because a+// browser WebSocket handshake cannot carry the Authorization header. The+// browser first POSTs (with a normal Bearer token) for a 2-minute ticket+// bound to this session and to that access-token's id, then presents the+// ticket on the handshake. After upgrade the bridge rechecks the bound+// token, user, workspace membership, and session ownership about once a+// minute and tears the PTY down on failure.+//+// binary frame client→server raw keystrokes into the PTY+// binary frame server→client raw PTY output+// text frame both ways JSON control frames (resize/ping/ready/…)+package session++import (+ "context"+ stderrors "errors"+ "net/http"+ "strconv"+ "strings"+ "sync"+ "time"++ "github.com/gin-gonic/gin"+ "github.com/gorilla/websocket"++ "github.com/Tencent/WeKnora/internal/application/service"+ "github.com/Tencent/WeKnora/internal/errors"+ "github.com/Tencent/WeKnora/internal/logger"+ "github.com/Tencent/WeKnora/internal/middleware"+ "github.com/Tencent/WeKnora/internal/sandbox"+ "github.com/Tencent/WeKnora/internal/types"+)++// Terminal protocol tunables.+const (+ // terminalPingInterval / terminalReadTimeout drive the liveness loop:+ // the server pings, and any read (pong, keystroke, control frame)+ // refreshes the read deadline. The read window is deliberately 4x the+ // ping interval (not 2x) because a backgrounded browser tab throttles+ // timers — its pong reply can lag well past one interval, and a tight+ // window would drop terminals that are perfectly healthy.+ terminalPingInterval = 30 * time.Second+ terminalReadTimeout = 120 * time.Second+ // terminalWriteTimeout bounds a single output-frame write so a stalled+ // browser tab cannot pin the pump goroutine forever.+ terminalWriteTimeout = 10 * time.Second+ // terminalMaxInputBytes caps one keystroke frame; terminals exchange+ // small chunks, so anything larger is abusive or buggy.+ terminalMaxInputBytes = 4096+ // terminalMaxGeometry caps the parsed initial geometry.+ terminalMaxGeometry = 500++ // terminalMaxPerSession caps concurrent PTYs per session to protect the+ // sandbox from resource exhaustion.+ terminalMaxPerSession = 5++ terminalAuthRecheckTimeout = 10 * time.Second+)++// terminalAuthRecheckInterval is how often an open PTY re-validates the+// minting access token, user, workspace membership, and session ownership.+// Handshake auth is a snapshot; this is what closes the window after logout,+// token revocation, or being removed from the workspace. Tests lower it.+var terminalAuthRecheckInterval = time.Minute++// Protocol error codes sent as HTTP close reasons and on error frames.+const (+ terminalErrNotBound = "SANDBOX_NOT_BOUND"+ terminalErrUnsupported = "TERMINAL_UNSUPPORTED"+ terminalErrInternal = "INTERNAL"+ terminalErrIdle = "IDLE_DISCONNECTED"+ terminalErrAuth = "AUTH_REVOKED"+)++// terminalUpgrader performs the WebSocket handshake.+//+// Origin is NOT checked here on purpose: authentication travels explicitly+// in the short-lived ticket query parameter and is validated before the+// upgrade, and the endpoint uses no ambient credentials (cookies), so a+// cross-origin browser tab cannot piggyback a victim session. A strict+// same-origin check would also break the dev setup, where the vite proxy+// rewrites Host to the backend address while Origin stays on the dev server.+var terminalUpgrader = websocket.Upgrader{+ ReadBufferSize: 4096,+ WriteBufferSize: 4096,+ CheckOrigin: func(*http.Request) bool { return true },+}++// terminalLimiter caps concurrent PTYs per session across this process.+type terminalLimiter struct {+ mu sync.Mutex+ counts map[string]int+}++var sessionTerminalLimiter = &terminalLimiter{counts: make(map[string]int)}++// acquire reserves a terminal slot. The returned release func is always+// non-nil and idempotent.+func (l *terminalLimiter) acquire(sessionID string) (release func(), ok bool) {+ l.mu.Lock()+ defer l.mu.Unlock()+ if l.counts[sessionID] >= terminalMaxPerSession {+ return func() {}, false+ }+ l.counts[sessionID]+++ released := false+ return func() {+ l.mu.Lock()+ defer l.mu.Unlock()+ if !released {+ released = true+ l.counts[sessionID]--+ if l.counts[sessionID] <= 0 {+ delete(l.counts, sessionID)+ }+ }+ }, true+}++// terminalControlFrame is a text-mode protocol frame.+type terminalControlFrame struct {+ Type string `json:"type"`+ // Code carries the error code on error frames.+ Code string `json:"code,omitempty"`+ // Message is a human-readable detail for error frames.+ Message string `json:"message,omitempty"`+ // PID is the remote shell process id on ready frames.+ PID uint32 `json:"pty_id,omitempty"`+ // Backend names the sandbox provider on ready frames.+ Backend string `json:"backend,omitempty"`+ // ExitCode is set on exited frames (-1 when the provider didn't say).+ ExitCode *int `json:"exit_code,omitempty"`+ // Cols/Rows carry resize requests.+ Cols int `json:"cols,omitempty"`+ Rows int `json:"rows,omitempty"`+}++// SandboxTerminalWS upgrades a browser connection into a session sandbox+// terminal. See the file header for the protocol.+func (h *Handler) SandboxTerminalWS(c *gin.Context) {+ sessionID := strings.TrimSpace(c.Param("id"))+ if sessionID == "" {+ sessionID = strings.TrimSpace(c.Param("session_id"))+ }+ if sessionID == "" {+ c.JSON(http.StatusBadRequest, gin.H{"error": "session id is required"})+ return+ }++ claims, err := service.ParseSandboxTerminalTicket(c.Query("ticket"))+ if err != nil {+ c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: invalid or expired ticket"})+ return+ }+ if claims.SessionID != sessionID {+ c.JSON(http.StatusForbidden, gin.H{"error": "ticket is not valid for this session"})+ return+ }+ // One call covers the whole handshake identity: minting token still live,+ // user active, workspace membership intact, session still owned. It also+ // hands back the user, so nothing below re-queries it.+ user, err := h.checkTerminalAuth(c.Request.Context(), *claims, true)+ if err != nil {+ if stderrors.Is(err, service.ErrTerminalAuthDenied) {+ c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: invalid or expired ticket"})+ return+ }+ logger.ErrorWithFields(c.Request.Context(), err, map[string]interface{}{"session_id": sessionID})+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to validate ticket"})+ return+ }+ if !middleware.AttachAuthenticatedUser(+ c, h.tenantService, h.memberService, h.config, user, claims.TenantID,+ ) {+ return+ }++ ctx := c.Request.Context()++ release, ok := sessionTerminalLimiter.acquire(sessionID)+ if !ok {+ c.JSON(http.StatusTooManyRequests, gin.H{"error": "too many terminals for this session"})+ return+ }+ defer release()++ conn, err := terminalUpgrader.Upgrade(c.Writer, c.Request, nil)+ if err != nil {+ // Upgrade already wrote the HTTP error response.+ return+ }++ // Provisioning is opt-in per connect, because it creates (or resumes and+ // re-bills) a microVM and this is a GET. A bare handshake — panel opened,+ // tab restored, background reconnect — stays lookup-only and reports+ // SANDBOX_NOT_BOUND, which the UI turns into an explicit "create and+ // start" button. Only that confirmed click sets provision=1.+ allowProvision := terminalFlagParam(c.Query("provision"))+ sandboxConfigID := h.terminalProvisionConfigID(ctx, c, allowProvision)++ // Geometry from the query string; the frontend resizes right after+ // ready anyway, so defaults only shape the first paint.+ opts := sandbox.RemoteTerminalOptions{+ Cols: terminalSizeParam(c.Query("cols")),+ Rows: terminalSizeParam(c.Query("rows")),+ AttachPID: terminalPIDParam(c.Query("pty_id")),+ }++ // The connection outlives the HTTP exchange, so the terminal lifetime is+ // governed by this derived context, cancelled in cleanup().+ termCtx, cancelTerm := context.WithCancel(context.WithoutCancel(ctx))+ terminal, err := h.openTerminal(termCtx, sessionID, sandboxConfigID, allowProvision, opts)+ if err != nil {+ code, detail := terminalErrorFrame(err)+ logger.Warnf(ctx, "[sandbox-terminal] open failed session=%s provision=%t code=%s: %v",+ sessionID, allowProvision, code, detail)+ _ = conn.WriteControl(websocket.CloseMessage,+ websocket.FormatCloseMessage(websocket.ClosePolicyViolation, code),+ time.Now().Add(terminalWriteTimeout))+ _ = conn.Close()+ cancelTerm()+ return+ }++ logger.Infof(ctx, "[sandbox-terminal] opened session=%s backend=%s pid=%d",+ sessionID, terminal.Backend, terminal.Session.PID())++ authClaims := *claims+ bridge := &terminalBridge{+ conn: conn,+ ctx: termCtx,+ cancel: cancelTerm,+ session: sessionID,+ terminal: terminal,+ idleDisconnect: terminal.IdleDisconnect,+ authCheck: func(checkCtx context.Context) error {+ _, err := h.checkTerminalAuth(checkCtx, authClaims, false)+ return err+ },+ }+ bridge.run()+}++// openTerminal picks the lookup-only or the provisioning entry point. The+// split is the whole point of the provision flag: only a confirmed user+// action may create infrastructure.+func (h *Handler) openTerminal(+ ctx context.Context,+ sessionID, sandboxConfigID string,+ allowProvision bool,+ opts sandbox.RemoteTerminalOptions,+) (*service.SessionTerminal, error) {+ if allowProvision {+ return h.terminalService.EnsureSessionTerminal(ctx, sessionID, sandboxConfigID, opts)+ }+ return h.terminalService.OpenSessionTerminal(ctx, sessionID, opts)+}++// terminalProvisionConfigID resolves the sandbox config a confirmed create+// should use. It goes through resolveAgent so a shared agent from another+// workspace provisions the same way a chat turn would, instead of looking the+// agent up only in the current tenant.+func (h *Handler) terminalProvisionConfigID(ctx context.Context, c *gin.Context, allowProvision bool) string {+ if !allowProvision || h == nil || c == nil {+ return ""+ }+ agentID := strings.TrimSpace(c.Query("agent_id"))+ if agentID == "" {+ return ""+ }+ agent, _, _ := h.resolveAgent(ctx, c, agentID, terminalTenantParam(c.Query("agent_source_tenant_id")))+ if agent == nil {+ return ""+ }+ return strings.TrimSpace(agent.Config.SandboxConfigID)+}++func terminalTenantParam(raw string) uint64 {+ value, err := strconv.ParseUint(strings.TrimSpace(raw), 10, 64)+ if err != nil || value == 0 {+ return 0+ }+ return value+}++// terminalFlagParam parses an opt-in query flag. Anything other than an+// explicit truthy value is false, so a missing or malformed parameter can+// never authorise a side effect.+func terminalFlagParam(raw string) bool {+ switch strings.ToLower(strings.TrimSpace(raw)) {+ case "1", "true", "yes":+ return true+ default:+ return false+ }+}++// terminalSizeParam parses a non-negative geometry query parameter.+func terminalSizeParam(raw string) uint32 {+ value, err := strconv.ParseUint(strings.TrimSpace(raw), 10, 32)+ if err != nil || value <= 0 || value > terminalMaxGeometry {+ return 0+ }+ return uint32(value)+}++func terminalPIDParam(raw string) uint32 {+ value, err := strconv.ParseUint(strings.TrimSpace(raw), 10, 32)+ if err != nil || value == 0 {+ return 0+ }+ return uint32(value)+}++// IssueSandboxTerminalTicket mints a short-lived handshake ticket for the+// WebSocket. The access JWT stays on this authenticated POST and never+// appears in the WS URL (or nginx access logs of that handshake).+func (h *Handler) IssueSandboxTerminalTicket(c *gin.Context) {+ ctx := c.Request.Context()+ sessionID := strings.TrimSpace(c.Param("session_id"))+ if sessionID == "" {+ sessionID = strings.TrimSpace(c.Param("id"))+ }+ if sessionID == "" {+ c.JSON(http.StatusBadRequest, gin.H{"error": "session id is required"})+ return+ }+ if _, err := h.sessionService.GetOwnedSession(ctx, sessionID); err != nil {+ if stderrors.Is(err, errors.ErrSessionNotFound) {+ c.JSON(http.StatusNotFound, gin.H{"error": "session not found"})+ return+ }+ logger.ErrorWithFields(ctx, err, map[string]interface{}{"session_id": sessionID})+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to load session"})+ return+ }+ userID, ok := types.UserIDFromContext(ctx)+ if !ok || userID == "" {+ c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})+ return+ }+ tenantID, ok := types.TenantIDFromContext(ctx)+ if !ok || tenantID == 0 {+ c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})+ return+ }+ accessToken := sandboxTerminalBearerToken(c)+ if accessToken == "" {+ c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: access token required"})+ return+ }+ record, err := h.userService.GetAccessTokenByValue(ctx, accessToken)+ if err != nil || record == nil || strings.TrimSpace(record.ID) == "" {+ c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})+ return+ }+ if err := service.AssertAccessTokenStillActive(record, userID, time.Now()); err != nil {+ c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})+ return+ }+ ticket, err := service.IssueSandboxTerminalTicket(userID, tenantID, sessionID, record.ID, 0)+ if err != nil {+ logger.ErrorWithFields(ctx, err, map[string]interface{}{"session_id": sessionID})+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to issue ticket"})+ return+ }+ c.JSON(http.StatusOK, gin.H{+ "success": true,+ "data": gin.H{+ "ticket": ticket,+ "expires_in": int(service.DefaultSandboxTerminalTicketTTL.Seconds()),+ },+ })+}++// terminalErrorFrame maps an OpenSessionTerminal failure onto a protocol+// error code and a short message.+func terminalErrorFrame(err error) (code, message string) {+ switch {+ case stderrors.Is(err, sandbox.ErrNoLiveSessionSandbox):+ return terminalErrNotBound, "session has no live sandbox"+ case stderrors.Is(err, service.ErrTerminalUnsupported):+ return terminalErrUnsupported, "sandbox backend does not support terminals"+ default:+ return terminalErrInternal, "failed to open terminal"+ }+}++func sandboxTerminalBearerToken(c *gin.Context) string {+ header := strings.TrimSpace(c.GetHeader("Authorization"))+ if !strings.HasPrefix(header, "Bearer ") {+ return ""+ }+ return strings.TrimSpace(strings.TrimPrefix(header, "Bearer "))+}++func (h *Handler) checkTerminalAuth(+ ctx context.Context,+ claims service.SandboxTerminalTicketClaims,+ rejectExpired bool,+) (*types.User, error) {+ if h == nil {+ return nil, service.ErrTerminalAuthDenied+ }+ return service.CheckSandboxTerminalAuth(+ ctx,+ h.userService,+ h.memberService,+ h.sessionService,+ claims,+ h.terminalRBACEnforced(),+ rejectExpired,+ )+}++func (h *Handler) terminalRBACEnforced() bool {+ return h != nil && h.config != nil && h.config.Tenant.IsRBACEnforced()+}diff --git a/internal/middleware/logger.go b/internal/middleware/logger.goindex 4f1569a37..d8b05d9a1 100644--- a/internal/middleware/logger.go+++ b/internal/middleware/logger.go@@ -43,7 +43,7 @@ func (r loggerResponseBodyWriter) Write(b []byte) (int, error) {// sensitiveFieldRegex 匹配 JSON 中的敏感字段(不区分大小写,兼容 snake_case / camelCase / PascalCase)。// $1 捕获原始字段名(包括两侧引号),保持日志中的字段名不变,仅将值替换为 "***"。var sensitiveFieldRegex = regexp.MustCompile(- `(?i)("(?:new[_-]?password|old[_-]?password|password|passwd|token|access[_-]?token|` ++ `(?i)("(?:new[_-]?password|old[_-]?password|password|passwd|ticket|token|access[_-]?token|` +`refresh[_-]?token|id[_-]?token|authorization|auth[_-]?token|api[_-]?key|` +`api[_-]?secret|secret[_-]?key|client[_-]?secret|private[_-]?key|secret|` +`authorization[_-]?url|authorization[_-]?attempt)")\s*:\s*"[^"]*"`,@@ -61,12 +61,18 @@ var sensitiveQueryFields = map[string]struct{}{"id_token": {},"refresh_token": {},"state": {},- "token": {},+ // ticket is the sandbox terminal's WebSocket handshake credential. A+ // browser cannot set Authorization on an upgrade, so it travels in the+ // query string; anyone holding it for its 2-minute TTL can open a shell+ // in the session's sandbox, which is why it must never reach a log line.+ "ticket": {},+ "token": {},}-// sanitizeQuery prevents OAuth authorization codes and CSRF/attempt state from-// being copied into access logs. Parsing the query also covers repeated and-// percent-encoded parameters without relying on fragile string replacement.+// sanitizeQuery prevents OAuth authorization codes, CSRF/attempt state, and+// handshake credentials from being copied into access logs. Parsing the query+// also covers repeated and percent-encoded parameters without relying on+// fragile string replacement.func sanitizeQuery(raw string) string {values, err := url.ParseQuery(raw)if err != nil {diff --git a/internal/middleware/logger_test.go b/internal/middleware/logger_test.goindex e27ba2956..72cc4e8bf 100644--- a/internal/middleware/logger_test.go+++ b/internal/middleware/logger_test.go@@ -1,6 +1,9 @@package middleware-import "testing"+import (+ "strings"+ "testing"+)func TestSanitizeBody(t *testing.T) {cases := []struct {@@ -38,6 +41,11 @@ func TestSanitizeBody(t *testing.T) {in: `{"password":"p","token":"t"}`,want: `{"password":"***","token":"***"}`,},+ {+ name: "sandbox terminal handshake ticket in JSON body",+ in: `{"success":true,"data":{"ticket":"eyJhbGciOiJIUzI1NiJ9.payload.signature","expires_in":120}}`,+ want: `{"success":true,"data":{"ticket":"***","expires_in":120}}`,+ },{name: "snake_case new_password and old_password",in: `{"email":"[email protected]","new_password":"FreshPass9","old_password":"OldPass9"}`,@@ -77,3 +85,18 @@ func TestSanitizeQuery(t *testing.T) {t.Fatalf("sanitizeQuery() = %q, want %q", got, want)}}++// The sandbox terminal presents its handshake credential as a query parameter+// because a browser WebSocket upgrade cannot carry Authorization. Holding that+// value for its TTL is enough to open a shell in the session's sandbox, so the+// redaction is a security boundary, not cosmetics.+func TestSanitizeQueryRedactsTerminalTicket(t *testing.T) {+ got := sanitizeQuery("ticket=eyJhbGciOiJIUzI1NiJ9.payload.signature&provision=1&cols=120")+ want := "cols=120&provision=1&ticket=%2A%2A%2A"+ if got != want {+ t.Fatalf("sanitizeQuery() = %q, want %q", got, want)+ }+ if strings.Contains(got, "signature") {+ t.Fatalf("sanitizeQuery() leaked the ticket: %q", got)+ }+}diff --git a/internal/middleware/ws_auth.go b/internal/middleware/ws_auth.gonew file mode 100644index 000000000..a931f2052--- /dev/null+++ b/internal/middleware/ws_auth.go@@ -0,0 +1,47 @@+// Package middleware: authentication for browser WebSocket upgrades.+//+// Browsers cannot attach custom headers (Authorization / X-API-Key) to a+// WebSocket handshake. The sandbox terminal mints a short-lived ticket over+// a normal authenticated POST and presents it as the ticket query parameter;+// AttachAuthenticatedUser then installs the same auth session Auth would,+// given the user the handler already resolved from that ticket.+package middleware++import (+ "net/http"+ "strconv"+ "strings"++ "github.com/Tencent/WeKnora/internal/config"+ "github.com/Tencent/WeKnora/internal/types"+ "github.com/Tencent/WeKnora/internal/types/interfaces"+ "github.com/gin-gonic/gin"+)++// AttachAuthenticatedUser installs the same auth session the Auth middleware+// would, given an already-resolved user and tenant. On success the request+// carries the resolved auth session and true is returned; on failure the+// response has already been written and false is returned.+//+// The tenant is taken from jwtTenantID unless the caller already set+// X-Tenant-ID, mirroring how Auth honours that header. Membership and role+// are still resolved from the database by authenticateJWTUser, so passing a+// user here grants nothing on its own.+func AttachAuthenticatedUser(+ c *gin.Context,+ tenantService interfaces.TenantService,+ memberService interfaces.TenantMemberService,+ cfg *config.Config,+ user *types.User,+ jwtTenantID uint64,+) bool {+ if user == nil {+ c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: invalid or expired token"})+ c.Abort()+ return false+ }+ if jwtTenantID != 0 && strings.TrimSpace(c.GetHeader("X-Tenant-ID")) == "" {+ c.Request.Header.Set("X-Tenant-ID", strconv.FormatUint(jwtTenantID, 10))+ }+ return authenticateJWTUser(c, tenantService, memberService, cfg, user, jwtTenantID)+}diff --git a/internal/router/router.go b/internal/router/router.goindex 9a496a682..1363d6a53 100644--- a/internal/router/router.go+++ b/internal/router/router.go@@ -176,6 +176,12 @@ func NewRouter(params RouterParams) *gin.Engine {// WeKnora authentication headers.serveResourceGrants(r, params.ResourceCatalog, params.TenantService, params.FileService, params.StorageBackendResolver)+ // Sandbox terminal WebSocket (self-authenticated via a short-lived+ // query ticket — see RegisterSandboxTerminalRoutes; browsers cannot set+ // auth headers on the WS handshake, so this must precede the global Auth+ // middleware). The ticket is minted by an authenticated POST.+ RegisterSandboxTerminalRoutes(r, params.SessionHandler)+// 认证中间件r.Use(middleware.Auth(params.TenantService, params.UserService, params.TenantMemberService, params.TenantAPIKeyService, params.Config))diff --git a/internal/router/routes_chat.go b/internal/router/routes_chat.goindex 8cd2cc78c..5f718bdf5 100644--- a/internal/router/routes_chat.go+++ b/internal/router/routes_chat.go@@ -64,6 +64,7 @@ func RegisterSessionRoutes(sessions.GET("/:id/attachments/:attachment_id/preview", handler.PreviewTemporaryDocument)sessions.DELETE("/:id/attachments/:attachment_id", handler.DeleteTemporaryDocument)sessions.POST("/:session_id/stop", handler.StopSession)+ sessions.POST("/:session_id/sandbox/terminal-ticket", handler.IssueSandboxTerminalTicket)// POST and DELETE share this path but gin maintains a separate radix tree// per HTTP verb, and the existing trees use different wildcard names// (POST uses :session_id, DELETE uses :id). Use whatever matches each@@ -120,3 +121,20 @@ func RegisterChatRoutes(r *gin.RouterGroup, handler *session.Handler, g *rbacGuaknowledgeSearch.POST("", handler.SearchKnowledge)}}++// RegisterSandboxTerminalRoutes registers the interactive-terminal WebSocket.+//+// Like the IM callback routes this is registered BEFORE the global auth+// middleware: a browser WebSocket handshake cannot carry the+// Authorization / X-API-Key headers, so a short-lived session-bound ticket+// travels in the ticket query parameter. The handler authenticates itself+// via service.ParseSandboxTerminalTicket + CheckSandboxTerminalAuth ++// middleware.AttachAuthenticatedUser (not the 24h access JWT). The ticket+// is bound to the minting access-token id; the open PTY rechecks that+// token, user, membership, and session ownership about once a minute.+//+// The wildcard is :id because this GET joins the same radix tree as+// /sessions/:id (gin requires identical wildcard names per tree).+func RegisterSandboxTerminalRoutes(r *gin.Engine, sessionHandler *session.Handler) {+ r.GET("/api/v1/sessions/:id/sandbox/terminal", sessionHandler.SandboxTerminalWS)+}diff --git a/internal/sandbox/capabilities.go b/internal/sandbox/capabilities.goindex 87dbf565b..4afc33e1b 100644--- a/internal/sandbox/capabilities.go+++ b/internal/sandbox/capabilities.go@@ -126,6 +126,27 @@ type SessionInstallCapabilityProvider interface {SessionInstallShellExecutor() SessionInstallShellExecutor}+// SessionTerminalManager opens interactive PTYs on the sandbox bound to a+// session. Like the file store it is provider-neutral: the WebSocket+// handler bridges browser terminal frames to it without knowing whether+// E2B or Cube serves the session.+type SessionTerminalManager interface {+ // OpenSessionTerminal connects to the session's currently bound sandbox+ // and opens a PTY. It is lookup-only: when no live sandbox is bound it+ // returns ErrNoLiveSessionSandbox instead of provisioning one, because+ // the terminal entry point lacks the agent's config-pin context and+ // must not create microVMs as a side effect. A backend that cannot+ // stream PTYs returns ErrTerminalUnsupported, not "no sandbox".+ OpenSessionTerminal(ctx context.Context, sessionID string, opts RemoteTerminalOptions) (RemoteTerminalSession, error)+}++// SessionTerminalProvider is implemented by managers that MAY offer+// interactive terminals. The accessor returns nil when the current runtime+// cannot honour the capability.+type SessionTerminalProvider interface {+ SessionTerminalManager() SessionTerminalManager+}+// SessionTurnHolder marks the start and end of one chat turn on a session's// sandbox. While the turn is open, a stale image mark waits: the first// resolve of the turn may rebuild, later resolves of the same turn keep thediff --git a/internal/sandbox/cube_mock_test.go b/internal/sandbox/cube_mock_test.goindex 59430f5ab..c23ce3120 100644--- a/internal/sandbox/cube_mock_test.go+++ b/internal/sandbox/cube_mock_test.go@@ -40,6 +40,15 @@ type cubeMockServer struct {executor func(sandboxID, cmd string, args []string) (stdout, stderr string, exitCode int)files map[string]map[string][]byte // sandboxID → path → contentcmdHistory []commandRecord+ // ptyHoldAfterStart, when set, keeps the envd PTY stream open and+ // delays the first output chunk so tests can observe HTTP-client+ // timeouts that fire while the stream is still alive.+ ptyHoldAfterStart time.Duration+ ptyLatePayload string+ ptyPID int+ ptyStartCount atomic.Int32+ ptyConnectCount atomic.Int32+ timeoutPOSTs atomic.Int32}type cubeMockSnapshot struct {@@ -89,6 +98,8 @@ func (m *cubeMockServer) handle(w http.ResponseWriter, r *http.Request) {m.handleCreate(w, r)case r.URL.Path == "/sandboxes" && r.Method == http.MethodGet:m.handleList(w, r)+ case strings.HasPrefix(r.URL.Path, "/sandboxes/") && strings.HasSuffix(r.URL.Path, "/timeout") && r.Method == http.MethodPost:+ m.handleSetTimeout(w, r)case strings.HasPrefix(r.URL.Path, "/sandboxes/") && strings.HasSuffix(r.URL.Path, "/connect") && r.Method == http.MethodPost:m.handleConnect(w, r)case strings.HasPrefix(r.URL.Path, "/sandboxes/") && strings.HasSuffix(r.URL.Path, "/snapshots") && r.Method == http.MethodPost:@@ -327,8 +338,17 @@ func (m *cubeMockServer) handleEnvd(w http.ResponseWriter, r *http.Request) {switch {case strings.Contains(r.URL.Path, "/process.Process/Start"):body, _ := io.ReadAll(r.Body)+ if envdBodyLooksLikePty(body) {+ m.ptyStartCount.Add(1)+ m.handlePtyStream(w, r)+ return+ }r.Body = io.NopCloser(bytes.NewBuffer(body))m.handleCommandExec(w, r, sandboxID)+ case strings.Contains(r.URL.Path, "/process.Process/Connect"):+ m.ptyConnectCount.Add(1)+ m.handlePtyStream(w, r)+ returncase strings.Contains(r.URL.Path, "/filesystem") && (strings.Contains(r.URL.Path, "Read") || strings.Contains(r.URL.Path, "Stat") || strings.Contains(r.URL.Path, "ListDir")):m.handleFileRead(w, r, sandboxID)case strings.Contains(r.URL.Path, "/filesystem") && strings.Contains(r.URL.Path, "MakeDir"):@@ -388,6 +408,81 @@ func (m *cubeMockServer) handleCommandExec(w http.ResponseWriter, r *http.RequeswriteEnvdCommandResult(w, stdout, stderr, code)}+func (m *cubeMockServer) handleSetTimeout(w http.ResponseWriter, r *http.Request) {+ id := extractSandboxID(r.URL.Path, "/timeout")+ m.mu.Lock()+ _, ok := m.sandboxes[id]+ m.mu.Unlock()+ if !ok {+ writeJSON(w, http.StatusNotFound, map[string]string{"message": "sandbox not found"})+ return+ }+ m.timeoutPOSTs.Add(1)+ w.WriteHeader(http.StatusNoContent)+}++func envdBodyLooksLikePty(body []byte) bool {+ payload := body+ if len(body) >= 5 {+ n := binary.BigEndian.Uint32(body[1:5])+ if int(n)+5 <= len(body) {+ payload = body[5 : 5+int(n)]+ }+ }+ var req struct {+ PTY json.RawMessage `json:"pty"`+ }+ return json.Unmarshal(payload, &req) == nil && len(req.PTY) > 0+}++func (m *cubeMockServer) handlePtyStream(w http.ResponseWriter, r *http.Request) {+ flusher, _ := w.(http.Flusher)+ pid := m.ptyPID+ if pid == 0 {+ pid = 4321+ }+ late := m.ptyLatePayload+ if late == "" {+ late = "late-frame"+ }+ hold := m.ptyHoldAfterStart++ w.Header().Set("Content-Type", "application/connect+json")+ w.WriteHeader(http.StatusOK)++ startJSON, _ := json.Marshal(map[string]any{+ "event": map[string]any{"start": map[string]any{"pid": pid}},+ })+ var startBuf bytes.Buffer+ writeConnectFrame(&startBuf, startJSON)+ _, _ = w.Write(startBuf.Bytes())+ if flusher != nil {+ flusher.Flush()+ }++ if hold > 0 {+ select {+ case <-r.Context().Done():+ return+ case <-time.After(hold):+ }+ }++ dataJSON, _ := json.Marshal(map[string]any{+ "event": map[string]any{+ "data": map[string]any{"pty": base64Encode(late)},+ },+ })+ var dataBuf bytes.Buffer+ writeConnectFrame(&dataBuf, dataJSON)+ _, _ = w.Write(dataBuf.Bytes())+ if flusher != nil {+ flusher.Flush()+ }++ <-r.Context().Done()+}+func (m *cubeMockServer) handleFileWrite(w http.ResponseWriter, r *http.Request, sandboxID string) {body, _ := io.ReadAll(r.Body)r.Body = io.NopCloser(bytes.NewBuffer(body))diff --git a/internal/sandbox/cube_remote_client.go b/internal/sandbox/cube_remote_client.goindex 49c1130cd..81510fa37 100644--- a/internal/sandbox/cube_remote_client.go+++ b/internal/sandbox/cube_remote_client.go@@ -76,7 +76,10 @@ func NewCubeRemoteClientWithPool(})}// Route both planes through the existing gateway pool while correcting- // the SDK's root-default filesystem identity.+ // the SDK's root-default filesystem identity. The timeout lives in the+ // transport rather than on http.Client so PTY streams, which ride+ // /process.Process/ and hold the response body open for the life of the+ // terminal, are not cut off at CubeHTTPTimeout.routingConfig := *configroutingConfig.Type = SandboxTypeCubehttpClient := &http.Client{@@ -148,6 +151,8 @@ func (c *CubeRemoteClient) Capabilities() RemoteSandboxCapabilities {// CreateOptions still has no volume-mount field; skills ride on// snapshots instead, so this stays false.SupportsVolumes: false,+ // envd exposes an interactive PTY service that the Cube SDK wraps.+ SupportsTerminals: true,}}diff --git a/internal/sandbox/cube_remote_client_test.go b/internal/sandbox/cube_remote_client_test.goindex bef0f0625..08fb345f2 100644--- a/internal/sandbox/cube_remote_client_test.go+++ b/internal/sandbox/cube_remote_client_test.go@@ -35,6 +35,7 @@ func TestCubeRemoteClientProviderAndCapabilities(t *testing.T) {SupportsTimeoutRefresh: true,SupportsFilesystemEnumeration: true,SupportsSnapshots: true,+ SupportsTerminals: true,}, client.Capabilities())}diff --git a/internal/sandbox/cube_terminal.go b/internal/sandbox/cube_terminal.gonew file mode 100644index 000000000..922b09b18--- /dev/null+++ b/internal/sandbox/cube_terminal.go@@ -0,0 +1,183 @@+// Package sandbox: interactive terminal capability for the Cube adapter.+//+// The Cube SDK wraps envd's PTY service (sandbox.Pty) and hands back a+// PtyHandle with an Output channel, so the adapter's job is mostly+// translating between the neutral RemoteTerminal* types and the SDK's.+package sandbox++import (+ "context"+ "strings"+ "sync"+ "time"++ cubesandbox "github.com/tencentcloud/CubeSandbox/sdk/go"+)++// Compile-time proof that the Cube adapter serves the terminal capability.+var _ RemoteTerminalManager = (*CubeRemoteClient)(nil)++// cubeTerminalTimeout bounds the envd stream server-side (Connect-Timeout-Ms)+// and client-side (idle abort). The SDK treats <= 0 as "use its 60s default",+// which would silently kill idle terminals, so WeKnora always passes an+// explicit long window. A session hitting it ends; the frontend reconnects+// and reattaches by PID when the shell is still running.+const cubeTerminalTimeout = 24 * time.Hour++func cubeSandboxTTL(cfg *Config) time.Duration {+ if cfg != nil && cfg.CubeSandboxTTL > 0 {+ return cfg.CubeSandboxTTL+ }+ return DefaultCubeSandboxTTL+}++// OpenTerminal opens an interactive shell PTY inside the sandbox behind+// handle. The returned session keeps streaming until the shell exits, the+// context passed to OpenTerminal is cancelled (the session derives its own+// lifetime from it), or Close is called.+func (c *CubeRemoteClient) OpenTerminal(+ ctx context.Context,+ handle RemoteSandboxHandle,+ opts RemoteTerminalOptions,+) (RemoteTerminalSession, error) {+ if _, err := cubeHandleSandbox("OpenTerminal", handle); err != nil {+ return nil, err+ }+ sandboxID := strings.TrimSpace(handle.ID())++ // Reattach rather than reuse the handle's sandbox so the PTY rides a+ // freshly resolved envd endpoint. The client carries no HTTP-level+ // timeout, and cubeFilesystemTransport exempts /process.Process/, so the+ // stream body is bounded by ctx alone rather than CubeHTTPTimeout.+ sb, err := c.client.Connect(ctx, sandboxID)+ if err != nil {+ return nil, normalizeCubeError("OpenTerminal", err)+ }+ if sb.TrafficAccessToken == "" {+ sb.TrafficAccessToken = handleTrafficAccessToken(handle)+ }++ // The caller's ctx governs the stream (the SDK derives its internal+ // stream context from it); explicit teardown goes through Close.+ ptyHandle, err := openCubePty(ctx, sb, opts)+ if err != nil {+ return nil, normalizeCubeError("OpenTerminal", err)+ }++ session := &cubeTerminalSession{+ sb: sb,+ handle: ptyHandle,+ pid: ptyHandle.PID(),+ out: make(chan RemoteTerminalEvent, terminalOutputBuffer),+ closedCh: make(chan struct{}),+ ttl: cubeSandboxTTL(c.config),+ }+ go session.pump()+ startTerminalTTLRefresh(ctx, session.closedCh, session.ttl, func(rctx context.Context) error {+ if session.sb == nil {+ return nil+ }+ return session.sb.SetTimeout(rctx, session.ttl)+ })+ return session, nil+}++func openCubePty(+ ctx context.Context,+ sb *cubesandbox.Sandbox,+ opts RemoteTerminalOptions,+) (*cubesandbox.PtyHandle, error) {+ size := cubesandbox.PtySize{+ Rows: int(terminalRows(opts)),+ Cols: int(terminalCols(opts)),+ }+ createOpts := cubesandbox.PtyCreateOptions{+ User: terminalUser(opts),+ Cwd: terminalCwd(opts),+ Envs: terminalEnvs(opts),+ Timeout: cubeTerminalTimeout,+ }+ if opts.AttachPID > 0 {+ handle, err := sb.Pty().Connect(ctx, int(opts.AttachPID), cubesandbox.PtyConnectOptions{+ Timeout: cubeTerminalTimeout,+ })+ if err == nil {+ return handle, nil+ }+ }+ return sb.Pty().Create(ctx, size, createOpts)+}++// cubeTerminalSession bridges one Cube PtyHandle to the neutral+// RemoteTerminalSession contract. The SDK's Output channel is closed when+// the stream ends, and Wait also surfaces exit code / error state — pump+// uses Wait so the terminal end is reported exactly once.+type cubeTerminalSession struct {+ sb *cubesandbox.Sandbox+ handle *cubesandbox.PtyHandle+ pid int++ out chan RemoteTerminalEvent+ closedCh chan struct{}+ closeOnce sync.Once+ ttl time.Duration+ // no cancel field: the SDK's handle owns its stream context and+ // Disconnect tears it down.+}++func (s *cubeTerminalSession) pump() {+ defer close(s.out)++ // Every send goes through emitTerminalEvent: Close() can abandon the+ // consumer at any point, and a bare send would strand this goroutine.+ code, err := s.handle.Wait(func(chunk []byte) {+ emitTerminalEvent(s.out, s.closedCh, RemoteTerminalEvent{Data: chunk})+ })+ select {+ case <-s.closedCh:+ return+ default:+ }+ if err != nil {+ emitTerminalEvent(s.out, s.closedCh,+ RemoteTerminalEvent{Err: normalizeCubeError("terminal stream", err)})+ return+ }+ emitTerminalEvent(s.out, s.closedCh, RemoteTerminalEvent{Exited: true, ExitCode: code})+}++func (s *cubeTerminalSession) Output() <-chan RemoteTerminalEvent { return s.out }++func (s *cubeTerminalSession) PID() uint32 { return uint32(s.pid) }++func (s *cubeTerminalSession) Write(ctx context.Context, data []byte) error {+ if len(data) == 0 {+ return nil+ }+ if err := s.handle.SendStdin(ctx, data); err != nil {+ return normalizeCubeError("terminal input", err)+ }+ return nil+}++func (s *cubeTerminalSession) Resize(ctx context.Context, cols, rows uint32) error {+ if cols == 0 || rows == 0 {+ return nil+ }+ if err := s.handle.Resize(ctx, cubesandbox.PtySize{Rows: int(rows), Cols: int(cols)}); err != nil {+ return normalizeCubeError("terminal resize", err)+ }+ return nil+}++// Close disconnects WeKnora from the PTY without killing the remote shell,+// leaving it reattachable via Pty.Connect. Wait unblocks through the+// disconnect without recording a stream error.+func (s *cubeTerminalSession) Close() error {+ // Signal the pump before disconnecting so a blocked onData send cannot+ // race the stream teardown. sync.Once rather than a select/default probe+ // on closedCh: that check-then-close is not atomic, so two concurrent+ // Close calls could both reach close() and panic.+ s.closeOnce.Do(func() { close(s.closedCh) })+ return s.handle.Disconnect()+}diff --git a/internal/sandbox/cube_terminal_test.go b/internal/sandbox/cube_terminal_test.gonew file mode 100644index 000000000..94436bdf5--- /dev/null+++ b/internal/sandbox/cube_terminal_test.go@@ -0,0 +1,176 @@+package sandbox++import (+ "bytes"+ "context"+ "sync"+ "testing"+ "time"++ "github.com/stretchr/testify/require"+)++func pooledCubeClient(t *testing.T, mock *cubeMockServer, httpTimeout time.Duration) *CubeRemoteClient {+ t.Helper()+ cfg := testConfig(t, mock)+ cfg.CubeHTTPTimeout = httpTimeout+ cfg.AllowPrivateEndpoints = true+ policy := OutboundURLPolicy{AllowPrivate: true}+ pool := NewSandboxGatewayTransportPoolWithPolicy(+ NewGuardedTransportWithPolicy(policy),+ policy,+ )+ client, err := NewCubeRemoteClientWithPool(cfg, pool)+ require.NoError(t, err)+ return client+}++func TestCubeOpenTerminalStreamSurvivesHTTPClientTimeout(t *testing.T) {+ mock := newCubeMockServer(t)+ mock.ptyHoldAfterStart = 300 * time.Millisecond+ mock.ptyLatePayload = "late-frame"+ client := pooledCubeClient(t, mock, 120*time.Millisecond)++ ctx := context.Background()+ handle, err := client.Create(ctx, RemoteCreateRequest{+ TemplateID: "template-a",+ Timeout: RemoteTimeoutPolicy{+ Mode: RemoteTimeoutExplicit,+ Value: time.Minute,+ Action: RemoteOnTimeoutKill,+ },+ })+ require.NoError(t, err)++ session, err := client.OpenTerminal(ctx, handle, RemoteTerminalOptions{Cols: 80, Rows: 24})+ require.NoError(t, err)+ t.Cleanup(func() { _ = session.Close() })++ deadline := time.After(time.Second)+ var got []byte+ for {+ select {+ case ev, ok := <-session.Output():+ if !ok {+ t.Fatalf("PTY stream closed before the late frame; collected %q", got)+ }+ if ev.Err != nil {+ t.Fatalf("PTY stream failed before the late frame: %v (collected %q)", ev.Err, got)+ }+ got = append(got, ev.Data...)+ if bytes.Contains(got, []byte("late-frame")) {+ return+ }+ case <-deadline:+ t.Fatalf("timed out waiting for late PTY frame; collected %q", got)+ }+ }+}++func TestCubeOpenTerminalRefreshesSandboxTTL(t *testing.T) {+ prevMin := terminalTTLRefreshMin+ terminalTTLRefreshMin = 40 * time.Millisecond+ t.Cleanup(func() { terminalTTLRefreshMin = prevMin })++ mock := newCubeMockServer(t)+ mock.ptyHoldAfterStart = time.Second+ client := pooledCubeClient(t, mock, 5*time.Second)+ cfg := testConfig(t, mock)+ cfg.CubeSandboxTTL = 3 * time.Second+ client.config = cfg++ ctx := context.Background()+ handle, err := client.Create(ctx, RemoteCreateRequest{+ TemplateID: "template-a",+ Timeout: RemoteTimeoutPolicy{+ Mode: RemoteTimeoutExplicit,+ Value: time.Minute,+ Action: RemoteOnTimeoutKill,+ },+ })+ require.NoError(t, err)++ session, err := client.OpenTerminal(ctx, handle, RemoteTerminalOptions{})+ require.NoError(t, err)+ t.Cleanup(func() { _ = session.Close() })++ require.Eventually(t, func() bool {+ return mock.timeoutPOSTs.Load() >= 1+ }, 2*time.Second, 20*time.Millisecond, "expected SetTimeout while the PTY is open")+}++func TestCubeOpenTerminalReattachesByPID(t *testing.T) {+ mock := newCubeMockServer(t)+ client := pooledCubeClient(t, mock, 5*time.Second)++ ctx := context.Background()+ handle, err := client.Create(ctx, RemoteCreateRequest{+ TemplateID: "template-a",+ Timeout: RemoteTimeoutPolicy{+ Mode: RemoteTimeoutExplicit,+ Value: time.Minute,+ Action: RemoteOnTimeoutKill,+ },+ })+ require.NoError(t, err)++ session, err := client.OpenTerminal(ctx, handle, RemoteTerminalOptions{AttachPID: 99})+ require.NoError(t, err)+ t.Cleanup(func() { _ = session.Close() })+ require.Equal(t, int32(1), mock.ptyConnectCount.Load())+ require.Equal(t, int32(0), mock.ptyStartCount.Load())+ require.Equal(t, uint32(4321), session.PID())+}++// RemoteTerminalSession documents Close as safe to call more than once, and+// the bridge can reach it from several goroutines. A check-then-close probe+// on the teardown channel would panic here.+func TestCubeTerminalCloseIsIdempotentUnderConcurrency(t *testing.T) {+ mock := newCubeMockServer(t)+ mock.ptyHoldAfterStart = time.Second+ client := pooledCubeClient(t, mock, 5*time.Second)++ ctx := context.Background()+ handle, err := client.Create(ctx, RemoteCreateRequest{+ TemplateID: "template-a",+ Timeout: RemoteTimeoutPolicy{+ Mode: RemoteTimeoutExplicit,+ Value: time.Minute,+ Action: RemoteOnTimeoutKill,+ },+ })+ require.NoError(t, err)++ session, err := client.OpenTerminal(ctx, handle, RemoteTerminalOptions{})+ require.NoError(t, err)++ drained := make(chan struct{})+ go func() {+ defer close(drained)+ for range session.Output() {+ }+ }()++ // A shared start barrier: the racy version's window between "channel+ // looks open" and close() is only a few nanoseconds, so staggered+ // goroutines would sail past it.+ start := make(chan struct{})+ var wg sync.WaitGroup+ for i := 0; i < 64; i++ {+ wg.Add(1)+ go func() {+ defer wg.Done()+ <-start+ _ = session.Close()+ }()+ }+ close(start)+ wg.Wait()++ // The pump must also terminate, closing Output exactly once.+ select {+ case <-drained:+ case <-time.After(3 * time.Second):+ t.Fatal("Output channel never closed after Close")+ }+}diff --git a/internal/sandbox/e2b_remote_client.go b/internal/sandbox/e2b_remote_client.goindex a620c628a..3fd5df6f9 100644--- a/internal/sandbox/e2b_remote_client.go+++ b/internal/sandbox/e2b_remote_client.go@@ -172,6 +172,8 @@ func (c *E2BRemoteClient) Capabilities() RemoteSandboxCapabilities {// E2B has no named-volume mount API that WeKnora can use; advertising// it would let a workspace configure a mount that never appears.SupportsVolumes: false,+ // envd exposes an interactive PTY service that go-e2b wraps.+ SupportsTerminals: true,}}diff --git a/internal/sandbox/e2b_remote_client_test.go b/internal/sandbox/e2b_remote_client_test.goindex 163149032..6d681ebbf 100644--- a/internal/sandbox/e2b_remote_client_test.go+++ b/internal/sandbox/e2b_remote_client_test.go@@ -373,6 +373,7 @@ func TestE2BRemoteClientProviderAndCapabilities(t *testing.T) {SupportsFilesystemEnumeration: true,SupportsSnapshots: true,SupportsVolumes: false,+ SupportsTerminals: true,}, client.Capabilities())}diff --git a/internal/sandbox/e2b_terminal.go b/internal/sandbox/e2b_terminal.gonew file mode 100644index 000000000..e7a02ab45--- /dev/null+++ b/internal/sandbox/e2b_terminal.go@@ -0,0 +1,208 @@+// Package sandbox: interactive terminal capability for the E2B adapter.+//+// go-e2b wraps envd's PTY service (sandbox.Pty). Output is delivered through+// a Wait-driven callback, so the adapter pumps it into a channel from a+// dedicated goroutine; input and resize are plain unary RPCs on the same+// service.+package sandbox++import (+ "context"+ "errors"+ "strings"+ "sync"++ e2b "github.com/matiasinsaurralde/go-e2b"+)++// Compile-time proof that the E2B adapter serves the terminal capability.+var _ RemoteTerminalManager = (*E2BRemoteClient)(nil)++// OpenTerminal opens an interactive shell PTY inside the sandbox behind+// handle. The returned session keeps streaming until the shell exits, the+// context passed to OpenTerminal is cancelled (the session derives its own+// lifetime from it), or Close is called.+func (c *E2BRemoteClient) OpenTerminal(+ ctx context.Context,+ handle RemoteSandboxHandle,+ opts RemoteTerminalOptions,+) (RemoteTerminalSession, error) {+ if _, err := e2bHandleSandbox("OpenTerminal", handle); err != nil {+ return nil, err+ }+ sandboxID := strings.TrimSpace(handle.ID())++ // Reattach rather than reuse the handle's sandbox: the connect refreshes+ // the sandbox lifetime exactly like RemoteSandboxClient.Connect does,+ // which doubles as the activity signal for TTL-based reclamation. The+ // client carries no HTTP-level timeout, and e2bRPCTimeoutTransport+ // exempts the PTY's Start/Connect routes, so the stream is bounded by+ // ptyCtx alone rather than by E2BHTTPTimeout.+ timeoutSeconds, err := e2bTimeoutSeconds(RemoteTimeoutPolicy{Mode: RemoteTimeoutServerDefault}, c.timeout)+ if err != nil {+ return nil, normalizeE2BError("OpenTerminal", err)+ }+ sbx, err := c.client.Connect(ctx, sandboxID, timeoutSeconds)+ if err != nil {+ return nil, normalizeE2BError("OpenTerminal", err)+ }+ if sbx.TrafficAccessToken == "" {+ sbx.TrafficAccessToken = handleTrafficAccessToken(handle)+ }+ c.inboundTokens.Put(sbx.ID, sbx.TrafficAccessToken)++ // The terminal session — not the SDK's per-command timeout — owns the+ // PTY lifetime: WithPtyTimeout(0) disables the context wrapping so the+ // stream survives as long as ptyCtx below.+ ptyOpts := []e2b.PtyOption{+ e2b.WithPtyTimeout(0),+ e2b.WithPtyCwd(terminalCwd(opts)),+ e2b.WithPtyUser(terminalUser(opts)),+ }+ if envs := terminalEnvs(opts); len(envs) > 0 {+ ptyOpts = append(ptyOpts, e2b.WithPtyEnv(envs))+ }++ ptyCtx, cancel := context.WithCancel(ctx)+ cmdHandle, err := openE2BPty(ptyCtx, sbx, opts, ptyOpts)+ if err != nil {+ cancel()+ return nil, normalizeE2BError("OpenTerminal", err)+ }++ session := &e2bTerminalSession{+ sbx: sbx,+ handle: cmdHandle,+ pid: cmdHandle.PID(),+ out: make(chan RemoteTerminalEvent, terminalOutputBuffer),+ ctx: ptyCtx,+ cancel: cancel,+ closedCh: make(chan struct{}),+ timeoutSeconds: timeoutSeconds,+ }+ // envd SendInput is a unary RPC. Waiting for it on the WebSocket read+ // path makes typing feel one-RTT-per-key; E2B's data plane is far+ // enough that that is noticeable. Queue and coalesce instead.+ session.input = newPtyInputCoalescer(ptyCtx, session.closedCh, func(rctx context.Context, data []byte) error {+ return session.sbx.Pty.SendInput(rctx, session.pid, data)+ })+ go session.pump()+ if timeoutSeconds > 0 {+ startTerminalTTLRefresh(ptyCtx, session.closedCh, c.timeout, func(rctx context.Context) error {+ return session.sbx.SetTimeoutWithContext(rctx, session.timeoutSeconds)+ })+ }+ return session, nil+}++func openE2BPty(+ ctx context.Context,+ sbx *e2b.Sandbox,+ opts RemoteTerminalOptions,+ ptyOpts []e2b.PtyOption,+) (*e2b.CommandHandle, error) {+ if opts.AttachPID > 0 {+ handle, err := sbx.Pty.Connect(ctx, opts.AttachPID, ptyOpts...)+ if err == nil {+ return handle, nil+ }+ }+ return sbx.Pty.Create(ctx, terminalCols(opts), terminalRows(opts), ptyOpts...)+}++// e2bTerminalSession bridges one go-e2b PTY handle to the neutral+// RemoteTerminalSession contract.+type e2bTerminalSession struct {+ sbx *e2b.Sandbox+ handle *e2b.CommandHandle+ pid uint32++ out chan RemoteTerminalEvent+ ctx context.Context+ cancel context.CancelFunc+ closedCh chan struct{}+ closeOnce sync.Once+ timeoutSeconds int+ input *ptyInputCoalescer+}++// pump drains the PTY event stream. go-e2b dispatches output only while+// Wait runs, so the Wait call lives here for the whole session. The output+// channel closes exactly once, when pump returns.+func (s *e2bTerminalSession) pump() {+ defer close(s.out)++ result, err := s.handle.Wait(s.ctx, e2b.WithWaitOnPty(func(chunk []byte) {+ s.emit(RemoteTerminalEvent{Data: chunk})+ }))++ // Close (or OpenTerminal-context cancellation) tears the stream down;+ // that is teardown, not a terminal failure — report nothing further.+ select {+ case <-s.closedCh:+ return+ default:+ }++ if err != nil {+ var exitErr *e2b.CommandExitError+ if errors.As(err, &exitErr) {+ // The shell exited with a non-zero status. That is still a+ // normal terminal end from the consumer's point of view.+ s.emit(RemoteTerminalEvent{Exited: true, ExitCode: exitErr.ExitCode})+ return+ }+ s.emit(RemoteTerminalEvent{Err: normalizeE2BError("terminal stream", err)})+ return+ }+ code := -1+ if result != nil {+ code = result.ExitCode+ }+ s.emit(RemoteTerminalEvent{Exited: true, ExitCode: code})+}++func (s *e2bTerminalSession) emit(event RemoteTerminalEvent) {+ emitTerminalEvent(s.out, s.closedCh, event)+}++func (s *e2bTerminalSession) Output() <-chan RemoteTerminalEvent { return s.out }++func (s *e2bTerminalSession) PID() uint32 { return s.pid }++func (s *e2bTerminalSession) Write(ctx context.Context, data []byte) error {+ if s.input == nil {+ if len(data) == 0 {+ return nil+ }+ if err := s.sbx.Pty.SendInput(ctx, s.pid, data); err != nil {+ return normalizeE2BError("terminal input", err)+ }+ return nil+ }+ if err := s.input.Write(ctx, data); err != nil {+ return normalizeE2BError("terminal input", err)+ }+ return nil+}++func (s *e2bTerminalSession) Resize(ctx context.Context, cols, rows uint32) error {+ if cols == 0 || rows == 0 {+ return nil+ }+ if err := s.sbx.Pty.Resize(ctx, s.pid, cols, rows); err != nil {+ return normalizeE2BError("terminal resize", err)+ }+ return nil+}++// Close disconnects WeKnora from the PTY without killing the remote shell,+// leaving it reattachable via Pty.Connect. The pump goroutine observes the+// disconnect and closes the output channel silently.+func (s *e2bTerminalSession) Close() error {+ s.closeOnce.Do(func() {+ close(s.closedCh)+ s.cancel()+ })+ return s.handle.Disconnect()+}diff --git a/internal/sandbox/langfuse.go b/internal/sandbox/langfuse.goindex e2695b6a7..2d413dd72 100644--- a/internal/sandbox/langfuse.go+++ b/internal/sandbox/langfuse.go@@ -280,7 +280,35 @@ func truncateSandboxPreview(s string) string {return string(runes[:sandboxSpanPreviewRunes]) + "…"}+// OpenTerminal forwards the interactive-terminal capability so wrapping does+// not hide RemoteTerminalManager from TerminalManagerFrom.+//+// It lives on the base decorator (not on a dedicated one like+// langfuseSnapshotClient) so *every* wrapping shape exposes the capability:+// langfuseSnapshotClient embeds this type, so it inherits the method.+// Whether a backend actually supports terminals stays delegated to the inner+// client's SupportsTerminals flag, which the *From helpers check.+func (c *langfuseRemoteClient) OpenTerminal(+ ctx context.Context,+ handle RemoteSandboxHandle,+ opts RemoteTerminalOptions,+) (RemoteTerminalSession, error) {+ inner, ok := c.inner.(RemoteTerminalManager)+ if !ok {+ return nil, &RemoteError{+ Kind: RemoteErrorKindUnsupported,+ Op: "OpenTerminal",+ Message: "inner client has no terminal manager",+ }+ }+ ctx, span := startSandboxSpan(ctx, "sandbox.open_terminal", sandboxHandleOut(handle), nil)+ session, err := inner.OpenTerminal(ctx, handle, opts)+ span.Finish(sandboxHandleOut(handle), nil, err)+ return session, err+}+var (_ RemoteSandboxClient = (*langfuseRemoteClient)(nil)_ RemoteSnapshotManager = (*langfuseSnapshotClient)(nil)+ _ RemoteTerminalManager = (*langfuseRemoteClient)(nil))diff --git a/internal/sandbox/langfuse_test.go b/internal/sandbox/langfuse_test.goindex 8687bbf14..8d69701f7 100644--- a/internal/sandbox/langfuse_test.go+++ b/internal/sandbox/langfuse_test.go@@ -54,6 +54,51 @@ func TestWrapLangfuseRemoteClientExecForwards(t *testing.T) {require.Equal(t, "echo hi", inner.execRequests[0].Command)}+func TestWrapLangfuseRemoteClientPreservesTerminalCapability(t *testing.T) {+ inner := &terminalFakeClient{fakeRemoteClient: newFakeRemoteClient(SandboxTypeCube)}+ inner.capabilities.SupportsTerminals = true++ wrapped := wrapLangfuseRemoteClient(inner)+ mgr, ok := TerminalManagerFrom(wrapped)+ require.True(t, ok, "wrapping must not hide RemoteTerminalManager from TerminalManagerFrom")+ require.NotNil(t, mgr)++ session, err := mgr.OpenTerminal(context.Background(), nil, RemoteTerminalOptions{Cols: 80, Rows: 24})+ require.NoError(t, err)+ require.NotNil(t, session)+}++func TestWrapLangfuseRemoteClientDoesNotInventTerminalSupport(t *testing.T) {+ // Docker advertises no terminal support; wrapping must not fake it.+ inner := newFakeRemoteClient(SandboxTypeDocker)+ wrapped := wrapLangfuseRemoteClient(inner)+ mgr, ok := TerminalManagerFrom(wrapped)+ require.False(t, ok)+ require.Nil(t, mgr)+}++// terminalFakeClient adds the optional terminal capability to the shared fake+// so wrapper tests can assert capability forwarding.+type terminalFakeClient struct {+ *fakeRemoteClient+}++func (c *terminalFakeClient) OpenTerminal(+ _ context.Context, _ RemoteSandboxHandle, _ RemoteTerminalOptions,+) (RemoteTerminalSession, error) {+ return &terminalFakeSession{}, nil+}++type terminalFakeSession struct{}++func (s *terminalFakeSession) Output() <-chan RemoteTerminalEvent { return nil }+func (s *terminalFakeSession) PID() uint32 { return 1 }+func (s *terminalFakeSession) Write(context.Context, []byte) error { return nil }+func (s *terminalFakeSession) Resize(context.Context, uint32, uint32) error {+ return nil+}+func (s *terminalFakeSession) Close() error { return nil }+func TestTruncateSandboxPreview(t *testing.T) {require.Equal(t, "short", truncateSandboxPreview("short"))long := strings.Repeat("x", sandboxSpanPreviewRunes+8)diff --git a/internal/sandbox/pty_input_coalesce.go b/internal/sandbox/pty_input_coalesce.gonew file mode 100644index 000000000..6a197dbe6--- /dev/null+++ b/internal/sandbox/pty_input_coalesce.go@@ -0,0 +1,96 @@+package sandbox++import (+ "context"+ "errors"+ "time"+)++const (+ ptyInputCoalesceMax = 4096+ ptyInputQueueDepth = 64+)++var errPtyInputClosed = errors.New("terminal input closed")++// ptyInputCoalescer turns many small Write calls into fewer send() RPCs,+// and never blocks Write on the RPC itself (unless the queue is full).+//+// The first queued chunk is sent immediately. Further keystrokes that arrive+// while that RPC is in flight are drained and sent as one follow-up, so burst+// typing shares RPCs without a Nagle-style pause on the first character.+type ptyInputCoalescer struct {+ send func(context.Context, []byte) error+ ch chan []byte+ done <-chan struct{}+ ctx context.Context+}++func newPtyInputCoalescer(+ ctx context.Context,+ done <-chan struct{},+ send func(context.Context, []byte) error,+) *ptyInputCoalescer {+ c := &ptyInputCoalescer{+ send: send,+ ch: make(chan []byte, ptyInputQueueDepth),+ done: done,+ ctx: ctx,+ }+ go c.loop()+ return c+}++func (c *ptyInputCoalescer) Write(ctx context.Context, data []byte) error {+ if len(data) == 0 {+ return nil+ }+ chunk := append([]byte(nil), data...)+ select {+ case <-c.done:+ return errPtyInputClosed+ case <-ctx.Done():+ return ctx.Err()+ case c.ch <- chunk:+ return nil+ }+}++func (c *ptyInputCoalescer) loop() {+ for {+ select {+ case <-c.done:+ return+ case first := <-c.ch:+ buf := append([]byte(nil), first...)+ buf = c.drain(buf)+ c.flush(buf)+ }+ }+}++func (c *ptyInputCoalescer) drain(buf []byte) []byte {+ for len(buf) < ptyInputCoalesceMax {+ select {+ case more := <-c.ch:+ buf = append(buf, more...)+ default:+ return buf+ }+ }+ return buf+}++func (c *ptyInputCoalescer) flush(buf []byte) {+ if len(buf) == 0 || c.send == nil {+ return+ }+ select {+ case <-c.done:+ return+ default:+ }+ rctx, cancel := context.WithTimeout(c.ctx, 5*time.Second)+ _ = c.send(rctx, buf)+ cancel()+}diff --git a/internal/sandbox/pty_input_coalesce_test.go b/internal/sandbox/pty_input_coalesce_test.gonew file mode 100644index 000000000..8cf78f553--- /dev/null+++ b/internal/sandbox/pty_input_coalesce_test.go@@ -0,0 +1,70 @@+package sandbox++import (+ "context"+ "sync"+ "testing"+ "time"++ "github.com/stretchr/testify/require"+)++func TestPtyInputCoalescerWriteDoesNotWaitForSendRTT(t *testing.T) {+ var mu sync.Mutex+ var got []byte+ var calls int++ closed := make(chan struct{})+ t.Cleanup(func() { close(closed) })++ c := newPtyInputCoalescer(context.Background(), closed, func(_ context.Context, data []byte) error {+ time.Sleep(40 * time.Millisecond)+ mu.Lock()+ calls+++ got = append(got, data...)+ mu.Unlock()+ return nil+ })++ ctx := context.Background()+ start := time.Now()+ for _, b := range []byte("hello") {+ require.NoError(t, c.Write(ctx, []byte{b}))+ }+ require.Less(t, time.Since(start), 25*time.Millisecond,+ "Write must enqueue instead of waiting for each SendInput round-trip")++ require.Eventually(t, func() bool {+ mu.Lock()+ defer mu.Unlock()+ return string(got) == "hello"+ }, time.Second, 5*time.Millisecond)++ mu.Lock()+ n := calls+ mu.Unlock()+ require.Less(t, n, 5, "burst keystrokes should share SendInput RPCs, got %d", n)+}++func TestPtyInputCoalescerSendsFirstChunkWithoutWaiting(t *testing.T) {+ started := make(chan struct{})+ closed := make(chan struct{})+ t.Cleanup(func() { close(closed) })++ c := newPtyInputCoalescer(context.Background(), closed, func(_ context.Context, _ []byte) error {+ select {+ case <-started:+ default:+ close(started)+ }+ time.Sleep(50 * time.Millisecond)+ return nil+ })++ require.NoError(t, c.Write(context.Background(), []byte("x")))+ select {+ case <-started:+ case <-time.After(20 * time.Millisecond):+ t.Fatal("first keystroke must start SendInput immediately, not after a coalesce timer")+ }+}diff --git a/internal/sandbox/remote_client.go b/internal/sandbox/remote_client.goindex fa9d9b366..36eb28d86 100644--- a/internal/sandbox/remote_client.go+++ b/internal/sandbox/remote_client.go@@ -428,6 +428,12 @@ type RemoteSandboxCapabilities struct {// use this to tell an operator up front that a backend cannot serve// volume-based features, instead of failing later at first use.SupportsVolumes bool++ // SupportsTerminals is true when the provider can open interactive PTYs+ // inside a running sandbox (RemoteTerminalManager). Callers use this to+ // reject terminal features with an unsupported-backend error instead of+ // failing after the WebSocket is upgraded.+ SupportsTerminals bool}// RemoteSandboxClient is the contract SessionBoundManager talks to. Alldiff --git a/internal/sandbox/sandbox.go b/internal/sandbox/sandbox.goindex 1416e7cb3..8e53e01cb 100644--- a/internal/sandbox/sandbox.go+++ b/internal/sandbox/sandbox.go@@ -106,6 +106,16 @@ var (ErrDangerousCommand = errors.New("script contains dangerous command")ErrArgInjection = errors.New("argument injection detected")ErrStdinInjection = errors.New("stdin injection detected")+ // ErrNoLiveSessionSandbox is returned by lookup-only entry points (the+ // interactive terminal) when the session has no currently bound sandbox.+ // Unlike Execute, these entry points never provision: creating a sandbox+ // needs the agent's config-pin context, which they do not carry.+ ErrNoLiveSessionSandbox = errors.New("session has no live sandbox")+ // ErrTerminalUnsupported is returned when the active backend cannot+ // stream PTYs (Docker, a disabled manager). Distinct from+ // ErrNoLiveSessionSandbox: the session may well have a live sandbox,+ // it just cannot host an interactive terminal.+ ErrTerminalUnsupported = errors.New("sandbox backend does not support interactive terminals"))// Sandbox defines the interface for isolated script execution@@ -232,6 +242,11 @@ type Config struct {// DefaultTimeout is the default execution timeoutDefaultTimeout time.Duration+ // TerminalIdleDisconnect is how long an open interactive terminal may+ // go without input or PTY output before the WebSocket is closed. Zero+ // is treated as DefaultTerminalIdleDisconnect at use time.+ TerminalIdleDisconnect time.Duration+// AllowPrivateEndpoints is the per-workspace outbound policy for this// connection. Link-local addresses are blocked regardless.AllowPrivateEndpoints booldiff --git a/internal/sandbox/session_manager.go b/internal/sandbox/session_manager.goindex d261fb32b..527095194 100644--- a/internal/sandbox/session_manager.go+++ b/internal/sandbox/session_manager.go@@ -226,6 +226,16 @@ func (m *SessionBoundManager) GetType() SandboxType {return m.activeType}+// TerminalIdleDisconnect is how long an open PTY may sit idle before the+// WebSocket is closed. Missing or out-of-range workspace values are clamped+// onto the built-in default so a stored 0 still disconnects.+func (m *SessionBoundManager) TerminalIdleDisconnect() time.Duration {+ if m == nil || m.config == nil {+ return DefaultTerminalIdleDisconnect+ }+ return EffectiveTerminalIdleDisconnect(m.config.TerminalIdleDisconnect)+}+// GetSandbox exposes a diagnostic Sandbox for callers that need to inspect// availability. Returns a stateless RemoteSandbox surface for the current// provider.@@ -810,6 +820,46 @@ func (m *SessionBoundManager) SessionFileStore() SessionFileStore {return m}+// SessionTerminalManager advertises the interactive-terminal capability while+// a real remote backend is active and the provider implements PTY streaming+// (E2B and Cube do; Docker does not).+func (m *SessionBoundManager) SessionTerminalManager() SessionTerminalManager {+ if m == nil || m.remoteDisabled() {+ return nil+ }+ if _, ok := TerminalManagerFrom(m.client); !ok {+ return nil+ }+ return m+}++// OpenSessionTerminal opens a PTY on the sandbox currently bound to the+// session. It is strictly lookup-only: with no live binding it returns+// ErrNoLiveSessionSandbox instead of provisioning, because the terminal+// entry point lacks the config-pin context that agent-driven creation+// relies on. A backend that cannot stream PTYs (Docker) returns+// ErrTerminalUnsupported, not "no sandbox".+func (m *SessionBoundManager) OpenSessionTerminal(+ ctx context.Context,+ sessionID string,+ opts RemoteTerminalOptions,+) (RemoteTerminalSession, error) {+ terminal, ok := TerminalManagerFrom(m.client)+ if !ok {+ return nil, ErrTerminalUnsupported+ }+ handle, found, err := m.lookupSessionHandle(ctx, sessionID)+ if err != nil {+ return nil, err+ }+ if !found {+ return nil, ErrNoLiveSessionSandbox+ }+ return terminal.OpenTerminal(ctx, handle, opts)+}++var _ SessionTerminalProvider = (*SessionBoundManager)(nil)+// Cleanup marks the manager closed. Session sandboxes are not force-deleted// here: their lifecycle is authoritative in the binding store and would// leak to any other WeKnora replica if this replica reaped them on shutdown.diff --git a/internal/sandbox/session_manager_test.go b/internal/sandbox/session_manager_test.goindex c83a3c5f7..f41f427f9 100644--- a/internal/sandbox/session_manager_test.go+++ b/internal/sandbox/session_manager_test.go@@ -475,3 +475,14 @@ func lastExecRequest(t *testing.T, client *fakeRemoteClient) RemoteExecRequest {require.NotEmpty(t, client.execRequests)return client.execRequests[len(client.execRequests)-1]}++// Direct callers of OpenSessionTerminal (tests, a future handler that skips+// the service layer) must not see "no live sandbox" when the backend simply+// cannot stream PTYs. The service layer already maps this, but the manager+// is the source of truth.+func TestSessionBoundManagerOpenSessionTerminalUnsupportedBackend(t *testing.T) {+ mgr, _ := newSessionManagerExecTestHarness(t)+ _, err := mgr.OpenSessionTerminal(context.Background(), "session-a", RemoteTerminalOptions{})+ require.ErrorIs(t, err, ErrTerminalUnsupported)+ require.NotErrorIs(t, err, ErrNoLiveSessionSandbox)+}diff --git a/internal/sandbox/tenant_config.go b/internal/sandbox/tenant_config.goindex 90bc1fadd..506a363cc 100644--- a/internal/sandbox/tenant_config.go+++ b/internal/sandbox/tenant_config.go@@ -60,6 +60,12 @@ func ResolveEffectiveConfig(effective.Type = resolved}overrideSeconds(&effective.DefaultTimeout, tenantCfg.DefaultTimeoutSec)+ // Terminal idle is workspace policy, not a deployment default: an omitted+ // value must fall back to the built-in 15 minutes, never to whatever the+ // process Config happened to carry.+ effective.TerminalIdleDisconnect = 0+ overrideSeconds(&effective.TerminalIdleDisconnect, tenantCfg.TerminalIdleDisconnectSec)+ effective.TerminalIdleDisconnect = EffectiveTerminalIdleDisconnect(effective.TerminalIdleDisconnect)effective.AllowPrivateEndpoints = tenantCfg.AllowPrivateEndpointseffective.Network = resolveNetworkPolicy(tenantCfg.Network)if tenantCfg.EnvVars != nil {diff --git a/internal/sandbox/tenant_config_test.go b/internal/sandbox/tenant_config_test.goindex 287b60e9d..e10a44dc7 100644--- a/internal/sandbox/tenant_config_test.go+++ b/internal/sandbox/tenant_config_test.go@@ -390,6 +390,7 @@ func TestResolveEffectiveConfigAppliesTimeoutsAndTTL(t *testing.T) {tenantCfg.DefaultTimeoutSec = 90tenantCfg.E2B.HTTPTimeoutSec = 15tenantCfg.E2B.E2BSandboxTTLSeconds = 600+ tenantCfg.TerminalIdleDisconnectSec = 1200got, err := ResolveEffectiveConfig(tenantCfg, global)@@ -397,6 +398,17 @@ func TestResolveEffectiveConfigAppliesTimeoutsAndTTL(t *testing.T) {require.Equal(t, 90*time.Second, got.DefaultTimeout)require.Equal(t, 15*time.Second, got.E2BHTTPTimeout)require.Equal(t, 600*time.Second, got.E2BSandboxTTL)+ require.Equal(t, 20*time.Minute, got.TerminalIdleDisconnect)+}++func TestResolveEffectiveConfigTerminalIdleFallsBackToBuiltIn(t *testing.T) {+ global := globalTestConfig()+ global.TerminalIdleDisconnect = 3 * time.Hour++ got, err := ResolveEffectiveConfig(completeE2BTenantConfig(), global)++ require.NoError(t, err)+ require.Equal(t, DefaultTerminalIdleDisconnect, got.TerminalIdleDisconnect)}// Tuning fields fall back to the built-in constants, never to the deployment's:diff --git a/internal/sandbox/terminal.go b/internal/sandbox/terminal.gonew file mode 100644index 000000000..5ca83b1fb--- /dev/null+++ b/internal/sandbox/terminal.go@@ -0,0 +1,277 @@+// Package sandbox: interactive terminal (PTY) capability.+//+// The terminal is an optional, provider-neutral capability alongside+// RemoteSnapshotManager. SessionBoundManager surfaces it only when the+// active backend implements PTY streaming; the WebSocket handler in the+// application layer bridges browser terminals to it.+package sandbox++import (+ "context"+ "strings"+ "time"+)++// RemoteTerminalOptions carries the neutral parameters for opening a PTY.+// Adapters translate these into their provider SDK's equivalent knobs.+type RemoteTerminalOptions struct {+ // Cols/Rows is the initial terminal size. Zero falls back to 80x24.+ Cols uint32+ Rows uint32++ // Cwd is the shell's working directory. Empty means the sandbox+ // default (/workspace).+ Cwd string++ // User is the account the shell runs as. Empty means+ // DefaultSandboxExecUser.+ User string++ // Envs are extra environment variables. TERM is always forced to a+ // 256-colour value by the adapters so full-screen programs work.+ Envs map[string]string++ // AttachPID, when non-zero, asks the provider to reattach to an+ // already-running PTY instead of creating a new shell. A failed+ // reattach falls back to Create.+ AttachPID uint32+}++// RemoteTerminalEvent is one event on a terminal's output stream. The+// channel returned by RemoteTerminalSession.Output closes when the terminal+// session ends (process exit, disconnect, or provider error).+type RemoteTerminalEvent struct {+ // Data is raw PTY output bytes. Nil for non-data events.+ Data []byte++ // Exited is true when the remote shell process terminated. ExitCode is+ // meaningful only then.+ Exited bool+ // ExitCode is the shell's exit code (may be unavailable; -1 fallback).+ ExitCode int++ // Err is set when the stream ended abnormally (transport failure,+ // provider error). A normal process exit leaves it nil.+ Err error+}++// RemoteTerminalSession is a neutral handle to one live PTY. Implementations+// MUST be safe for concurrent Write/Resize calls alongside the Output+// consumer goroutine.+type RemoteTerminalSession interface {+ // Output streams PTY output events. The channel is closed exactly once+ // when the terminal session ends; consumers must not send to it.+ Output() <-chan RemoteTerminalEvent++ // PID is the remote shell's process ID, when the provider exposes one.+ PID() uint32++ // Write feeds raw bytes (keystrokes) into the PTY.+ Write(ctx context.Context, data []byte) error++ // Resize changes the PTY window size.+ Resize(ctx context.Context, cols, rows uint32) error++ // Close disconnects WeKnora from the PTY without killing the remote+ // process: the shell stays in the sandbox so a provider-native+ // reconnect can re-attach. Safe to call more than once.+ Close() error+}++// emitTerminalEvent hands one event to the Output consumer, giving up as+// soon as teardown starts.+//+// Adapters MUST route every send through it. A bare send races Close: once+// the consumer has stopped draining (it returns on the first error/exit+// event) and the buffer is full, the send blocks forever, the pump goroutine+// never reaches its `defer close(out)`, and the provider stream leaks with+// it.+func emitTerminalEvent(+ out chan<- RemoteTerminalEvent,+ closed <-chan struct{},+ event RemoteTerminalEvent,+) {+ select {+ case out <- event:+ case <-closed:+ }+}++// terminalOutputBuffer bounds queued PTY output between pump dispatches. A+// slow consumer applies backpressure to the envd stream rather than losing+// bytes.+const terminalOutputBuffer = 256++// The terminal*(opts) helpers below resolve one neutral option to the value+// an adapter should hand its SDK. They live here, not in a provider file,+// because every adapter needs them: removing one backend must not take the+// other's defaults with it.++func terminalCols(opts RemoteTerminalOptions) uint32 {+ if opts.Cols > 0 {+ return opts.Cols+ }+ return 80+}++func terminalRows(opts RemoteTerminalOptions) uint32 {+ if opts.Rows > 0 {+ return opts.Rows+ }+ return 24+}++func terminalCwd(opts RemoteTerminalOptions) string {+ if cwd := strings.TrimSpace(opts.Cwd); cwd != "" {+ return cwd+ }+ return "/workspace"+}++func terminalUser(opts RemoteTerminalOptions) string {+ if user := strings.TrimSpace(opts.User); user != "" {+ return user+ }+ return DefaultSandboxExecUser+}++// terminalEnvs merges caller envs over the interactive defaults the SDK+// already applies (TERM/LANG/LC_ALL), never downgrading TERM.+func terminalEnvs(opts RemoteTerminalOptions) map[string]string {+ if len(opts.Envs) == 0 {+ return nil+ }+ merged := make(map[string]string, len(opts.Envs)+1)+ for key, value := range opts.Envs {+ merged[key] = value+ }+ if merged["TERM"] == "" {+ merged["TERM"] = "xterm-256color"+ }+ return merged+}++// handleTrafficAccessToken extracts the traffic token without assuming a+// concrete handle type beyond the optional carrier interface.+func handleTrafficAccessToken(handle RemoteSandboxHandle) string {+ carrier, ok := handle.(RemoteInboundTokenCarrier)+ if !ok {+ return ""+ }+ return carrier.TrafficAccessToken()+}++// RemoteTerminalManager is the optional capability interface for backends+// that can open interactive PTYs inside a running sandbox. Mirrors+// RemoteSnapshotManager: advertised via RemoteSandboxCapabilities+// (SupportsTerminals) and narrowed with TerminalManagerFrom.+type RemoteTerminalManager interface {+ // OpenTerminal opens a new PTY inside the sandbox behind handle.+ OpenTerminal(ctx context.Context, handle RemoteSandboxHandle, opts RemoteTerminalOptions) (RemoteTerminalSession, error)+}++// TerminalManagerFrom narrows a client to its terminal capability. It+// returns false for providers that cannot stream PTYs, so callers can+// report an unsupported-backend error instead of failing mid-session.+//+// Both signals must agree: the type assertion finds the methods, and+// SupportsTerminals is the advertised capability (see SnapshotManagerFrom+// for the rationale).+func TerminalManagerFrom(client RemoteSandboxClient) (RemoteTerminalManager, bool) {+ if client == nil {+ return nil, false+ }+ mgr, ok := client.(RemoteTerminalManager)+ if !ok {+ return nil, false+ }+ if !client.Capabilities().SupportsTerminals {+ return nil, false+ }+ return mgr, true+}++// DefaultTerminalIdleDisconnect is how long an interactive terminal may sit+// without keystrokes or PTY output before WeKnora closes the WebSocket.+// Closing the socket stops TTL refresh so the sandbox can pause on its own+// provider timeout. 0 in a stored workspace config means this default.+const DefaultTerminalIdleDisconnect = 15 * time.Minute++const (+ minTerminalIdleDisconnect = 60 * time.Second+ maxTerminalIdleDisconnect = 24 * time.Hour+)++// EffectiveTerminalIdleDisconnect clamps a stored workspace value onto the+// range the terminal bridge will honour. 0 (unset) uses the built-in default+// so existing configs get an idle disconnect without a migration.+func EffectiveTerminalIdleDisconnect(d time.Duration) time.Duration {+ if d <= 0 {+ return DefaultTerminalIdleDisconnect+ }+ if d < minTerminalIdleDisconnect {+ return minTerminalIdleDisconnect+ }+ if d > maxTerminalIdleDisconnect {+ return maxTerminalIdleDisconnect+ }+ return d+}++// terminalTTLRefreshMin is the floor for how often an open terminal+// refreshes the provider sandbox idle timeout. Tests lower it.+var terminalTTLRefreshMin = 15 * time.Second++const terminalTTLRefreshMax = 2 * time.Minute++func terminalTTLRefreshInterval(ttl time.Duration) time.Duration {+ interval := ttl / 3+ if interval < terminalTTLRefreshMin {+ return terminalTTLRefreshMin+ }+ if interval > terminalTTLRefreshMax {+ return terminalTTLRefreshMax+ }+ return interval+}++func startTerminalTTLRefresh(+ ctx context.Context,+ closed <-chan struct{},+ ttl time.Duration,+ refresh func(context.Context) error,+) {+ if refresh == nil || ttl <= 0 {+ return+ }+ interval := terminalTTLRefreshInterval(ttl)+ go func() {+ doRefresh := func() {+ rctx, cancel := context.WithTimeout(ctx, 8*time.Second)+ _ = refresh(rctx)+ cancel()+ }+ // Cube Connect does not bump idle TTL; refresh immediately so a+ // terminal opened near expiry is not waiting a full interval.+ select {+ case <-closed:+ return+ case <-ctx.Done():+ return+ default:+ doRefresh()+ }+ ticker := time.NewTicker(interval)+ defer ticker.Stop()+ for {+ select {+ case <-closed:+ return+ case <-ctx.Done():+ return+ case <-ticker.C:+ doRefresh()+ }+ }+ }()+}diff --git a/internal/sandbox/terminal_test.go b/internal/sandbox/terminal_test.gonew file mode 100644index 000000000..662616f48--- /dev/null+++ b/internal/sandbox/terminal_test.go@@ -0,0 +1,39 @@+package sandbox++import (+ "testing"+ "time"++ "github.com/stretchr/testify/require"+)++// A pump that emits after the consumer walked away must not block. The+// stranded goroutine would never reach its `defer close(out)`, holding the+// provider's PTY stream open for the life of the process.+func TestEmitTerminalEventGivesUpWhenClosed(t *testing.T) {+ t.Parallel()+ out := make(chan RemoteTerminalEvent) // unbuffered: nobody is draining+ closed := make(chan struct{})+ close(closed)++ done := make(chan struct{})+ go func() {+ defer close(done)+ emitTerminalEvent(out, closed, RemoteTerminalEvent{Exited: true})+ }()++ select {+ case <-done:+ case <-time.After(2 * time.Second):+ t.Fatal("emitTerminalEvent blocked on a channel nobody drains")+ }+}++func TestEmitTerminalEventDeliversToLiveConsumer(t *testing.T) {+ t.Parallel()+ out := make(chan RemoteTerminalEvent, 1)++ emitTerminalEvent(out, make(chan struct{}), RemoteTerminalEvent{Data: []byte("hi")})++ require.Equal(t, []byte("hi"), (<-out).Data)+}diff --git a/internal/sandbox/terminal_ttl_test.go b/internal/sandbox/terminal_ttl_test.gonew file mode 100644index 000000000..92bcf4f84--- /dev/null+++ b/internal/sandbox/terminal_ttl_test.go@@ -0,0 +1,52 @@+package sandbox++import (+ "context"+ "sync/atomic"+ "testing"+ "time"++ "github.com/stretchr/testify/require"+)++func TestTerminalTTLRefreshInterval(t *testing.T) {+ t.Parallel()+ require.Equal(t, 15*time.Second, terminalTTLRefreshInterval(0))+ require.Equal(t, 15*time.Second, terminalTTLRefreshInterval(10*time.Second))+ require.Equal(t, 20*time.Second, terminalTTLRefreshInterval(60*time.Second))+ require.Equal(t, 2*time.Minute, terminalTTLRefreshInterval(30*time.Minute))+ require.Equal(t, 2*time.Minute, terminalTTLRefreshInterval(time.Hour))+}++func TestEffectiveTerminalIdleDisconnect(t *testing.T) {+ t.Parallel()+ require.Equal(t, DefaultTerminalIdleDisconnect, EffectiveTerminalIdleDisconnect(0))+ require.Equal(t, DefaultTerminalIdleDisconnect, EffectiveTerminalIdleDisconnect(-time.Second))+ require.Equal(t, minTerminalIdleDisconnect, EffectiveTerminalIdleDisconnect(30*time.Second))+ require.Equal(t, 20*time.Minute, EffectiveTerminalIdleDisconnect(20*time.Minute))+ require.Equal(t, maxTerminalIdleDisconnect, EffectiveTerminalIdleDisconnect(48*time.Hour))+}++func TestStartTerminalTTLRefreshCallsImmediately(t *testing.T) {+ prevMin := terminalTTLRefreshMin+ terminalTTLRefreshMin = 40 * time.Millisecond+ t.Cleanup(func() { terminalTTLRefreshMin = prevMin })++ var n atomic.Int32+ ctx, cancel := context.WithCancel(context.Background())+ t.Cleanup(cancel)+ closed := make(chan struct{})+ t.Cleanup(func() { close(closed) })++ startTerminalTTLRefresh(ctx, closed, 90*time.Millisecond, func(context.Context) error {+ n.Add(1)+ return nil+ })++ require.Eventually(t, func() bool {+ return n.Load() >= 1+ }, 500*time.Millisecond, 5*time.Millisecond, "expected an immediate TTL refresh")+ require.Eventually(t, func() bool {+ return n.Load() >= 2+ }, time.Second, 10*time.Millisecond, "expected a follow-up refresh on the interval")+}diff --git a/internal/types/interfaces/user.go b/internal/types/interfaces/user.goindex 25f8cfd02..263b82dc6 100644--- a/internal/types/interfaces/user.go+++ b/internal/types/interfaces/user.go@@ -66,6 +66,13 @@ type UserService interface {// non-home tenant. Falls back to user.TenantID when the claim is// missing (old tokens issued before tenant-level RBAC).ValidateToken(ctx context.Context, token string) (*types.User, uint64, error)+ // GetAccessTokenByValue looks up the stored access-token row for a JWT+ // string. The Token field is redacted. Used to bind a sandbox-terminal+ // ticket to the minting session without putting the JWT in the ticket.+ GetAccessTokenByValue(ctx context.Context, token string) (*types.AuthToken, error)+ // GetAccessTokenByID looks up a stored access-token row by primary key.+ // The Token field is redacted. Used by the sandbox-terminal recheck.+ GetAccessTokenByID(ctx context.Context, id string) (*types.AuthToken, error)// RefreshToken refreshes access token using refresh tokenRefreshToken(ctx context.Context, refreshToken string) (accessToken, newRefreshToken string, err error)// RevokeToken revokes a token@@ -137,6 +144,8 @@ type AuthTokenRepository interface {CreateToken(ctx context.Context, token *types.AuthToken) error// GetTokenByValue gets a token by its valueGetTokenByValue(ctx context.Context, tokenValue string) (*types.AuthToken, error)+ // GetTokenByID gets a token by its primary key+ GetTokenByID(ctx context.Context, id string) (*types.AuthToken, error)// GetTokensByUserID gets all tokens for a userGetTokensByUserID(ctx context.Context, userID string) ([]*types.AuthToken, error)// UpdateToken updates a tokendiff --git a/internal/types/tenant.go b/internal/types/tenant.goindex ca07ef30c..914f0eae6 100644--- a/internal/types/tenant.go+++ b/internal/types/tenant.go@@ -633,6 +633,12 @@ type TenantSandboxConfig struct {// program's built-in default.DefaultTimeoutSec int `json:"default_timeout_sec,omitempty"`+ // TerminalIdleDisconnectSec is how long an interactive terminal may go+ // without keystrokes or PTY output before WeKnora closes the connection+ // so the sandbox can pause on its provider TTL. 0 uses the built-in+ // default (15 minutes). Not an identity field.+ TerminalIdleDisconnectSec int `json:"terminal_idle_disconnect_sec,omitempty"`+// AllowPrivateEndpoints permits this workspace config to reach RFC1918 or// loopback cluster endpoints. Link-local/cloud-metadata addresses remain// blocked. It is explicit in the UI instead of hidden in process env.