From 3ab6d3940d1564f4db69d011941041e366370de7 Mon Sep 17 00:00:00 2001 From: nullptr-error <104547331+nullptr-error@users.noreply.github.com> Date: Wed, 9 Sep 2026 18:17:10 +0800 Subject: [PATCH] feat(sandbox): unify the interactive PTY prompt and reconnect running sandboxes (#3128) * feat(sandbox): use a classic colored user@host prompt in the PTY Cube, Docker, and E2B now share user@host:last-dir with WeKnora brand green, overriding E2B's default `\w $ ` prompt. * fix(sandbox): redraw the PTY prompt after connect instead of waiting for Enter Reattach does not replay bash's already-printed prompt, and FitAddon can clear the first paint. Fit before flushing output, then Ctrl-L if the screen is still empty. * feat(sandbox): add Debian-style ll/la/l aliases in the interactive PTY Interactive bash now gets colored ls/grep shortcuts; non-interactive skill scripts still see the real commands. * fix(sandbox): restore conventional ls colors so directories stay blue Map ANSI blue/cyan back to Tango colors so directories and executables are distinguishable; keep brand green only for user@host. * fix(sandbox): correct runtime env-var hint to this config and create time The copy claimed workspace-wide injection. Scope it to sandboxes created from this config, point per-run secrets to the Sandbox secrets page, and keep the hint off the add-button row so Chinese no longer wraps mid-word. * feat(sandbox): attach a running session sandbox when the terminal opens Opening the panel used to always show the start overlay. Lookup first so a running sandbox reconnects, while paused or missing sandboxes still wait for an explicit click and Connect cannot silently resume. * fix(sandbox): do not inject PTY input or auto-connect a non-running sandbox Empty-screen reconnect now SIGWINCHes so a reattached busy PTY is not fed Ctrl-L. Lookup-only opens require a click unless List confirms running, and closing the panel drops the terminal mount so a Files-tab reopen cannot attach. --------- Co-authored-by: hailongzhao Co-authored-by: wizardchen --- docker/Dockerfile.sandbox | 8 + docker/sandbox-pty-prompt.sh | 54 ++++++ .../components/SandboxConfigEditorDrawer.vue | 7 +- .../components/chat/SandboxSidePanel.test.mjs | 6 + .../src/components/chat/SandboxSidePanel.vue | 8 +- .../src/composables/useSandboxTerminal.ts | 32 ++-- frontend/src/i18n/locales/en-US.ts | 5 +- frontend/src/i18n/locales/ja-JP.ts | 5 +- frontend/src/i18n/locales/ko-KR.ts | 5 +- frontend/src/i18n/locales/ru-RU.ts | 5 +- frontend/src/i18n/locales/zh-CN.ts | 5 +- frontend/src/utils/ptyPromptNudge.test.ts | 13 ++ frontend/src/utils/ptyPromptNudge.ts | 12 ++ .../chat/components/SandboxTerminal.test.mjs | 79 +++++++++ .../views/chat/components/SandboxTerminal.vue | 140 +++++++++++---- .../service/sandbox_terminal_service.go | 24 ++- .../session/sandbox_terminal_idle_test.go | 16 ++ .../handler/session/sandbox_terminal_ws.go | 10 +- internal/sandbox/capabilities.go | 7 +- internal/sandbox/e2b_remote_client.go | 11 +- internal/sandbox/e2b_remote_client_test.go | 43 +++++ internal/sandbox/sandbox.go | 7 + internal/sandbox/session_manager.go | 68 +++++++- .../sandbox/session_manager_terminal_test.go | 163 ++++++++++++++++++ internal/sandbox/terminal.go | 6 + 25 files changed, 668 insertions(+), 71 deletions(-) create mode 100644 docker/sandbox-pty-prompt.sh create mode 100644 frontend/src/utils/ptyPromptNudge.test.ts create mode 100644 frontend/src/utils/ptyPromptNudge.ts create mode 100644 frontend/src/views/chat/components/SandboxTerminal.test.mjs create mode 100644 internal/sandbox/session_manager_terminal_test.go diff --git a/docker/Dockerfile.sandbox b/docker/Dockerfile.sandbox index d1712c4a..c28fc46b 100644 --- a/docker/Dockerfile.sandbox +++ b/docker/Dockerfile.sandbox @@ -68,6 +68,14 @@ RUN groupadd -g 1000 user && \ RUN mkdir -p /workspace/input /workspace/output && \ chown -R user:user /workspace +# Classic user@host:path prompt (colored). E2B's provisioner later appends +# `PS1='\w $ '`; the script reapplies this prompt via PROMPT_COMMAND so +# Cube, Docker, and E2B all show the same Debian-style line. +COPY docker/sandbox-pty-prompt.sh /etc/weknora/pty-prompt.sh +RUN echo '. /etc/weknora/pty-prompt.sh' > /etc/profile.d/zz-weknora-prompt.sh && \ + echo '. /etc/weknora/pty-prompt.sh' >> /root/.bashrc && \ + echo '. /etc/weknora/pty-prompt.sh' >> /home/user/.bashrc + WORKDIR /workspace USER root diff --git a/docker/sandbox-pty-prompt.sh b/docker/sandbox-pty-prompt.sh new file mode 100644 index 00000000..504f25d9 --- /dev/null +++ b/docker/sandbox-pty-prompt.sh @@ -0,0 +1,54 @@ +# WeKnora interactive PTY prompt: classic \u@\h:\W\$ +# (user@host:last-path-segment, # for root / $ otherwise). +# +# \W is the last directory only (e.g. /opt/weknora/skills → skills), +# so deep cwd does not blow the prompt width. +# +# Bold green (01;32) is user@host; bold blue (01;34) is the path — the +# usual Debian colors, so ls --color can keep directories blue and +# executables green. Root uses the same green as a normal user. +# +# Also enables Debian-style interactive aliases (ll, la, l, colored ls/grep). +# +# Sourced from profile.d and bashrc. E2B's template provisioner later +# appends PS1='\w $ '; PROMPT_COMMAND reapplies this prompt so that cannot +# stick. No-op for non-bash (Debian /etc/profile is also read by dash). + +[ -n "${BASH_VERSION-}" ] || return 0 + +weknora_set_pty_prompt() { + PS1='\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\W\[\033[00m\]\$ ' +} + +weknora_set_pty_prompt + +# Debian/Ubuntu interactive shortcuts. Aliases only apply in interactive +# shells, so skill scripts still see the real ls/grep. +case "$-" in +*i*) + if command -v dircolors >/dev/null 2>&1; then + eval "$(dircolors -b)" + fi + alias ls='ls --color=auto' + alias grep='grep --color=auto' + alias fgrep='fgrep --color=auto' + alias egrep='egrep --color=auto' + alias ll='ls -alF' + alias la='ls -A' + alias l='ls -CF' + ;; +esac + +case ";${PROMPT_COMMAND-};" in + *weknora_set_pty_prompt*) ;; + *) + if [ -n "${PROMPT_COMMAND-}" ]; then + PROMPT_COMMAND="weknora_set_pty_prompt; ${PROMPT_COMMAND}" + else + PROMPT_COMMAND="weknora_set_pty_prompt" + fi + ;; +esac +# PS1 and PROMPT_COMMAND stay shell-local. Exporting PS1 makes child +# processes look interactive (`[ -z "$PS1" ]`); exporting PROMPT_COMMAND +# without `export -f weknora_set_pty_prompt` breaks nested bash. diff --git a/frontend/src/components/SandboxConfigEditorDrawer.vue b/frontend/src/components/SandboxConfigEditorDrawer.vue index 660bef87..c4b06136 100644 --- a/frontend/src/components/SandboxConfigEditorDrawer.vue +++ b/frontend/src/components/SandboxConfigEditorDrawer.vue @@ -677,15 +677,13 @@
-
-

{{ $t('settings.sandbox.sectionEnvironment') }}

-

{{ $t('settings.sandbox.envVarsHint') }}

-
+

{{ $t('settings.sandbox.sectionEnvironment') }}

{{ $t('settings.sandbox.addRow') }}
+

{{ $t('settings.sandbox.envVarsHint') }}

@@ -2360,6 +2358,7 @@ onUnmounted(stopTemplatePolling) &--under-title { margin-top: 5px; max-width: 540px; + white-space: pre-line; } /* Sits under an input inside the same form item. */ diff --git a/frontend/src/components/chat/SandboxSidePanel.test.mjs b/frontend/src/components/chat/SandboxSidePanel.test.mjs index 672239c6..319cb552 100644 --- a/frontend/src/components/chat/SandboxSidePanel.test.mjs +++ b/frontend/src/components/chat/SandboxSidePanel.test.mjs @@ -15,3 +15,9 @@ test('artifacts is the first sandbox panel tab', () => { assert.doesNotMatch(panel, /chat-sandbox-panel__title/) assert.doesNotMatch(panel, /

{ + assert.match(panel, /if\s*\(!visible\)/) + assert.match(panel, /terminalMounted\.value = false/) + assert.match(panel, /tab === 'terminal'/) +}) diff --git a/frontend/src/components/chat/SandboxSidePanel.vue b/frontend/src/components/chat/SandboxSidePanel.vue index ab491edf..29d9922c 100644 --- a/frontend/src/components/chat/SandboxSidePanel.vue +++ b/frontend/src/components/chat/SandboxSidePanel.vue @@ -130,7 +130,13 @@ const terminalRef = ref<{ focus?: () => void } | null>(null) watch( () => [panel?.visible.value, panel?.activeTab.value] as const, ([visible, tab]) => { - if (visible && tab === 'terminal') { + if (!visible) { + // Drop the lazy-mount flag so reopening on Files does not remount + // SandboxTerminal (which would lookup-connect a PTY and refresh TTL). + terminalMounted.value = false + return + } + if (tab === 'terminal') { terminalMounted.value = true void nextTick(() => terminalRef.value?.focus?.()) } diff --git a/frontend/src/composables/useSandboxTerminal.ts b/frontend/src/composables/useSandboxTerminal.ts index 31fc1f57..f0140515 100644 --- a/frontend/src/composables/useSandboxTerminal.ts +++ b/frontend/src/composables/useSandboxTerminal.ts @@ -3,8 +3,8 @@ import { post } from '@/utils/request' import { readStoredPtyId, writeStoredPtyId } from '@/utils/sandboxPtyId' export type SandboxTerminalStatus = - /** 尚未连接:打开面板不会碰后端,等用户显式启动。 */ - | 'not_started' + /** 查询到会话沙箱已暂停;唤醒需要用户确认。 */ + | 'paused' | 'connecting' | 'ready' /** 查到会话没有运行中的沙箱;创建需要用户确认。 */ @@ -66,6 +66,7 @@ function statusFromErrorCode( if (code === 'SANDBOX_NOT_BOUND') { return provisionAttempted ? 'no_sandbox' : 'needs_provision' } + if (code === 'SANDBOX_PAUSED') return 'paused' if (code === 'TERMINAL_UNSUPPORTED') return 'unsupported' if (code === 'IDLE_DISCONNECTED') return 'idle' if (code === 'AUTH_REVOKED') return 'unauthorized' @@ -83,11 +84,11 @@ export type SandboxTerminalSession = { /** * 连接并打开终端;已在连接中时幂等。 * - * provision 表示"这是用户的显式动作,允许后端创建或重建沙箱"。只有点击 - * 按钮才应该传 true:创建沙箱是要计费的真实基础设施,不能是打开面板的副 - * 作用。自动重连一律不带,查不到沙箱就退回让用户确认。 + * provision 表示"这是用户的显式动作,允许后端创建或唤醒沙箱"。只有点击 + * 按钮才应该传 true:创建/唤醒沙箱是要计费的真实基础设施。打开面板时的 + * 自动连接一律不带:运行中的沙箱直接挂上,暂停或尚未创建则退回让用户确认。 */ - connect: (options?: { provision?: boolean }) => void + connect: (options?: { provision?: boolean; cols?: number; rows?: number }) => void /** 发送键盘输入(xterm onData 的原始字符串)。 */ sendInput: (data: string) => void /** 同步终端尺寸;ready 后调用。 */ @@ -106,7 +107,7 @@ export function useSandboxTerminal( agentId: Ref, agentSourceTenantId: Ref = ref(undefined), ): SandboxTerminalSession { - const status = ref('not_started') + const status = ref('connecting') let ws: WebSocket | null = null let opening = false @@ -118,6 +119,7 @@ export function useSandboxTerminal( let reconnectTimer: ReturnType | null = null let pingTimer: ReturnType | null = null let pendingResize: { cols: number; rows: number } | null = null + let pendingGeometry: { cols: number; rows: number } | null = null // 刷新 / 关面板会拆掉这个闭包;PID 写在 sessionStorage,重挂时才能带 pty_id。 let lastPid: number | null = readStoredPtyId(sessionId.value) // 当前这次连接是否带创建意图。只由 connect({ provision: true }) 置真。 @@ -187,6 +189,10 @@ export function useSandboxTerminal( if (lastPid && lastPid > 0) { query.set('pty_id', String(lastPid)) } + if (pendingGeometry) { + query.set('cols', String(pendingGeometry.cols)) + query.set('rows', String(pendingGeometry.rows)) + } const socket = new WebSocket( `${resolveWsBase()}/api/v1/sessions/${encodeURIComponent(sid)}/sandbox/terminal?${query.toString()}`, ) @@ -234,6 +240,7 @@ export function useSandboxTerminal( if ( event.code === 1008 || reason === 'SANDBOX_NOT_BOUND' + || reason === 'SANDBOX_PAUSED' || reason === 'TERMINAL_UNSUPPORTED' || reason === 'IDLE_DISCONNECTED' || reason === 'AUTH_REVOKED' @@ -243,15 +250,16 @@ export function useSandboxTerminal( } else if (status.value === 'ready' || status.value === 'connecting') { status.value = 'error' } - // idle / unauthorized:shell 还在沙箱里,PID 必须留下才能重挂。 + // idle / unauthorized / paused:shell 还在沙箱里,PID 必须留下才能重挂。 // 沙箱没了或后端不支持:PID 已无效,清掉以免下次 Create 撞上死进程。 - if (status.value !== 'idle' && status.value !== 'unauthorized') { + if (status.value !== 'idle' && status.value !== 'unauthorized' && status.value !== 'paused') { rememberPid(null) } return } if ( status.value !== 'needs_provision' + && status.value !== 'paused' && status.value !== 'no_sandbox' && status.value !== 'unsupported' && status.value !== 'exited' @@ -296,7 +304,7 @@ export function useSandboxTerminal( } case 'error': { status.value = statusFromErrorCode(frame.code, allowProvision) - if (status.value !== 'idle' && status.value !== 'unauthorized') { + if (status.value !== 'idle' && status.value !== 'unauthorized' && status.value !== 'paused') { rememberPid(null) } break @@ -351,6 +359,10 @@ export function useSandboxTerminal( clearReconnectTimer() allowProvision = options?.provision === true reconnectAttempt = 0 + const cols = options?.cols + const rows = options?.rows + pendingGeometry = + cols && rows && cols > 0 && rows > 0 ? { cols, rows } : null void openSocket() }, sendInput(data) { diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 388617ce..a75e7b6a 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -1272,7 +1272,7 @@ export default { allowPrivateEndpoints: 'Allow private cluster endpoints', allowPrivateEndpointsHint: 'Use for self-hosted private control planes. Link-local and cloud metadata addresses remain blocked.', howToBuildTemplate: 'Sandbox cluster setup and template guide', - noEnvVars: 'No additional environment variables. Add only values required by skills.', + noEnvVars: 'No additional environment variables.', fieldRequired: 'Required', cubeApiKeyOptional: 'Optional — leave empty for an unauthenticated self-hosted CubeSandbox', cubeApiKeyWhere: 'How to enable auth on a self-hosted cluster', @@ -1327,7 +1327,7 @@ export default { envVars: 'Environment variables', envKey: 'Name', envValue: 'Value', - envVarsHint: 'Injected into every sandbox for this workspace. Values are encrypted at rest but visible to scripts running inside the sandbox.', + envVarsHint: 'Injected into every sandbox created from this config. Values are encrypted at rest but visible to scripts inside the sandbox.\nInjected only when a sandbox is created; to inject on each run, add them on the Sandbox secrets page.', addRow: 'Add variable', removeRow: 'Remove', save: 'Save', @@ -3412,6 +3412,7 @@ export default { 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.', + paused: 'This conversation\'s sandbox is paused. Starting the terminal resumes it.', 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.', diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts index e4744359..f086d3b4 100644 --- a/frontend/src/i18n/locales/ja-JP.ts +++ b/frontend/src/i18n/locales/ja-JP.ts @@ -1272,7 +1272,7 @@ export default { allowPrivateEndpoints: 'プライベートクラスタエンドポイントを許可', allowPrivateEndpointsHint: 'セルフホストのプライベートコントロールプレーン向けです。リンクローカルアドレスとクラウドメタデータアドレスは引き続きブロックされます。', howToBuildTemplate: 'サンドボックスクラスタの構築とテンプレートのガイド', - noEnvVars: '追加の環境変数はありません。スキルが必要とする値のみを追加してください。', + noEnvVars: '追加の環境変数はありません。', fieldRequired: '必須', cubeApiKeyOptional: '任意。認証なしのセルフホストCubeSandboxでは空欄のままにしてください', cubeApiKeyWhere: 'セルフホストクラスタで認証を有効にする方法', @@ -1327,7 +1327,7 @@ export default { envVars: '環境変数', envKey: '名前', envValue: '値', - envVarsHint: 'このワークスペースのすべてのサンドボックスに注入されます。値は保存時に暗号化されますが、サンドボックス内で実行されるスクリプトからは参照できます。', + envVarsHint: 'この設定から作成されるサンドボックスに注入されます。値は保存時に暗号化されますが、サンドボックス内のスクリプトからは参照できます。\n注入はサンドボックス作成時のみです。実行のたびに注入する場合は「サンドボックスのシークレット」ページで追加してください。', addRow: '変数を追加', removeRow: '削除', save: '保存', @@ -3412,6 +3412,7 @@ export default { artifactsEmpty: 'この会話で生成されたファイルはまだありません', desktopPlaceholder: 'デスクトップの可視化は近日対応予定です', notStarted: 'ターミナルはまだ起動していません。起動するとこの会話のサンドボックスに接続し、存在しないか一時停止中の場合は作成または再開します。', + paused: 'この会話のサンドボックスは一時停止中です。ターミナルを起動すると再開します。', start: 'ターミナルを起動', connecting: 'サンドボックスに接続中…', needsProvision: 'この会話には実行中のサンドボックスがありません。作成すると新しいサンドボックスが起動し、ワークスペースの設定に従って課金されます。', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 103eac37..f7ccff4e 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -3463,6 +3463,7 @@ export default { artifactsEmpty: '이 대화에서 생성된 파일이 없습니다', desktopPlaceholder: '데스크톱 시각화는 곧 지원될 예정입니다', notStarted: '터미널이 아직 실행되지 않았습니다. 시작하면 이 대화의 샌드박스에 연결하며, 샌드박스가 없거나 일시 중지된 경우 생성하거나 다시 시작합니다.', + paused: '이 대화의 샌드박스가 일시 중지되었습니다. 터미널을 시작하면 다시 시작됩니다.', start: '터미널 시작', connecting: '샌드박스에 연결하는 중…', needsProvision: '이 대화에는 실행 중인 샌드박스가 없습니다. 생성하고 시작하면 새 샌드박스가 만들어지며 워크스페이스 설정에 따라 요금이 부과됩니다.', @@ -5397,7 +5398,7 @@ export default { allowPrivateEndpoints: 'Allow private cluster endpoints', allowPrivateEndpointsHint: 'Use for self-hosted private control planes. Link-local and cloud metadata addresses remain blocked.', howToBuildTemplate: 'Sandbox cluster setup and template guide', - noEnvVars: 'No additional environment variables. Add only values required by skills.', + noEnvVars: 'No additional environment variables.', fieldRequired: 'Required', cubeApiKeyOptional: 'Optional — leave empty for an unauthenticated self-hosted CubeSandbox', cubeApiKeyWhere: '자체 호스팅 클러스터에서 인증을 켜는 방법', @@ -5452,7 +5453,7 @@ export default { envVars: 'Environment variables', envKey: 'Name', envValue: 'Value', - envVarsHint: 'Injected into every sandbox for this workspace. Values are encrypted at rest but visible to scripts running inside the sandbox.', + envVarsHint: 'Injected into every sandbox created from this config. Values are encrypted at rest but visible to scripts inside the sandbox.\nInjected only when a sandbox is created; to inject on each run, add them on the Sandbox secrets page.', addRow: 'Add variable', removeRow: 'Remove', save: 'Save', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 1a9b1ee9..1e6df443 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -3463,6 +3463,7 @@ export default { artifactsEmpty: 'В этом диалоге пока нет созданных файлов', desktopPlaceholder: 'Визуализация рабочего стола скоро появится', notStarted: 'Терминал ещё не запущен. Запуск подключит его к песочнице этого диалога, создав или возобновив её при необходимости.', + paused: 'Песочница этого диалога приостановлена. Запуск терминала возобновит её.', start: 'Запустить терминал', connecting: 'Подключение к песочнице…', needsProvision: 'В этом диалоге нет работающей песочницы. Создание запустит новую песочницу — она тарифицируется согласно настройкам рабочего пространства.', @@ -5397,7 +5398,7 @@ export default { allowPrivateEndpoints: 'Allow private cluster endpoints', allowPrivateEndpointsHint: 'Use for self-hosted private control planes. Link-local and cloud metadata addresses remain blocked.', howToBuildTemplate: 'Sandbox cluster setup and template guide', - noEnvVars: 'No additional environment variables. Add only values required by skills.', + noEnvVars: 'No additional environment variables.', fieldRequired: 'Required', cubeApiKeyOptional: 'Optional — leave empty for an unauthenticated self-hosted CubeSandbox', cubeApiKeyWhere: 'Как включить аутентификацию в собственном кластере', @@ -5452,7 +5453,7 @@ export default { envVars: 'Environment variables', envKey: 'Name', envValue: 'Value', - envVarsHint: 'Injected into every sandbox for this workspace. Values are encrypted at rest but visible to scripts running inside the sandbox.', + envVarsHint: 'Injected into every sandbox created from this config. Values are encrypted at rest but visible to scripts inside the sandbox.\nInjected only when a sandbox is created; to inject on each run, add them on the Sandbox secrets page.', addRow: 'Add variable', removeRow: 'Remove', save: 'Save', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 12207a09..89b9188e 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -3465,6 +3465,7 @@ export default { artifactsEmpty: '本会话尚未生成可下载的文件', desktopPlaceholder: '桌面可视化即将支持', notStarted: '终端尚未启动。启动后会连接本会话的沙箱环境;若沙箱不存在或已暂停,将为你创建或唤醒它。', + paused: '本会话的沙箱已暂停。启动终端会唤醒它。', start: '启动终端', connecting: '正在连接沙箱…', needsProvision: '本会话当前没有运行中的沙箱环境。创建并启动会新建一个沙箱,并按工作区配置计费。', @@ -5399,7 +5400,7 @@ export default { allowPrivateEndpoints: '允许访问私网集群地址', allowPrivateEndpointsHint: '仅用于自建 Cube 等私网控制面;云元数据等链路本地地址始终禁止访问。', howToBuildTemplate: '沙箱集群搭建与模板说明', - noEnvVars: '暂无额外环境变量,仅添加技能确实需要的值。', + noEnvVars: '暂无额外环境变量。', fieldRequired: '必填', cubeApiKeyOptional: '可留空 —— 自建 CubeSandbox 通常无鉴权', cubeApiKeyWhere: '自建集群如何开启鉴权', @@ -5454,7 +5455,7 @@ export default { envVars: '环境变量', envKey: '变量名', envValue: '变量值', - envVarsHint: '注入到该空间所有沙箱;值加密存储,但对沙箱内脚本可见,请勿放入脚本不应读取的密钥。', + envVarsHint: '注入到该配置下所有沙箱;值加密存储,但对沙箱内脚本可见。\n只会在沙箱创建时注入,如果要实时注入请在「沙箱密钥」页面添加。', addRow: '添加变量', removeRow: '删除', save: '保存', diff --git a/frontend/src/utils/ptyPromptNudge.test.ts b/frontend/src/utils/ptyPromptNudge.test.ts new file mode 100644 index 00000000..f0054f2e --- /dev/null +++ b/frontend/src/utils/ptyPromptNudge.test.ts @@ -0,0 +1,13 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { xtermBufferLooksEmpty } from './ptyPromptNudge' + +test('xtermBufferLooksEmpty is true when every visible row is blank', () => { + const rows = ['', ' ', '\t'] + assert.equal(xtermBufferLooksEmpty((i) => rows[i], rows.length), true) +}) + +test('xtermBufferLooksEmpty is false when any row has text', () => { + const rows = ['', 'root@host:workspace#'] + assert.equal(xtermBufferLooksEmpty((i) => rows[i], rows.length), false) +}) diff --git a/frontend/src/utils/ptyPromptNudge.ts b/frontend/src/utils/ptyPromptNudge.ts new file mode 100644 index 00000000..02732c1a --- /dev/null +++ b/frontend/src/utils/ptyPromptNudge.ts @@ -0,0 +1,12 @@ +/** Wait for in-flight PTY bytes before deciding the screen is empty. */ +export const PTY_PROMPT_NUDGE_DELAY_MS = 120 + +export function xtermBufferLooksEmpty( + getLine: (row: number) => string | undefined, + rows: number, +): boolean { + for (let i = 0; i < rows; i++) { + if ((getLine(i) ?? '').trim() !== '') return false + } + return true +} diff --git a/frontend/src/views/chat/components/SandboxTerminal.test.mjs b/frontend/src/views/chat/components/SandboxTerminal.test.mjs new file mode 100644 index 00000000..80332b86 --- /dev/null +++ b/frontend/src/views/chat/components/SandboxTerminal.test.mjs @@ -0,0 +1,79 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { execFileSync } from 'node:child_process' +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' + +const terminal = readFileSync(new URL('./SandboxTerminal.vue', import.meta.url), 'utf8') +const theme = readFileSync(new URL('../../../assets/theme/theme.css', import.meta.url), 'utf8') +const promptUrl = new URL('../../../../../docker/sandbox-pty-prompt.sh', import.meta.url) +const prompt = readFileSync(promptUrl, 'utf8') +const promptPath = fileURLToPath(promptUrl) + +test('xterm palette keeps prompt green but ls directories blue', () => { + assert.match(theme, /--td-brand-color-4: #07c05f/) + assert.match(terminal, /brightGreen: '#07c05f'/) + assert.match(terminal, /brightBlue: '#729fcf'/) + assert.doesNotMatch(terminal, /brightBlue: '#07c05f'/) + assert.match(terminal, /brightCyan: '#34e2e2'/) + assert.doesNotMatch(terminal, /brightCyan: '#08dd6e'/) + assert.match(prompt, /\\033\[01;32m/) + assert.match(prompt, /\\033\[01;34m/) + assert.doesNotMatch(prompt, /\\033\[01;31m/) + assert.match(prompt, /\]\\W\\\[/) + assert.doesNotMatch(prompt, /\]\\w\\\[/) +}) + +test('PTY output attaches after the first fit so FitAddon cannot wipe the prompt', () => { + const start = terminal.indexOf('function mountTerminal') + const end = terminal.indexOf('function unmountTerminal') + assert.ok(start >= 0 && end > start) + const mount = terminal.slice(start, end) + const fitAt = mount.indexOf('applyFit()') + const outputAt = mount.indexOf('terminal.onOutput') + assert.ok(fitAt >= 0, 'mountTerminal must fit xterm') + assert.ok(outputAt >= 0, 'mountTerminal must attach PTY output') + assert.ok( + fitAt < outputAt, + 'FitAddon.fit() clears the renderer when cols/rows change; flushing the buffered prompt before that fit leaves an empty cursor until the next keystroke', + ) + assert.match(terminal, /xterm\.refresh\(0,\s*xterm\.rows\s*-\s*1\)/) +}) + +test('empty PTY screen is nudged with SIGWINCH, not keystrokes', () => { + assert.match(terminal, /schedulePromptNudge/) + assert.match(terminal, /estimatePtySize/) + assert.match(terminal, /resize\(cols,\s*rows\s*-\s*1\)/) + assert.doesNotMatch(terminal, /sendInput\(PTY_PROMPT_NUDGE\)/) + assert.doesNotMatch(terminal, /sendInput\('\\x0c'\)/) + assert.doesNotMatch(terminal, /sendInput\('\\r'\)/) +}) + +test('panel open looks up a running sandbox and only provisions on an explicit click', () => { + assert.match(terminal, /connectLookup/) + assert.match(terminal, /onMounted\(\(\) => \{\s*connectLookup\(\)/) + assert.match(terminal, /connect\(\{ provision: false/) + assert.match(terminal, /connect\(\{ provision: true/) + assert.match(terminal, /status === 'paused'/) + assert.match(terminal, /chat\.sandbox\.paused/) + assert.doesNotMatch(terminal, /not_started/) +}) + +test('interactive bash defines Debian-style ls aliases', () => { + const out = execFileSync('bash', [ + '--norc', + '--noprofile', + '-ic', + `. '${promptPath}'; alias ll; alias la; alias l; alias ls; alias grep`, + ], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }) + assert.match(out, /alias ll='ls -alF'/) + assert.match(out, /alias la='ls -A'/) + assert.match(out, /alias l='ls -CF'/) + assert.match(out, /alias ls='ls --color=auto'/) + assert.match(out, /alias grep='grep --color=auto'/) +}) + +test('interactive prompt script does not export PS1 or PROMPT_COMMAND', () => { + assert.doesNotMatch(prompt, /export PS1/) + assert.doesNotMatch(prompt, /export PROMPT_COMMAND/) +}) diff --git a/frontend/src/views/chat/components/SandboxTerminal.vue b/frontend/src/views/chat/components/SandboxTerminal.vue index d2679d66..4889a34f 100644 --- a/frontend/src/views/chat/components/SandboxTerminal.vue +++ b/frontend/src/views/chat/components/SandboxTerminal.vue @@ -6,7 +6,7 @@ @@ -24,7 +24,7 @@