diff --git a/frontend/src/composables/useSandboxTerminal.ts b/frontend/src/composables/useSandboxTerminal.ts index f0140515..749a11af 100644 --- a/frontend/src/composables/useSandboxTerminal.ts +++ b/frontend/src/composables/useSandboxTerminal.ts @@ -23,6 +23,7 @@ export type SandboxTerminalControlFrame = { message?: string pty_id?: number backend?: string + reattachable?: boolean exit_code?: number | null cols?: number rows?: number @@ -66,7 +67,9 @@ function statusFromErrorCode( if (code === 'SANDBOX_NOT_BOUND') { return provisionAttempted ? 'no_sandbox' : 'needs_provision' } - if (code === 'SANDBOX_PAUSED') return 'paused' + // SANDBOX_STOPPED 是不会暂停的后端(Docker)的同一状态:同样要用户确认才 + // 启动,只是提示文案不同,见 sandboxMayBeReclaimed。 + if (code === 'SANDBOX_PAUSED' || code === 'SANDBOX_STOPPED') return 'paused' if (code === 'TERMINAL_UNSUPPORTED') return 'unsupported' if (code === 'IDLE_DISCONNECTED') return 'idle' if (code === 'AUTH_REVOKED') return 'unauthorized' @@ -75,6 +78,18 @@ function statusFromErrorCode( export type SandboxTerminalSession = { status: Ref + /** + * status 为 paused 时,沙箱是否可能已被回收(后端回的是 SANDBOX_STOPPED)。 + * Docker 没有暂停:没在运行的容器要么是停止了,要么已被空闲回收删掉, + * 启动后可能是一个全新的沙箱,不能对用户说"唤醒"。 + */ + sandboxMayBeReclaimed: Ref + /** + * 最近一次 ready 帧声明的:断线后重连能否接回同一个 shell。Docker 为 + * false:断开即结束 shell,重连只会得到新 shell,所以不自动重连, + * 由用户点"重新连接"。 + */ + reattachable: Ref /** * 由 SandboxTerminal.vue 注入:PTY 输出写入 xterm。 * 在 handler 注册前到达的二进制帧会先入队,避免 bash 提示符在 xterm @@ -108,9 +123,14 @@ export function useSandboxTerminal( agentSourceTenantId: Ref = ref(undefined), ): SandboxTerminalSession { const status = ref('connecting') + const sandboxMayBeReclaimed = ref(false) + const reattachable = ref(true) let ws: WebSocket | null = null let opening = false + // 当前这条连接是否已收到 ready。ready 之前断线时服务端未必开了 shell, + // 照常自动重连;ready 之后断线是否重连取决于 reattachable。 + let readyReceived = false let outputHandler: ((data: Uint8Array) => void) | null = null let pendingOutput: Uint8Array[] = [] let pendingOutputBytes = 0 @@ -169,6 +189,7 @@ export function useSandboxTerminal( if (!sid) return opening = true + readyReceived = false status.value = 'connecting' try { const ticket = await mintTerminalTicket(sid) @@ -241,11 +262,13 @@ export function useSandboxTerminal( event.code === 1008 || reason === 'SANDBOX_NOT_BOUND' || reason === 'SANDBOX_PAUSED' + || reason === 'SANDBOX_STOPPED' || reason === 'TERMINAL_UNSUPPORTED' || reason === 'IDLE_DISCONNECTED' || reason === 'AUTH_REVOKED' ) { if (reason) { + sandboxMayBeReclaimed.value = reason === 'SANDBOX_STOPPED' status.value = statusFromErrorCode(reason, allowProvision) } else if (status.value === 'ready' || status.value === 'connecting') { status.value = 'error' @@ -267,6 +290,7 @@ export function useSandboxTerminal( && status.value !== 'unauthorized' ) { status.value = 'error' + if (readyReceived && !reattachable.value) return scheduleReconnect() } } @@ -286,6 +310,8 @@ export function useSandboxTerminal( switch (frame.type) { case 'ready': status.value = 'ready' + readyReceived = true + reattachable.value = frame.reattachable !== false rememberPid(typeof frame.pty_id === 'number' ? frame.pty_id : null) reconnectAttempt = 0 // 创建意图到此为止。它只用来解释 SANDBOX_NOT_BOUND:连上之前是"还没 @@ -303,6 +329,7 @@ export function useSandboxTerminal( break } case 'error': { + sandboxMayBeReclaimed.value = frame.code === 'SANDBOX_STOPPED' status.value = statusFromErrorCode(frame.code, allowProvision) if (status.value !== 'idle' && status.value !== 'unauthorized' && status.value !== 'paused') { rememberPid(null) @@ -342,6 +369,8 @@ export function useSandboxTerminal( const session: SandboxTerminalSession = { status, + sandboxMayBeReclaimed, + reattachable, onOutput(handler) { outputHandler = handler if (!handler) return diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 98dc3529..a7c21325 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -4040,6 +4040,7 @@ export default { desktopRetry: 'Reconnect', 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.', + stopped: 'This conversation\'s sandbox is not running: it was stopped, or reclaimed after being idle. Starting the terminal restarts it; if it was reclaimed, a new sandbox is created and previous files and installed software are not kept.', 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.', @@ -4050,6 +4051,8 @@ export default { retry: 'Reconnect', sessionEnded: 'Terminal session ended', idleDisconnected: 'The terminal disconnected after being idle. The sandbox will pause on its own TTL. You can reconnect.', + idleDisconnectedNewShell: 'The terminal disconnected after being idle and its shell has ended (background jobs started with nohup keep running). Reconnecting opens a new shell.', + disconnectedNewShell: 'Connection lost and the terminal\'s shell has ended (background jobs started with nohup keep running). Reconnecting opens a new shell.', authRevoked: 'Your session is no longer valid, so the terminal was disconnected. Sign in again, then reconnect.', }, questionMinimapTitle: 'Q&A', diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts index 72e215fd..025fa341 100644 --- a/frontend/src/i18n/locales/ja-JP.ts +++ b/frontend/src/i18n/locales/ja-JP.ts @@ -4040,6 +4040,7 @@ export default { desktopRetry: 'Reconnect', notStarted: 'ターミナルはまだ起動していません。起動するとこの会話のサンドボックスに接続し、存在しないか一時停止中の場合は作成または再開します。', paused: 'この会話のサンドボックスは一時停止中です。ターミナルを起動すると再開します。', + stopped: 'この会話のサンドボックスは実行されていません。停止したか、長時間アイドル状態だったため回収された可能性があります。ターミナルを起動すると再起動します。回収済みの場合は新しいサンドボックスが作成され、以前のファイルやインストールしたソフトウェアは保持されません。', start: 'ターミナルを起動', connecting: 'サンドボックスに接続中…', needsProvision: 'この会話には実行中のサンドボックスがありません。作成すると新しいサンドボックスが起動し、ワークスペースの設定に従って課金されます。', @@ -4050,6 +4051,8 @@ export default { retry: '再接続', sessionEnded: 'ターミナルセッションが終了しました', idleDisconnected: 'アイドル状態のためターミナルが切断されました。サンドボックスは自身のTTLで一時停止します。再接続できます。', + idleDisconnectedNewShell: 'アイドル状態のためターミナルが切断され、シェルは終了しました(nohup で起動したバックグラウンドジョブは影響を受けません)。再接続すると新しいシェルが開きます。', + disconnectedNewShell: '接続が切断され、ターミナルのシェルは終了しました(nohup で起動したバックグラウンドジョブは影響を受けません)。再接続すると新しいシェルが開きます。', authRevoked: 'ログイン状態が無効になったため、ターミナルが切断されました。再度サインインしてから接続してください。', }, questionMinimapTitle: 'Q&A', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 5f80daaa..504d289f 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -3949,6 +3949,7 @@ export default { desktopRetry: 'Reconnect', notStarted: '터미널이 아직 실행되지 않았습니다. 시작하면 이 대화의 샌드박스에 연결하며, 샌드박스가 없거나 일시 중지된 경우 생성하거나 다시 시작합니다.', paused: '이 대화의 샌드박스가 일시 중지되었습니다. 터미널을 시작하면 다시 시작됩니다.', + stopped: '이 대화의 샌드박스가 실행 중이 아닙니다. 중지되었거나 오랫동안 유휴 상태여서 회수되었을 수 있습니다. 터미널을 시작하면 다시 시작되며, 이미 회수된 경우 새 샌드박스가 만들어지고 이전 파일과 설치한 소프트웨어는 유지되지 않습니다.', start: '터미널 시작', connecting: '샌드박스에 연결하는 중…', needsProvision: '이 대화에는 실행 중인 샌드박스가 없습니다. 생성하고 시작하면 새 샌드박스가 만들어지며 워크스페이스 설정에 따라 요금이 부과됩니다.', @@ -3959,6 +3960,8 @@ export default { retry: '다시 연결', sessionEnded: '터미널 세션이 종료되었습니다', idleDisconnected: '터미널이 유휴 상태로 연결이 끊어졌습니다. 샌드박스는 TTL에 따라 일시 중지됩니다. 다시 연결할 수 있습니다.', + idleDisconnectedNewShell: '터미널이 유휴 상태로 연결이 끊어져 셸이 종료되었습니다(nohup으로 시작한 백그라운드 작업은 영향을 받지 않습니다). 다시 연결하면 새 셸이 열립니다.', + disconnectedNewShell: '연결이 끊어져 터미널의 셸이 종료되었습니다(nohup으로 시작한 백그라운드 작업은 영향을 받지 않습니다). 다시 연결하면 새 셸이 열립니다.', authRevoked: '로그인 상태가 더 이상 유효하지 않아 터미널 연결이 끊어졌습니다. 다시 로그인한 뒤 재연결하세요.', }, questionMinimapTitle: '질문', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 0b4854a6..a883c7d2 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -3949,6 +3949,7 @@ export default { desktopRetry: 'Reconnect', notStarted: 'Терминал ещё не запущен. Запуск подключит его к песочнице этого диалога, создав или возобновив её при необходимости.', paused: 'Песочница этого диалога приостановлена. Запуск терминала возобновит её.', + stopped: 'Песочница этого диалога не работает: она была остановлена или удалена после долгого простоя. Запуск терминала перезапустит её; если она была удалена, будет создана новая песочница, а прежние файлы и установленные программы не сохранятся.', start: 'Запустить терминал', connecting: 'Подключение к песочнице…', needsProvision: 'В этом диалоге нет работающей песочницы. Создание запустит новую песочницу — она тарифицируется согласно настройкам рабочего пространства.', @@ -3959,6 +3960,8 @@ export default { retry: 'Переподключиться', sessionEnded: 'Сеанс терминала завершён', idleDisconnected: 'Терминал отключён из‑за простоя. Песочница приостановится по своему TTL. Можно подключиться снова.', + idleDisconnectedNewShell: 'Терминал отключён из‑за простоя, его оболочка завершена (фоновые задачи, запущенные через nohup, продолжают работать). Повторное подключение откроет новую оболочку.', + disconnectedNewShell: 'Соединение потеряно, оболочка терминала завершена (фоновые задачи, запущенные через nohup, продолжают работать). Повторное подключение откроет новую оболочку.', authRevoked: 'Сессия больше не действительна, терминал отключён. Войдите снова и переподключитесь.', }, questionMinimapTitle: 'Вопросы', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 095c0659..c9b3fb52 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -3951,6 +3951,7 @@ export default { desktopRetry: '重新连接', notStarted: '终端尚未启动。启动后会连接本会话的沙箱环境;若沙箱不存在或已暂停,将为你创建或唤醒它。', paused: '本会话的沙箱已暂停。启动终端会唤醒它。', + stopped: '本会话的沙箱未在运行:可能已停止,或因长时间空闲已被回收。启动终端会重新启动它;若已被回收,则会新建一个沙箱,之前的文件和安装的软件不会保留。', start: '启动终端', connecting: '正在连接沙箱…', needsProvision: '本会话当前没有运行中的沙箱环境。创建并启动会新建一个沙箱,并按工作区配置计费。', @@ -3961,6 +3962,8 @@ export default { retry: '重新连接', sessionEnded: '终端会话已结束', idleDisconnected: '终端空闲已断开,沙箱将按工作区 TTL 自行暂停。可重新连接。', + idleDisconnectedNewShell: '终端空闲已断开,其中的 shell 已结束(nohup 启动的后台任务不受影响)。重新连接会打开一个新的 shell。', + disconnectedNewShell: '连接已断开,终端中的 shell 已结束(nohup 启动的后台任务不受影响)。重新连接会打开一个新的 shell。', authRevoked: '登录状态已失效,终端已断开。请重新登录后再连接。', }, questionMinimapTitle: '问答', diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.ts index 5bfcdbf7..8eff5293 100644 --- a/frontend/src/i18n/locales/zh-TW.ts +++ b/frontend/src/i18n/locales/zh-TW.ts @@ -3951,6 +3951,7 @@ export default { desktopRetry: '重新連結', notStarted: '終端尚未啟動。啟動後會連結本會話的沙箱環境;若沙箱不存在或已暫停,將為你建立或喚醒它。', paused: '本會話的沙箱已暫停。啟動終端會喚醒它。', + stopped: '本會話的沙箱未在執行:可能已停止,或因長時間閒置已被回收。啟動終端會重新啟動它;若已被回收,則會新建一個沙箱,先前的檔案和安裝的軟體不會保留。', start: '啟動終端', connecting: '正在連結沙箱…', needsProvision: '本會話當前沒有運行中的沙箱環境。建立並啟動會新建一個沙箱,並按工作區設定計費。', @@ -3961,6 +3962,8 @@ export default { retry: '重新連結', sessionEnded: '終端會話已結束', idleDisconnected: '終端空閒已斷開,沙箱將按工作區 TTL 自行暫停。可重新連結。', + idleDisconnectedNewShell: '終端閒置已斷開,其中的 shell 已結束(nohup 啟動的背景任務不受影響)。重新連結會開啟一個新的 shell。', + disconnectedNewShell: '連結已斷開,終端中的 shell 已結束(nohup 啟動的背景任務不受影響)。重新連結會開啟一個新的 shell。', authRevoked: '登入狀態已失效,終端已斷開。請重新登入後再連結。', }, questionMinimapTitle: '問答', diff --git a/frontend/src/views/chat/components/SandboxTerminal.test.mjs b/frontend/src/views/chat/components/SandboxTerminal.test.mjs index f6aa9449..43beca79 100644 --- a/frontend/src/views/chat/components/SandboxTerminal.test.mjs +++ b/frontend/src/views/chat/components/SandboxTerminal.test.mjs @@ -71,6 +71,19 @@ test('panel open looks up a running sandbox and only provisions on an explicit c assert.doesNotMatch(terminal, /not_started/) }) +test('a non-reattachable (Docker) terminal never redials silently after ready', () => { + const composable = readFileSync( + new URL('../../../composables/useSandboxTerminal.ts', import.meta.url), + 'utf8', + ) + assert.match(composable, /reattachable\.value = frame\.reattachable !== false/) + assert.match(composable, /if \(readyReceived && !reattachable\.value\) return\s*scheduleReconnect\(\)/) + assert.match(composable, /code === 'SANDBOX_PAUSED' \|\| code === 'SANDBOX_STOPPED'/) + assert.match(terminal, /chat\.sandbox\.idleDisconnectedNewShell/) + assert.match(terminal, /chat\.sandbox\.disconnectedNewShell/) + assert.match(terminal, /chat\.sandbox\.stopped/) +}) + test('interactive bash defines Debian-style ls aliases', () => { const out = execFileSync('bash', [ '--norc', diff --git a/frontend/src/views/chat/components/SandboxTerminal.vue b/frontend/src/views/chat/components/SandboxTerminal.vue index 41517f5a..d31f7d08 100644 --- a/frontend/src/views/chat/components/SandboxTerminal.vue +++ b/frontend/src/views/chat/components/SandboxTerminal.vue @@ -125,12 +125,14 @@ const terminal = useSandboxTerminal( toRef(props, 'agentId'), toRef(props, 'agentSourceTenantId'), ); -const { status } = terminal; +const { status, sandboxMayBeReclaimed, reattachable } = terminal; const statusText = computed(() => { switch (status.value as SandboxTerminalStatus) { case 'paused': - return t('chat.sandbox.paused'); + return sandboxMayBeReclaimed.value + ? t('chat.sandbox.stopped') + : t('chat.sandbox.paused'); case 'connecting': return t('chat.sandbox.connecting'); case 'needs_provision': @@ -142,11 +144,15 @@ const statusText = computed(() => { case 'exited': return t('chat.sandbox.sessionEnded'); case 'idle': - return t('chat.sandbox.idleDisconnected'); + return reattachable.value + ? t('chat.sandbox.idleDisconnected') + : t('chat.sandbox.idleDisconnectedNewShell'); case 'unauthorized': return t('chat.sandbox.authRevoked'); default: - return t('chat.sandbox.disconnected'); + return reattachable.value + ? t('chat.sandbox.disconnected') + : t('chat.sandbox.disconnectedNewShell'); } }); diff --git a/internal/handler/session/sandbox_terminal_bridge.go b/internal/handler/session/sandbox_terminal_bridge.go index 1de3d3f4..40a6372a 100644 --- a/internal/handler/session/sandbox_terminal_bridge.go +++ b/internal/handler/session/sandbox_terminal_bridge.go @@ -56,10 +56,13 @@ func (b *terminalBridge) teardownWith(reason string) { } func (b *terminalBridge) run() { + pid := b.terminal.Session.PID() + reattachable := pid > 0 b.sendControl(terminalControlFrame{ - Type: "ready", - PID: b.terminal.Session.PID(), - Backend: b.terminal.Backend, + Type: "ready", + PID: pid, + Backend: b.terminal.Backend, + Reattachable: &reattachable, }) // Liveness defaults; the read loop also refreshes on every frame. @@ -328,8 +331,8 @@ func (b *terminalBridge) heartbeat(done chan struct{}) { // 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. + // On Cube/E2B Close only disconnects WeKnora from the PTY and the shell + // stays reattachable; Docker cannot reattach, so its Close ends the shell. if err := b.terminal.Session.Close(); err != nil { logger.Debugf(b.ctx, "[sandbox-terminal] close failed session=%s: %v", b.session, err) diff --git a/internal/handler/session/sandbox_terminal_bridge_test.go b/internal/handler/session/sandbox_terminal_bridge_test.go index d98b1eb3..9b13fe70 100644 --- a/internal/handler/session/sandbox_terminal_bridge_test.go +++ b/internal/handler/session/sandbox_terminal_bridge_test.go @@ -22,15 +22,16 @@ import ( // so a test controls exactly when the bridge ends. type fakeTerminalSession struct { out chan sandbox.RemoteTerminalEvent + pid uint32 closes atomic.Int32 } func newFakeTerminalSession() *fakeTerminalSession { - return &fakeTerminalSession{out: make(chan sandbox.RemoteTerminalEvent)} + return &fakeTerminalSession{out: make(chan sandbox.RemoteTerminalEvent), pid: 4321} } func (s *fakeTerminalSession) Output() <-chan sandbox.RemoteTerminalEvent { return s.out } -func (s *fakeTerminalSession) PID() uint32 { return 4321 } +func (s *fakeTerminalSession) PID() uint32 { return s.pid } func (s *fakeTerminalSession) Write(context.Context, []byte) error { return nil } func (s *fakeTerminalSession) Resize(context.Context, uint32, uint32) error { return nil @@ -93,6 +94,28 @@ func readTerminalFrame(t *testing.T, conn *websocket.Conn) terminalControlFrame return frame } +func TestTerminalBridgeReadyAdvertisesReattachability(t *testing.T) { + for name, tc := range map[string]struct { + pid uint32 + want bool + }{ + "envd PTY with a pid": {pid: 4321, want: true}, + "docker exec without a pid": {pid: 0, want: false}, + } { + t.Run(name, func(t *testing.T) { + pty := newFakeTerminalSession() + pty.pid = tc.pid + client := serveTerminalBridge(t, pty, nil) + + ready := readTerminalFrame(t, client) + require.Equal(t, "ready", ready.Type) + require.NotNil(t, ready.Reattachable, + "ready must always say whether a reconnect resumes the shell") + require.Equal(t, tc.want, *ready.Reattachable) + }) + } +} + func TestTerminalBridgeTearsDownWhenAuthIsRevoked(t *testing.T) { prev := terminalAuthRecheckInterval terminalAuthRecheckInterval = 20 * time.Millisecond diff --git a/internal/handler/session/sandbox_terminal_idle_test.go b/internal/handler/session/sandbox_terminal_idle_test.go index eb6dcaa8..ad602c08 100644 --- a/internal/handler/session/sandbox_terminal_idle_test.go +++ b/internal/handler/session/sandbox_terminal_idle_test.go @@ -1,6 +1,7 @@ package session import ( + "fmt" "testing" "time" @@ -61,6 +62,10 @@ func TestTerminalErrorFrame(t *testing.T) { code, _ = terminalErrorFrame(sandbox.ErrSandboxPaused) require.Equal(t, terminalErrPaused, code) + code, _ = terminalErrorFrame(fmt.Errorf("open: %w", sandbox.ErrSandboxStopped)) + require.Equal(t, terminalErrStopped, code, + "Docker's not-running case must not be reported as a wakeable pause") + code, _ = terminalErrorFrame(service.ErrTerminalUnsupported) require.Equal(t, terminalErrUnsupported, code) } diff --git a/internal/handler/session/sandbox_terminal_ws.go b/internal/handler/session/sandbox_terminal_ws.go index a3458890..8bd7b212 100644 --- a/internal/handler/session/sandbox_terminal_ws.go +++ b/internal/handler/session/sandbox_terminal_ws.go @@ -71,6 +71,7 @@ var terminalAuthRecheckInterval = time.Minute const ( terminalErrNotBound = "SANDBOX_NOT_BOUND" terminalErrPaused = "SANDBOX_PAUSED" + terminalErrStopped = "SANDBOX_STOPPED" terminalErrUnsupported = "TERMINAL_UNSUPPORTED" terminalErrInternal = "INTERNAL" terminalErrIdle = "IDLE_DISCONNECTED" @@ -133,6 +134,10 @@ type terminalControlFrame struct { PID uint32 `json:"pty_id,omitempty"` // Backend names the sandbox provider on ready frames. Backend string `json:"backend,omitempty"` + // Reattachable tells the browser, on ready frames, whether reconnecting + // with pty_id resumes this shell. False (Docker) means a reconnect gets a + // fresh shell, so the client must not redial silently. + Reattachable *bool `json:"reattachable,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. @@ -399,6 +404,9 @@ func terminalErrorFrame(err error) (code, message string) { switch { case stderrors.Is(err, sandbox.ErrNoLiveSessionSandbox): return terminalErrNotBound, "session has no live sandbox" + // Before ErrSandboxPaused, which it wraps. + case stderrors.Is(err, sandbox.ErrSandboxStopped): + return terminalErrStopped, "session sandbox is stopped or was reclaimed" case stderrors.Is(err, sandbox.ErrSandboxPaused): return terminalErrPaused, "session sandbox is paused" case stderrors.Is(err, service.ErrTerminalUnsupported): diff --git a/internal/sandbox/docker_engine.go b/internal/sandbox/docker_engine.go index 6eef9e0e..dad8aa5a 100644 --- a/internal/sandbox/docker_engine.go +++ b/internal/sandbox/docker_engine.go @@ -51,7 +51,14 @@ type dockerEngineAPI interface { ctx context.Context, containerID string, options client.ExecCreateOptions, ) (client.ExecCreateResult, error) ExecAttach(ctx context.Context, execID string, options client.ExecAttachOptions) (client.ExecAttachResult, error) + // ExecStart starts an already-created exec. The terminal path uses it, + // detached, to run a best-effort teardown of a shell it is abandoning: + // a Docker exec can neither be re-attached nor stopped any other way. + ExecStart(ctx context.Context, execID string, options client.ExecStartOptions) (client.ExecStartResult, error) ExecInspect(ctx context.Context, execID string, options client.ExecInspectOptions) (client.ExecInspectResult, error) + // ExecResize resizes the TTY of a running exec, which is what backs the + // interactive terminal's window-size changes. + ExecResize(ctx context.Context, execID string, options client.ExecResizeOptions) (client.ExecResizeResult, error) // ContainerStatPath is the one archive endpoint this adapter uses, and only // against the activity marker's fixed path. The copy endpoints are diff --git a/internal/sandbox/docker_integration_test.go b/internal/sandbox/docker_integration_test.go index dedc1733..d968d125 100644 --- a/internal/sandbox/docker_integration_test.go +++ b/internal/sandbox/docker_integration_test.go @@ -24,6 +24,7 @@ import ( "os" "path" "strings" + "sync" "testing" "time" @@ -691,3 +692,361 @@ func TestDockerSkillSnapshotIntegration(t *testing.T) { } } } + +// terminalCapture drains a PTY session in the background so assertions can wait +// for output that arrived before the check, which a direct receive would have +// consumed. +type terminalCapture struct { + mu sync.Mutex + buf bytes.Buffer + done chan struct{} +} + +func captureTerminal(session RemoteTerminalSession) *terminalCapture { + capture := &terminalCapture{done: make(chan struct{})} + go func() { + defer close(capture.done) + for event := range session.Output() { + if event.Err != nil { + return + } + capture.mu.Lock() + capture.buf.Write(event.Data) + capture.mu.Unlock() + } + }() + return capture +} + +func (c *terminalCapture) String() string { + c.mu.Lock() + defer c.mu.Unlock() + return c.buf.String() +} + +func (c *terminalCapture) waitFor(t *testing.T, want string, timeout time.Duration) { + t.Helper() + deadline := time.Now().Add(timeout) + for time.Now().Before(deadline) { + if strings.Contains(c.String(), want) { + return + } + time.Sleep(50 * time.Millisecond) + } + t.Fatalf("terminal output never contained %q; got: %q", want, c.String()) +} + +func (c *terminalCapture) assertNever(t *testing.T, unwanted string, window time.Duration) { + t.Helper() + deadline := time.Now().Add(window) + for time.Now().Before(deadline) { + if strings.Contains(c.String(), unwanted) { + t.Fatalf("terminal output unexpectedly contained %q: %q", unwanted, c.String()) + } + time.Sleep(50 * time.Millisecond) + } +} + +// TestDockerBackendTerminalIntegration exercises the interactive PTY against a +// real daemon and the standard image: live output, window resize, and Ctrl-C. +func TestDockerBackendTerminalIntegration(t *testing.T) { + cfg := dockerIntegrationConfig(t) + manager := newDockerIntegrationManager(t, cfg) + + ctx, cancel := context.WithTimeout( + types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID), + 6*time.Minute, + ) + defer cancel() + + sessionID := fmt.Sprintf("docker-terminal-%d", time.Now().UnixNano()) + t.Cleanup(func() { + cleanupCtx, cleanupCancel := context.WithTimeout( + types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID), + 2*time.Minute, + ) + defer cleanupCancel() + if err := manager.DestroySession(cleanupCtx, sessionID); err != nil { + t.Errorf("DestroySession: %v", err) + } + }) + + // Provision the session sandbox the way a chat turn would, then open the + // PTY on it. + executor := manager.SessionShellExecutor() + if executor == nil { + t.Fatal("session shell executor is unavailable on a healthy docker backend") + } + if _, err := executor.ExecShellCommand( + ctx, sessionID, "true", SessionWorkspaceRoot, time.Minute, nil, + ); err != nil { + t.Fatalf("provision session sandbox: %v", err) + } + + terminal := manager.SessionTerminalManager() + if terminal == nil { + t.Fatal("docker backend must advertise the terminal capability") + } + session, err := manager.OpenSessionTerminal(ctx, sessionID, + RemoteTerminalOptions{Cols: 100, Rows: 40}) + if err != nil { + t.Fatalf("OpenSessionTerminal: %v", err) + } + t.Cleanup(func() { _ = session.Close() }) + + capture := captureTerminal(session) + + // Live output: the computed value 42 does not appear in the typed command's + // own echo, so matching it proves the shell actually ran the line. + if err := session.Write(ctx, []byte("echo LIVE=$((6*7))\n")); err != nil { + t.Fatalf("write: %v", err) + } + capture.waitFor(t, "LIVE=42", 30*time.Second) + + // Resize: stty reports the geometry the PTY was resized to. The target + // differs from the 100x40 the PTY opened at, so a match proves ExecResize + // took effect rather than echoing the create-time ConsoleSize. + if err := session.Resize(ctx, 120, 30); err != nil { + t.Fatalf("resize: %v", err) + } + if err := session.Write(ctx, []byte("stty size\n")); err != nil { + t.Fatalf("write: %v", err) + } + capture.waitFor(t, "30 120", 30*time.Second) + + // The adapter's interactive defaults reach the shell (the daemon alone + // would leave TERM=xterm). + if err := session.Write(ctx, []byte("echo ENV=$TERM/$LC_ALL\n")); err != nil { + t.Fatalf("write: %v", err) + } + capture.waitFor(t, "ENV=xterm-256color/C.UTF-8", 30*time.Second) + + // Interrupt: Ctrl-C cancels the sleeping command, and its sentinel never + // runs. The prompt returning is proven by the follow-up echo completing. + if err := session.Write(ctx, []byte("sleep 60; echo SLOW=$((2+2))\n")); err != nil { + t.Fatalf("write: %v", err) + } + time.Sleep(500 * time.Millisecond) + if err := session.Write(ctx, []byte{0x03}); err != nil { + t.Fatalf("interrupt: %v", err) + } + if err := session.Write(ctx, []byte("echo AFTER=$((5+5))\n")); err != nil { + t.Fatalf("write: %v", err) + } + capture.waitFor(t, "AFTER=10", 20*time.Second) + capture.assertNever(t, "SLOW=4", 3*time.Second) +} + +// Closing a live Docker terminal must terminate the shell. The daemon keeps an +// exec (and its foreground jobs) alive when the hijacked connection goes away, +// so a bare disconnect would strand the process until the container is swept. +func TestDockerBackendTerminalCloseTerminatesShellIntegration(t *testing.T) { + cfg := dockerIntegrationConfig(t) + manager := newDockerIntegrationManager(t, cfg) + + ctx, cancel := context.WithTimeout( + types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID), + 6*time.Minute, + ) + defer cancel() + + sessionID := fmt.Sprintf("docker-terminal-close-%d", time.Now().UnixNano()) + t.Cleanup(func() { + cleanupCtx, cleanupCancel := context.WithTimeout( + types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID), + 2*time.Minute, + ) + defer cleanupCancel() + if err := manager.DestroySession(cleanupCtx, sessionID); err != nil { + t.Errorf("DestroySession: %v", err) + } + }) + + executor := manager.SessionShellExecutor() + if executor == nil { + t.Fatal("session shell executor is unavailable on a healthy docker backend") + } + if _, err := executor.ExecShellCommand( + ctx, sessionID, "true", SessionWorkspaceRoot, time.Minute, nil, + ); err != nil { + t.Fatalf("provision session sandbox: %v", err) + } + + session, err := manager.OpenSessionTerminal(ctx, sessionID, RemoteTerminalOptions{}) + if err != nil { + t.Fatalf("OpenSessionTerminal: %v", err) + } + go func() { + for range session.Output() { + } + }() + + // Record the shell PID and start a long foreground job with a unique + // marker so the probe can find the job without matching itself. + if err := session.Write(ctx, []byte("echo $$ > /tmp/weknora-close.pid\n")); err != nil { + t.Fatalf("write pid: %v", err) + } + // A job the user detached on purpose must outlive the hangup, as it would + // when any real terminal closes. + if err := session.Write(ctx, []byte("nohup sleep 3619 >/dev/null 2>&1 &\n")); err != nil { + t.Fatalf("write nohup job: %v", err) + } + if err := session.Write(ctx, []byte("sleep 3611\n")); err != nil { + t.Fatalf("write job: %v", err) + } + + // Positive control: the shell and its job must both be visible before the + // close, or a broken probe would read as a pass. + var shellPID string + for deadline := time.Now().Add(15 * time.Second); time.Now().Before(deadline); { + shellPID = strings.TrimSpace(terminalProbeOutput( + t, ctx, executor, sessionID, "cat /tmp/weknora-close.pid 2>/dev/null || true")) + if shellPID != "" && terminalProbeJobAlive(t, ctx, executor, sessionID, "sleep 3611") { + break + } + time.Sleep(300 * time.Millisecond) + } + if shellPID == "" { + t.Fatal("terminal shell never recorded its PID") + } + if !terminalProbeJobAlive(t, ctx, executor, sessionID, "sleep 3611") { + t.Fatal("positive control failed: foreground job not visible before close") + } + if !terminalProbeJobAlive(t, ctx, executor, sessionID, "sleep 3619") { + t.Fatal("positive control failed: nohup job not visible before close") + } + + if err := session.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + + // The hangup runs as a detached exec, so it may land just after Close + // returns; poll until both the shell and its job are gone. + for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline); { + alive := strings.Contains(terminalProbeOutput(t, ctx, executor, sessionID, + "if [ -d /proc/"+shellPID+" ]; then echo ALIVE; else echo DEAD; fi"), "ALIVE") + if !alive && !terminalProbeJobAlive(t, ctx, executor, sessionID, "sleep 3611") { + // Past the script's SIGKILL pass too, so a survivor is not just + // a job the second pass has yet to reach. + time.Sleep(3 * time.Second) + if !terminalProbeJobAlive(t, ctx, executor, sessionID, "sleep 3619") { + t.Fatal("Close killed a nohup'd job; a terminal hangup must spare it") + } + return + } + time.Sleep(500 * time.Millisecond) + } + t.Fatalf("Close left the shell (pid %s) and/or its foreground job running", shellPID) +} + +// Cancelling the caller's context must terminate the shell just like Close. The +// adapter's stream never observes the context on its own — the pump reads the +// hijacked connection and the moby hijack stops watching the context once +// upgraded — so without the lifetime watcher a cancelled context would leak the +// shell and (via the detached TTL refresh) pin the container forever. +func TestDockerBackendTerminalContextCancelTerminatesShellIntegration(t *testing.T) { + cfg := dockerIntegrationConfig(t) + manager := newDockerIntegrationManager(t, cfg) + + probeCtx, cancelProbe := context.WithTimeout( + types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID), + 6*time.Minute, + ) + defer cancelProbe() + + sessionID := fmt.Sprintf("docker-terminal-cancel-%d", time.Now().UnixNano()) + t.Cleanup(func() { + cleanupCtx, cleanupCancel := context.WithTimeout( + types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID), + 2*time.Minute, + ) + defer cleanupCancel() + if err := manager.DestroySession(cleanupCtx, sessionID); err != nil { + t.Errorf("DestroySession: %v", err) + } + }) + + executor := manager.SessionShellExecutor() + if executor == nil { + t.Fatal("session shell executor is unavailable on a healthy docker backend") + } + if _, err := executor.ExecShellCommand( + probeCtx, sessionID, "true", SessionWorkspaceRoot, time.Minute, nil, + ); err != nil { + t.Fatalf("provision session sandbox: %v", err) + } + + // The session ctx is a child of probeCtx so the probes below keep a live + // context after we cancel only the session's. + sessionCtx, cancelSession := context.WithCancel(probeCtx) + defer cancelSession() + session, err := manager.OpenSessionTerminal(sessionCtx, sessionID, RemoteTerminalOptions{}) + if err != nil { + t.Fatalf("OpenSessionTerminal: %v", err) + } + go func() { + for range session.Output() { + } + }() + + if err := session.Write(sessionCtx, []byte("echo $$ > /tmp/weknora-cancel.pid\n")); err != nil { + t.Fatalf("write pid: %v", err) + } + if err := session.Write(sessionCtx, []byte("sleep 3613\n")); err != nil { + t.Fatalf("write job: %v", err) + } + + var shellPID string + for deadline := time.Now().Add(15 * time.Second); time.Now().Before(deadline); { + shellPID = strings.TrimSpace(terminalProbeOutput( + t, probeCtx, executor, sessionID, "cat /tmp/weknora-cancel.pid 2>/dev/null || true")) + if shellPID != "" && terminalProbeJobAlive(t, probeCtx, executor, sessionID, "sleep 3613") { + break + } + time.Sleep(300 * time.Millisecond) + } + if shellPID == "" { + t.Fatal("terminal shell never recorded its PID") + } + if !terminalProbeJobAlive(t, probeCtx, executor, sessionID, "sleep 3613") { + t.Fatal("positive control failed: foreground job not visible before cancel") + } + + // Cancel only. No Close(). + cancelSession() + + for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline); { + alive := strings.Contains(terminalProbeOutput(t, probeCtx, executor, sessionID, + "if [ -d /proc/"+shellPID+" ]; then echo ALIVE; else echo DEAD; fi"), "ALIVE") + if !alive && !terminalProbeJobAlive(t, probeCtx, executor, sessionID, "sleep 3613") { + return + } + time.Sleep(500 * time.Millisecond) + } + t.Fatalf("cancelling the context left the shell (pid %s) and/or its job running", shellPID) +} + +func terminalProbeOutput( + t *testing.T, ctx context.Context, executor SessionShellExecutor, sessionID, script string, +) string { + t.Helper() + result, err := executor.ExecShellCommand( + ctx, sessionID, script, SessionWorkspaceRoot, 30*time.Second, nil) + if err != nil { + t.Fatalf("probe: %v", err) + } + return result.Stdout +} + +// terminalProbeJobAlive reports whether the foreground job (jobCmd, e.g. +// "sleep 3611") is still running. The pattern is anchored to the start of the +// command line so the probe's own shell (whose argv contains the pattern text) +// never matches itself. +func terminalProbeJobAlive( + t *testing.T, ctx context.Context, executor SessionShellExecutor, sessionID, jobCmd string, +) bool { + t.Helper() + out := terminalProbeOutput(t, ctx, executor, sessionID, + `n=0; for p in /proc/[0-9]*; do cmd=$(tr '\0' ' ' < "$p/cmdline" 2>/dev/null); case "$cmd" in "`+jobCmd+` "*) n=$((n+1));; esac; done; echo $n`) + return strings.TrimSpace(out) != "0" +} diff --git a/internal/sandbox/docker_remote_client.go b/internal/sandbox/docker_remote_client.go index 4ce9cc02..106b752e 100644 --- a/internal/sandbox/docker_remote_client.go +++ b/internal/sandbox/docker_remote_client.go @@ -216,7 +216,9 @@ func (c *DockerRemoteClient) Provider() RemoteProvider { return SandboxTypeDocke // refresh: idle reclamation is WeKnora's own sweep, not a provider feature. // SupportsVolumes is false until the volume-mount surface is mapped onto // Docker named volumes; advertising it early would let a workspace configure -// a mount that silently never appears. +// a mount that silently never appears. SupportsDesktop stays false: the +// desktop needs a way to reach the container's websockify port, which this +// backend has no gateway for yet. func (c *DockerRemoteClient) Capabilities() RemoteSandboxCapabilities { return RemoteSandboxCapabilities{ SupportsReconnect: true, @@ -230,6 +232,8 @@ func (c *DockerRemoteClient) Capabilities() RemoteSandboxCapabilities { // filesystem-only (no memory) and lives on this daemon. SupportsSnapshots: true, SupportsVolumes: false, + // The terminal is a hijacked TTY exec; see docker_terminal.go. + SupportsTerminals: true, } } diff --git a/internal/sandbox/docker_remote_client_test.go b/internal/sandbox/docker_remote_client_test.go index f92d73d2..4fc11703 100644 --- a/internal/sandbox/docker_remote_client_test.go +++ b/internal/sandbox/docker_remote_client_test.go @@ -53,7 +53,23 @@ type fakeDockerEngine struct { execStdout string execStderr string execExit int - execErr error + // execCreateHook observes each ExecCreate from whatever goroutine issued + // it, so a test can wait for a background exec (the terminal's marker + // refresh) without racing on the execOptions slice. + execCreateHook func(client.ExecCreateOptions) + // execInspectPID is what ExecInspect reports as the running process PID, + // used by the terminal's best-effort PID lookup. + execInspectPID int + // execInspectRunning is how many ExecInspect calls still report the exec + // as running before it reports the exit, which is how a daemon that has + // not recorded the exit code yet when the TTY stream hits EOF looks. + execInspectRunning atomic.Int32 + execInspects atomic.Int32 + // execStarts records every ExecStart, so a test can prove the terminal's + // terminate exec was launched (detached) at close. + execStarts []execStartCall + execStartErr error + execErr error // execNotRunningOnce makes the first ExecCreate fail the way the daemon // does when the container has not reached State.Running yet. execNotRunningOnce bool @@ -64,6 +80,22 @@ type fakeDockerEngine struct { execStreamStalls bool execStream *stalledReader + // PTY (terminal) path. attachedOptions records every ExecAttach so a test + // can assert TTY was requested; execResizes records ExecResize calls. + // terminalStream, when set, is handed to a TTY attach verbatim (no stdcopy + // framing — that is exactly what a real TTY attach looks like). + attachedOptions []client.ExecAttachOptions + execResizes []client.ExecResizeOptions + execResizeErr error + terminalStream io.Reader + // terminalBlocks makes a TTY attach return a stream that only ends when + // the hijacked connection is closed, mirroring a live shell. + terminalBlocks bool + // terminalConn, when set, is the hijacked connection of a TTY attach, + // both halves: a test holding the peer of a net.Pipe gets real deadline + // and back-pressure semantics. + terminalConn net.Conn + statResult map[string]container.PathStat // statHook lets a test answer differently per call, which is how the // sweeper's re-check before deletion is exercised. @@ -189,6 +221,9 @@ func (f *fakeDockerEngine) ExecCreate( _ context.Context, _ string, options client.ExecCreateOptions, ) (client.ExecCreateResult, error) { f.execOptions = append(f.execOptions, options) + if f.execCreateHook != nil { + f.execCreateHook(options) + } if f.execNotRunningOnce && len(f.execOptions) == 1 { return client.ExecCreateResult{}, cerrdefs.ErrConflict.WithMessage( "container is not running") @@ -200,8 +235,34 @@ func (f *fakeDockerEngine) ExecCreate( } func (f *fakeDockerEngine) ExecAttach( - _ context.Context, _ string, _ client.ExecAttachOptions, + _ context.Context, _ string, options client.ExecAttachOptions, ) (client.ExecAttachResult, error) { + f.attachedOptions = append(f.attachedOptions, options) + // A TTY attach is a raw byte stream: the daemon does not prepend the + // stdcopy 8-byte frame headers. Hand back exactly what the test supplied. + if options.TTY { + if f.terminalConn != nil { + return client.ExecAttachResult{HijackedResponse: client.HijackedResponse{ + Conn: f.terminalConn, + Reader: bufio.NewReader(f.terminalConn), + }}, nil + } + if f.terminalBlocks { + release := make(chan struct{}) + return client.ExecAttachResult{HijackedResponse: client.HijackedResponse{ + Conn: &fakeHijackedConn{stdin: &f.execStdin, release: release}, + Reader: bufio.NewReader(&terminalHijackReader{release: release, tail: f.terminalStream}), + }}, nil + } + stream := f.terminalStream + if stream == nil { + stream = strings.NewReader(f.execStdout) + } + return client.ExecAttachResult{HijackedResponse: client.HijackedResponse{ + Conn: &fakeHijackedConn{stdin: &f.execStdin}, + Reader: bufio.NewReader(stream), + }}, nil + } if f.execStreamStalls { release := make(chan struct{}) f.execStream = &stalledReader{release: release} @@ -219,6 +280,23 @@ func (f *fakeDockerEngine) ExecAttach( }}, nil } +// terminalHijackReader is the raw-stream sibling of stalledReader: it blocks +// until the paired hijacked connection closes, then yields tail (if any) before +// EOF. That is how a real TTY attach ends when the client detaches. +type terminalHijackReader struct { + release <-chan struct{} + once sync.Once + tail io.Reader +} + +func (r *terminalHijackReader) Read(p []byte) (int, error) { + r.once.Do(func() { <-r.release }) + if r.tail == nil { + return 0, io.EOF + } + return r.tail.Read(p) +} + // stalledReader blocks until the hijacked connection it is paired with is // closed, then flushes the output a daemon still has buffered when a client // hangs up. Both halves matter: the block keeps the copy goroutine alive past @@ -250,10 +328,34 @@ func (r *stalledReader) Read(p []byte) (int, error) { return n, err } +func (f *fakeDockerEngine) ExecStart( + _ context.Context, execID string, options client.ExecStartOptions, +) (client.ExecStartResult, error) { + f.execStarts = append(f.execStarts, execStartCall{execID: execID, options: options}) + return client.ExecStartResult{}, f.execStartErr +} + +// execStartCall is one recorded ExecStart. +type execStartCall struct { + execID string + options client.ExecStartOptions +} + func (f *fakeDockerEngine) ExecInspect( _ context.Context, _ string, _ client.ExecInspectOptions, ) (client.ExecInspectResult, error) { - return client.ExecInspectResult{ExitCode: f.execExit}, nil + f.execInspects.Add(1) + if f.execInspectRunning.Add(-1) >= 0 { + return client.ExecInspectResult{Running: true, PID: f.execInspectPID}, nil + } + return client.ExecInspectResult{ExitCode: f.execExit, PID: f.execInspectPID}, nil +} + +func (f *fakeDockerEngine) ExecResize( + _ context.Context, _ string, options client.ExecResizeOptions, +) (client.ExecResizeResult, error) { + f.execResizes = append(f.execResizes, options) + return client.ExecResizeResult{}, f.execResizeErr } func (f *fakeDockerEngine) ContainerStatPath( @@ -1065,6 +1167,10 @@ func TestDockerClientCapabilities(t *testing.T) { "the daemon has no TTL to refresh; reclamation is WeKnora's own sweep") require.True(t, caps.SupportsSnapshots, "docker commit is the skill-image snapshot; without this flag install is refused") + require.True(t, caps.SupportsTerminals, + "the PTY is a hijacked TTY exec; without this flag the terminal tab shows unsupported") + require.False(t, caps.SupportsDesktop, + "desktop relaying is not scheduled for the docker backend yet") require.False(t, caps.SupportsVolumes) } diff --git a/internal/sandbox/docker_rpc_timeout.go b/internal/sandbox/docker_rpc_timeout.go index 0fb892d7..ba342a2a 100644 --- a/internal/sandbox/docker_rpc_timeout.go +++ b/internal/sandbox/docker_rpc_timeout.go @@ -98,6 +98,14 @@ func (a *dockerRPCTimeoutAPI) ExecAttach( return a.inner.ExecAttach(ctx, execID, options) } +func (a *dockerRPCTimeoutAPI) ExecStart( + ctx context.Context, execID string, options client.ExecStartOptions, +) (client.ExecStartResult, error) { + rpcCtx, cancel := a.rpcCtx(ctx) + defer cancel() + return a.inner.ExecStart(rpcCtx, execID, options) +} + func (a *dockerRPCTimeoutAPI) ExecInspect( ctx context.Context, execID string, options client.ExecInspectOptions, ) (client.ExecInspectResult, error) { @@ -106,6 +114,14 @@ func (a *dockerRPCTimeoutAPI) ExecInspect( return a.inner.ExecInspect(rpcCtx, execID, options) } +func (a *dockerRPCTimeoutAPI) ExecResize( + ctx context.Context, execID string, options client.ExecResizeOptions, +) (client.ExecResizeResult, error) { + rpcCtx, cancel := a.rpcCtx(ctx) + defer cancel() + return a.inner.ExecResize(rpcCtx, execID, options) +} + func (a *dockerRPCTimeoutAPI) ContainerStatPath( ctx context.Context, containerID string, options client.ContainerStatPathOptions, ) (client.ContainerStatPathResult, error) { diff --git a/internal/sandbox/docker_terminal.go b/internal/sandbox/docker_terminal.go new file mode 100644 index 00000000..68304ba0 --- /dev/null +++ b/internal/sandbox/docker_terminal.go @@ -0,0 +1,421 @@ +// Interactive terminal (PTY) capability for the Docker adapter. +// +// Cube and E2B ride envd's PTY service, so their adapters translate an SDK +// handle. Docker has no such service: the PTY is a plain `exec` created with +// TTY=true whose hijacked connection is a raw byte stream, and window resizes +// go through a separate Engine call. This file bridges that to the neutral +// RemoteTerminalSession contract. +// +// One structural difference from envd: a Docker exec cannot be re-attached. +// /exec/{id}/start runs once and the Engine API has no exec attach endpoint, +// so RemoteTerminalOptions.AttachPID is ignored and every reconnecting browser +// gets a fresh shell. It also cannot be left running: unlike Cube/E2B, closing +// the hijacked connection does NOT end the shell (verified against a live +// daemon — an idle bash and its foreground jobs survive), so abandoning it +// would strand processes in the container. Close therefore hangs up the shell +// the way a closing terminal emulator would. See dockerTerminalKillCmd. + +package sandbox + +import ( + "bufio" + "context" + "crypto/rand" + "encoding/hex" + "errors" + "io" + "net" + "strconv" + "sync" + "time" + + "github.com/Tencent/WeKnora/internal/logger" + "github.com/moby/moby/client" +) + +// Compile-time proof that the Docker adapter serves the terminal capability. +var _ RemoteTerminalManager = (*DockerRemoteClient)(nil) + +const ( + // dockerTerminalActivityTimeout bounds the marker-refresh exec. It is a + // trivial `true`, so this only has to outlast a round trip. + dockerTerminalActivityTimeout = 15 * time.Second + // dockerTerminalInspectTimeout bounds the exit-code read that follows the + // stream ending. + dockerTerminalInspectTimeout = 5 * time.Second + // dockerTerminalInspectPoll is how often that read retries while the + // daemon still reports the exec as running: the hijacked stream can hit + // EOF before the daemon records the exit code. + dockerTerminalInspectPoll = 100 * time.Millisecond + // dockerTerminalKillTimeout bounds the best-effort terminate exec issued + // when a terminal is closed while its shell is still alive. + dockerTerminalKillTimeout = 10 * time.Second +) + +// dockerTerminalIDEnv tags every process of one terminal. The PTY exec gets +// this variable set to a per-open token, and every process it starts inherits +// it — which is what lets teardown find and kill the shell's whole tree from +// inside the container, without having to map ExecInspect's host PID into the +// container's PID namespace. +const dockerTerminalIDEnv = "WEKNORA_TERMINAL_ID" + +// dockerTerminalToken mints a per-open marker. It only has to distinguish +// concurrent terminals in one container, so a random 16-byte hex string is +// more than enough and stays shell-safe. +func dockerTerminalToken() string { + var b [16]byte + if _, err := rand.Read(b[:]); err != nil { + // crypto/rand failing is a broken host; a time-based token still + // separates concurrent opens well enough for a best-effort kill. + return strconv.FormatInt(time.Now().UnixNano(), 16) + } + return hex.EncodeToString(b[:]) +} + +// dockerTerminalEnvs is the PTY's environment. Cube and E2B get TERM, LANG +// and LC_ALL from their SDK; a Docker exec gets nothing but the daemon's +// TERM=xterm, which loses 256 colours and, on an image without a LANG, breaks +// multibyte input. The defaults below mirror the E2B SDK, caller envs win, and +// the per-open marker is always set last so nothing can override it. +func dockerTerminalEnvs(opts RemoteTerminalOptions, terminalID string) map[string]string { + envs := map[string]string{ + "TERM": "xterm-256color", + "LANG": "C.UTF-8", + "LC_ALL": "C.UTF-8", + } + for key, value := range terminalEnvs(opts) { + envs[key] = value + } + envs[dockerTerminalIDEnv] = terminalID + return envs +} + +// dockerTerminalShellCmd is the argv the PTY runs. bash is preferred for line +// editing and job control; a minimal image that only ships the POSIX shell +// still gets a usable terminal instead of "no such file". +func dockerTerminalShellCmd() []string { + return []string{ + "/bin/sh", "-c", + "if command -v bash >/dev/null 2>&1; then exec bash; else exec sh; fi", + } +} + +// OpenTerminal opens an interactive shell PTY inside the container behind +// handle. The returned session streams until the shell exits, the context +// passed to OpenTerminal is cancelled, or Close is called — the last two end +// it identically (through Close, which also terminates the shell). +func (c *DockerRemoteClient) OpenTerminal( + ctx context.Context, + handle RemoteSandboxHandle, + opts RemoteTerminalOptions, +) (RemoteTerminalSession, error) { + id, err := dockerHandleID("OpenTerminal", handle) + if err != nil { + return nil, err + } + + terminalID := dockerTerminalToken() + execOpts := client.ExecCreateOptions{ + Cmd: dockerTerminalShellCmd(), + User: dockerExecUser(opts.User), + WorkingDir: terminalCwd(opts), + Env: dockerEnvSlice(dockerTerminalEnvs(opts, terminalID)), + TTY: true, + AttachStdin: true, + AttachStdout: true, + AttachStderr: true, + ConsoleSize: client.ConsoleSize{ + Height: uint(terminalRows(opts)), + Width: uint(terminalCols(opts)), + }, + } + created, err := c.api.ExecCreate(ctx, id, execOpts) + if err != nil && dockerContainerNotRunning(err) { + if readyErr := c.ensureRunning(ctx, id, "OpenTerminal"); readyErr != nil { + return nil, readyErr + } + created, err = c.api.ExecCreate(ctx, id, execOpts) + } + if err != nil { + return nil, dockerError("OpenTerminal", err) + } + + // ExecAttach both starts the exec and hijacks its stdio. With TTY=true the + // hijacked stream is raw bytes — no stdcopy 8-byte framing — so the pump + // below reads it directly. + attached, err := c.api.ExecAttach(ctx, created.ID, client.ExecAttachOptions{TTY: true}) + if err != nil { + return nil, dockerError("OpenTerminal", err) + } + + // The exit code has to be readable after the WebSocket handler's request + // context is gone, so the session keeps a detached copy for its one + // inspect call at stream end. + inspectCtx := context.WithoutCancel(ctx) + session := &dockerTerminalSession{ + api: c.api, + containerID: id, + execID: created.ID, + terminalID: terminalID, + conn: attached.Conn, + reader: attached.Reader, + out: make(chan RemoteTerminalEvent, terminalOutputBuffer), + closedCh: make(chan struct{}), + inspectCtx: inspectCtx, + } + go session.pump() + + // The caller's context is part of the session's lifetime, matching Cube and + // E2B. Nothing else can honour it: the pump only reads the hijacked stream + // and the moby hijack stops watching the context once the connection is + // upgraded, so without this watcher a caller that only cancels its context + // (never calling Close) would leave the shell running — and, worse, the TTL + // refresh below rides a detached context, so it would keep the container + // from ever being idle-reclaimed. Cancellation goes through the same Close + // path as everything else, so it reaps the shell too. + go func() { + select { + case <-ctx.Done(): + _ = session.Close() + case <-session.closedCh: + } + }() + + // A PTY never runs the exec wrapper that touches the idle-sweep activity + // marker, so without this a session that only ever sits in the terminal + // would be reclaimed mid-use at its TTL. Exec refreshes the marker on its + // way through the wrapper; a zero IdleTTL (sweeping disabled) no-ops. The + // refresh is deliberately on the detached context: it must survive the + // request context the handler used, and stops when closedCh closes. + startTerminalTTLRefresh(inspectCtx, session.closedCh, c.settings.IdleTTL, + func(rctx context.Context) error { + _, err := c.Exec(rctx, handle, RemoteExecRequest{ + Command: "true", + Timeout: dockerTerminalActivityTimeout, + }) + return err + }) + return session, nil +} + +// dockerTerminalSession bridges one hijacked TTY exec stream to the neutral +// RemoteTerminalSession contract. +type dockerTerminalSession struct { + api dockerEngineAPI + // containerID is where the terminate exec is created; the shell lives in + // this container and the kill has to run there too. + containerID string + execID string + // terminalID is the per-open marker set in the shell's environment; the + // terminate exec matches it to find the shell and its descendants. + terminalID string + conn net.Conn + reader *bufio.Reader + + out chan RemoteTerminalEvent + closedCh chan struct{} + // closeOnce guards both closedCh and conn so concurrent Close calls are + // safe (RemoteTerminalSession documents Close as idempotent). + closeOnce sync.Once + // killOnce serialises the terminate exec: pump reaching its end and an + // explicit Close can both arrive, and the kill must run at most once. + killOnce sync.Once + inspectCtx context.Context +} + +// pump copies raw PTY output into the event channel until the stream ends. +func (s *dockerTerminalSession) pump() { + defer close(s.out) + + var readErr error + buf := make([]byte, 32*1024) + for { + n, err := s.reader.Read(buf) + if n > 0 { + // The daemon reuses the buffer, so copy before emitting. + chunk := make([]byte, n) + copy(chunk, buf[:n]) + emitTerminalEvent(s.out, s.closedCh, RemoteTerminalEvent{Data: chunk}) + } + if err != nil { + readErr = err + break + } + } + + // Close tears the stream down on purpose; that is not a terminal failure + // and must not be reported as one. + select { + case <-s.closedCh: + return + default: + } + + switch { + case readErr == nil || errors.Is(readErr, io.EOF): + // The daemon ended the stream itself (the shell exited). Its exit code + // is the only useful thing left to report. + emitTerminalEvent(s.out, s.closedCh, + RemoteTerminalEvent{Exited: true, ExitCode: s.inspectExitCode()}) + default: + emitTerminalEvent(s.out, s.closedCh, + RemoteTerminalEvent{Err: dockerError("terminal stream", readErr)}) + } + // The stream is over; release the marker-refresh loop now instead of + // waiting for the handler to get around to Close. + s.teardown() +} + +func (s *dockerTerminalSession) inspectExitCode() int { + ctx, cancel := context.WithTimeout(s.inspectCtx, dockerTerminalInspectTimeout) + defer cancel() + for { + inspected, err := s.api.ExecInspect(ctx, s.execID, client.ExecInspectOptions{}) + if err != nil { + return -1 + } + if !inspected.Running { + return inspected.ExitCode + } + select { + case <-ctx.Done(): + return -1 + case <-time.After(dockerTerminalInspectPoll): + } + } +} + +func (s *dockerTerminalSession) Output() <-chan RemoteTerminalEvent { return s.out } + +// PID is always 0. ExecInspect only knows the host PID, which means nothing +// inside the container and must not reach the browser; and since the exec +// cannot be re-attached there is no identifier worth handing out for a +// reconnect either. 0 keeps the frontend from sending a pty_id back. +func (s *dockerTerminalSession) PID() uint32 { return 0 } + +// Write feeds keystrokes into the PTY. net.Conn is safe for concurrent use, so +// no lock is needed against Resize/Close. +// +// The hijacked conn does not see ctx, so its deadline is applied explicitly: +// a PTY whose foreground program stops reading stdin back-pressures this +// write, and without a deadline the caller's input loop would hang with it. +// Only the bridge's input pump writes, so setting the deadline here does not +// race another writer. +func (s *dockerTerminalSession) Write(ctx context.Context, data []byte) error { + if len(data) == 0 { + return nil + } + if deadline, ok := ctx.Deadline(); ok { + _ = s.conn.SetWriteDeadline(deadline) + defer func() { _ = s.conn.SetWriteDeadline(time.Time{}) }() + } + if _, err := s.conn.Write(data); err != nil { + return dockerError("terminal input", err) + } + return nil +} + +func (s *dockerTerminalSession) Resize(ctx context.Context, cols, rows uint32) error { + if cols == 0 || rows == 0 { + return nil + } + if _, err := s.api.ExecResize(ctx, s.execID, client.ExecResizeOptions{ + Height: uint(rows), + Width: uint(cols), + }); err != nil { + return dockerError("terminal resize", err) + } + return nil +} + +// Close detaches WeKnora from the PTY and, because Docker has no re-attach to +// preserve, hangs up the shell inside the container. Unlike Cube/E2B, +// closing the hijacked connection does not end the exec — the daemon keeps it +// (and any foreground jobs) alive — so a bare disconnect would strand the +// process until the container is swept. Safe to call more than once. +func (s *dockerTerminalSession) Close() error { + s.teardown() + s.terminate() + return nil +} + +// terminate hangs up the exec's shell and the processes it started, best +// effort. It runs from Close only, but Close follows every session end, +// including a shell that already exited on its own: then the shell is gone and +// the hangup only reaches jobs it left behind. Runs at most once. +// +// A failed terminate leaves the shell running until the container is swept, so +// it is logged: nothing else would ever surface the leak. +func (s *dockerTerminalSession) terminate() { + s.killOnce.Do(func() { + ctx, cancel := context.WithTimeout(s.inspectCtx, dockerTerminalKillTimeout) + defer cancel() + created, err := s.api.ExecCreate(ctx, s.containerID, client.ExecCreateOptions{ + Cmd: dockerTerminalKillCmd(s.terminalID), + User: dockerExecUser(""), + }) + if err != nil { + logger.Warnf(ctx, "[sandbox-terminal] docker terminate exec create failed container=%s exec=%s: %v", + s.containerID, s.execID, err) + return + } + // Detached: the kill outlives this context and needs no output. + if _, err := s.api.ExecStart(ctx, created.ID, client.ExecStartOptions{Detach: true}); err != nil { + logger.Warnf(ctx, "[sandbox-terminal] docker terminate exec start failed container=%s exec=%s: %v", + s.containerID, s.execID, err) + } + }) +} + +// dockerTerminalKillCmd builds the argv that hangs up an abandoned PTY shell +// and the processes it started. +// +// It matches on the marker environment variable rather than a PID because +// ExecInspect reports the *host* PID, which is meaningless inside the +// container's PID namespace — a kill exec running there cannot see /proc/. +// Every process the shell starts inherits WEKNORA_TERMINAL_ID, so walking +// /proc finds the shell and its whole job tree (a running foreground job is in +// its own process group, so signalling the shell or its group alone would +// orphan it). A shell that already exited has no carriers left, which is why +// no existence check is needed before running it. +// +// The signals mirror a terminal emulator closing: SIGHUP (plus SIGCONT so a +// stopped job sees it) ends the shell and its jobs, while anything the user +// detached on purpose with nohup or a HUP trap keeps running, as it would on +// any real terminal. Only the session leader — the shell itself — is SIGKILLed +// if it is still alive after the grace period. +// +// /proc is read directly instead of shelling out to pgrep/pkill, which minimal +// sandbox images do not ship; the entry is compared with a shell `case` rather +// than grep for the same reason. +func dockerTerminalKillCmd(token string) []string { + script := `m="` + dockerTerminalIDEnv + `=$1" +carriers() { +for d in /proc/[0-9]*; do +e=$(tr '\0' '\n' < "$d/environ" 2>/dev/null) || continue +case "$e" in *"$m"*) echo "${d#/proc/}" ;; esac +done +} +pids=$(carriers) +[ -n "$pids" ] || exit 0 +kill -HUP $pids 2>/dev/null +kill -CONT $pids 2>/dev/null +sleep 2 +for q in $(carriers); do +s=$(cat "/proc/$q/stat" 2>/dev/null) || continue +set -- ${s##*) } +[ "$4" = "$q" ] && kill -9 "$q" 2>/dev/null +done +exit 0` + return []string{"/bin/sh", "-c", script, "weknora-terminate", token} +} + +// teardown closes the stream and the marker-refresh loop exactly once. Both +// Close and the end of pump call it, so it is the single choke point for the +// idempotent-close contract. +func (s *dockerTerminalSession) teardown() { + s.closeOnce.Do(func() { + close(s.closedCh) + _ = s.conn.Close() + }) +} diff --git a/internal/sandbox/docker_terminal_test.go b/internal/sandbox/docker_terminal_test.go new file mode 100644 index 00000000..d75dd7fe --- /dev/null +++ b/internal/sandbox/docker_terminal_test.go @@ -0,0 +1,478 @@ +package sandbox + +import ( + "bytes" + "context" + "errors" + "net" + "strings" + "sync" + "testing" + "time" + + "github.com/moby/moby/client" + "github.com/stretchr/testify/require" +) + +// newTerminalTestClient builds a Docker client with the idle sweep enabled, so +// the terminal's activity-marker refresh actually runs (newTestDockerClient +// disables it). ttl is the sweep window handed to the client. +func newTerminalTestClient( + t *testing.T, engine *fakeDockerEngine, ttl time.Duration, +) *DockerRemoteClient { + t.Helper() + settings, err := dockerSettingsFromConfig(&Config{ + Type: SandboxTypeDocker, + DockerImage: "weknora/sandbox:test", + }) + require.NoError(t, err) + settings.IdleTTL = ttl + return newDockerRemoteClientWithAPI(engine, settings) +} + +func TestDockerOpenTerminalConfiguresTTYExec(t *testing.T) { + engine := newFakeDockerEngine() + engine.execStdout = "ready\n" + docker := newTestDockerClient(t, engine) + + session, err := docker.OpenTerminal(context.Background(), testHandle("c"), + RemoteTerminalOptions{ + Cols: 100, Rows: 40, + User: "user", + Cwd: "/workspace", + Envs: map[string]string{"FOO": "bar"}, + }) + require.NoError(t, err) + t.Cleanup(func() { _ = session.Close() }) + + require.Len(t, engine.execOptions, 1) + created := engine.execOptions[0] + require.True(t, created.TTY, "a PTY needs TTY=true") + require.True(t, created.AttachStdin) + require.True(t, created.AttachStdout) + require.True(t, created.AttachStderr) + require.Equal(t, "user", created.User) + require.Equal(t, "/workspace", created.WorkingDir) + require.Equal(t, uint(40), created.ConsoleSize.Height) + require.Equal(t, uint(100), created.ConsoleSize.Width) + require.Contains(t, created.Env, "FOO=bar") + require.Equal(t, []string{ + "/bin/sh", "-c", + "if command -v bash >/dev/null 2>&1; then exec bash; else exec sh; fi", + }, created.Cmd, "the PTY must launch an interactive shell, not a bare command") + + require.Len(t, engine.attachedOptions, 1) + require.True(t, engine.attachedOptions[0].TTY) +} + +// A Docker exec gets only the daemon's TERM=xterm, so with no caller envs (the +// WebSocket handler never sends any) the adapter itself must supply what the +// Cube/E2B SDKs default: 256 colours and a UTF-8 locale. +func TestDockerOpenTerminalDefaultsInteractiveEnv(t *testing.T) { + engine := newFakeDockerEngine() + docker := newTestDockerClient(t, engine) + + session, err := docker.OpenTerminal(context.Background(), testHandle("c"), + RemoteTerminalOptions{}) + require.NoError(t, err) + t.Cleanup(func() { _ = session.Close() }) + + require.Len(t, engine.execOptions, 1) + env := engine.execOptions[0].Env + require.Contains(t, env, "TERM=xterm-256color") + require.Contains(t, env, "LANG=C.UTF-8") + require.Contains(t, env, "LC_ALL=C.UTF-8") + require.NotEmpty(t, terminalMarkerToken(t, engine.execOptions[0])) +} + +// Caller envs override the defaults, but never the teardown marker: a caller +// that could pick it would steer the terminate exec at another terminal. +func TestDockerOpenTerminalCallerEnvOverridesDefaultsButNotMarker(t *testing.T) { + engine := newFakeDockerEngine() + docker := newTestDockerClient(t, engine) + + session, err := docker.OpenTerminal(context.Background(), testHandle("c"), + RemoteTerminalOptions{Envs: map[string]string{ + "TERM": "screen", + "LANG": "zh_CN.UTF-8", + dockerTerminalIDEnv: "chosen", + }}) + require.NoError(t, err) + t.Cleanup(func() { _ = session.Close() }) + + env := engine.execOptions[0].Env + require.Contains(t, env, "TERM=screen") + require.Contains(t, env, "LANG=zh_CN.UTF-8") + require.NotContains(t, env, "TERM=xterm-256color") + require.NotEqual(t, "chosen", terminalMarkerToken(t, engine.execOptions[0])) +} + +// The hijacked conn does not watch ctx. A PTY that stops reading stdin +// back-pressures Write, and without the ctx deadline the bridge's input loop +// would hang until something else tore the session down. +func TestDockerTerminalWriteHonoursContextDeadline(t *testing.T) { + local, remote := net.Pipe() + t.Cleanup(func() { _ = remote.Close() }) + engine := newFakeDockerEngine() + engine.terminalConn = local + docker := newTestDockerClient(t, engine) + + session, err := docker.OpenTerminal(context.Background(), testHandle("c"), + RemoteTerminalOptions{}) + require.NoError(t, err) + t.Cleanup(func() { _ = session.Close() }) + + // Nobody reads remote, so the pipe write blocks like a full PTY. + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + errCh := make(chan error, 1) + go func() { errCh <- session.Write(ctx, []byte("ls\n")) }() + select { + case err := <-errCh: + require.Error(t, err, "a back-pressured write must give up at the ctx deadline") + case <-time.After(2 * time.Second): + t.Fatal("Write ignored the ctx deadline") + } + + // The deadline is per call: a later write without one must not inherit + // the expired deadline and fail immediately. + received := make(chan []byte, 1) + go func() { + buf := make([]byte, 16) + n, _ := remote.Read(buf) + received <- buf[:n] + }() + require.NoError(t, session.Write(context.Background(), []byte("pwd\n"))) + require.Equal(t, []byte("pwd\n"), <-received) +} + +// The terminate exec is best effort: a daemon refusing to start it must not +// turn Close into an error or a hang. +func TestDockerTerminalCloseToleratesTerminateFailure(t *testing.T) { + engine := newFakeDockerEngine() + engine.terminalBlocks = true + engine.execStartErr = errors.New("daemon refused") + docker := newTestDockerClient(t, engine) + + session, err := docker.OpenTerminal(context.Background(), testHandle("c"), + RemoteTerminalOptions{}) + require.NoError(t, err) + go drainTerminalOutput(session) + + require.NoError(t, session.Close()) + require.Len(t, engine.execStarts, 1, "the terminate exec was attempted") + require.NoError(t, session.Close(), "a second Close stays a no-op") + require.Len(t, engine.execStarts, 1) +} + +// A TTY attach is a raw byte stream. If the adapter reused the exec path's +// stdcopy demultiplexer here, the first 8 bytes would be eaten as a frame +// header and every keystroke echo would come back garbled. +func TestDockerTerminalStreamsRawBytesAndExitCode(t *testing.T) { + engine := newFakeDockerEngine() + engine.execStdout = "hello\r\n" + engine.execExit = 7 + docker := newTestDockerClient(t, engine) + + session, err := docker.OpenTerminal(context.Background(), testHandle("c"), + RemoteTerminalOptions{}) + require.NoError(t, err) + t.Cleanup(func() { _ = session.Close() }) + + var got bytes.Buffer + var exitCode *int + deadline := time.After(2 * time.Second) + for exitCode == nil { + select { + case ev, ok := <-session.Output(): + require.True(t, ok, "stream closed without an exit event") + require.NoError(t, ev.Err) + if ev.Exited { + code := ev.ExitCode + exitCode = &code + break + } + got.Write(ev.Data) + case <-deadline: + t.Fatalf("timed out waiting for exit; got %q", got.String()) + } + } + require.Equal(t, "hello\r\n", got.String(), + "TTY output must be raw, not stdcopy-framed") + require.Equal(t, 7, *exitCode) +} + +// The TTY stream can reach EOF before the daemon records the exit; reading the +// exit code once at that moment would report 0 for a shell that failed. +func TestDockerTerminalWaitsForExecExitBeforeReportingCode(t *testing.T) { + engine := newFakeDockerEngine() + engine.execExit = 23 + engine.execInspectRunning.Store(2) + docker := newTestDockerClient(t, engine) + + session, err := docker.OpenTerminal(context.Background(), testHandle("c"), + RemoteTerminalOptions{}) + require.NoError(t, err) + t.Cleanup(func() { _ = session.Close() }) + + deadline := time.After(3 * time.Second) + for { + select { + case ev, ok := <-session.Output(): + require.True(t, ok, "stream closed without an exit event") + require.NoError(t, ev.Err) + if !ev.Exited { + continue + } + require.Equal(t, 23, ev.ExitCode) + require.EqualValues(t, 3, engine.execInspects.Load(), + "the exit code is read only once the exec stops running") + return + case <-deadline: + t.Fatal("timed out waiting for exit") + } + } +} + +func TestDockerTerminalWriteResizeAndPID(t *testing.T) { + engine := newFakeDockerEngine() + engine.execInspectPID = 4321 + engine.terminalBlocks = true + docker := newTestDockerClient(t, engine) + + session, err := docker.OpenTerminal(context.Background(), testHandle("c"), + RemoteTerminalOptions{}) + require.NoError(t, err) + t.Cleanup(func() { _ = session.Close() }) + + require.Zero(t, session.PID(), + "ExecInspect's PID is a host PID; it must not reach the browser as a pty_id") + + require.NoError(t, session.Write(context.Background(), []byte("ls\n"))) + require.Equal(t, "ls\n", engine.execStdin.String()) + + require.NoError(t, session.Resize(context.Background(), 120, 30)) + require.Len(t, engine.execResizes, 1) + require.Equal(t, uint(30), engine.execResizes[0].Height) + require.Equal(t, uint(120), engine.execResizes[0].Width) + + // A zero dimension is the "browser has not measured yet" case; it must + // not reach the daemon. + require.NoError(t, session.Resize(context.Background(), 0, 0)) + require.Len(t, engine.execResizes, 1) +} + +// 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 TestDockerTerminalCloseIsIdempotentUnderConcurrency(t *testing.T) { + engine := newFakeDockerEngine() + engine.terminalBlocks = true + docker := newTestDockerClient(t, engine) + + session, err := docker.OpenTerminal(context.Background(), testHandle("c"), + RemoteTerminalOptions{}) + require.NoError(t, err) + + drained := make(chan struct{}) + go func() { + defer close(drained) + drainTerminalOutput(session) + }() + + 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() + + select { + case <-drained: + case <-time.After(3 * time.Second): + t.Fatal("Output channel never closed after Close") + } +} + +// Closing a live terminal must terminate the shell: a Docker exec with a TTY +// survives the hijacked connection going away, so a bare disconnect would +// strand the shell (and its jobs) until the container is swept. Close has to +// issue a kill exec itself, matching the terminal's marker env. +func TestDockerTerminalCloseTerminatesLiveShell(t *testing.T) { + engine := newFakeDockerEngine() + engine.terminalBlocks = true + docker := newTestDockerClient(t, engine) + + session, err := docker.OpenTerminal(context.Background(), testHandle("c"), + RemoteTerminalOptions{}) + require.NoError(t, err) + // The terminal's own TTY exec, and nothing else yet. + require.Len(t, engine.execOptions, 1) + token := terminalMarkerToken(t, engine.execOptions[0]) + + go drainTerminalOutput(session) + require.NoError(t, session.Close()) + + require.Len(t, engine.execOptions, 2, "Close must create a kill exec") + kill := engine.execOptions[1] + require.False(t, kill.TTY) + require.Equal(t, DefaultSandboxExecUser, kill.User) + require.Equal(t, dockerTerminalKillCmd(token), kill.Cmd, + "the kill must carry the terminal's marker token") + + require.Len(t, engine.execStarts, 1, "the kill exec must actually be started") + require.True(t, engine.execStarts[0].options.Detach, + "the kill must run detached so it outlives the request context") +} + +// The kill matches on the marker env, not a PID: ExecInspect reports a host +// PID that is meaningless inside the container's PID namespace, so a kill that +// targeted it would silently do nothing (the original bug). +func TestDockerTerminalKillCmdTargetsMarkerEnv(t *testing.T) { + cmd := dockerTerminalKillCmd("deadbeef") + require.Equal(t, "/bin/sh", cmd[0]) + require.Equal(t, "-c", cmd[1]) + require.Equal(t, "weknora-terminate", cmd[3]) + require.Equal(t, "deadbeef", cmd[4], "the token travels as argv") + require.Contains(t, cmd[2], dockerTerminalIDEnv+"=$1", + "the script matches the marker env") + require.Contains(t, cmd[2], "kill -HUP $pids", + "closing must hang up like a terminal so nohup'd jobs survive") + require.Contains(t, cmd[2], "kill -CONT $pids", + "a stopped job only acts on the hangup once continued") + require.NotContains(t, cmd[2], "kill -9 $pids", + "SIGKILL on every carrier would also take out nohup'd jobs") + require.Contains(t, cmd[2], `[ "$4" = "$q" ] && kill -9`, + "only the session leader (the shell) is force-killed after the grace period") + require.Contains(t, cmd[2], "/proc/[0-9]*", "it must walk every process") + require.NotContains(t, cmd[2], "ExecInspect") +} + +// drainTerminalOutput consumes a session's output until the channel closes, so +// the pump never stalls on a full buffer while a test drives Close. +func drainTerminalOutput(session RemoteTerminalSession) { + for event := range session.Output() { + _ = event + } +} + +// terminalMarkerToken extracts the WEKNORA_TERMINAL_ID value the adapter set on +// a captured ExecCreate, so a test can predict the kill argv. +func terminalMarkerToken(t *testing.T, opts client.ExecCreateOptions) string { + t.Helper() + prefix := dockerTerminalIDEnv + "=" + for _, entry := range opts.Env { + if strings.HasPrefix(entry, prefix) { + return strings.TrimPrefix(entry, prefix) + } + } + t.Fatalf("terminal exec is missing %s: %#v", dockerTerminalIDEnv, opts.Env) + return "" +} + +// The marker must be present and unique so two concurrent terminals in one +// container do not kill each other. +func TestDockerOpenTerminalTagsEachSession(t *testing.T) { + engine := newFakeDockerEngine() + engine.execStdout = "" + docker := newTestDockerClient(t, engine) + + first, err := docker.OpenTerminal(context.Background(), testHandle("c"), RemoteTerminalOptions{}) + require.NoError(t, err) + t.Cleanup(func() { _ = first.Close() }) + second, err := docker.OpenTerminal(context.Background(), testHandle("c"), RemoteTerminalOptions{}) + require.NoError(t, err) + t.Cleanup(func() { _ = second.Close() }) + + require.Len(t, engine.execOptions, 2) + a := terminalMarkerToken(t, engine.execOptions[0]) + b := terminalMarkerToken(t, engine.execOptions[1]) + require.NotEmpty(t, a) + require.NotEqual(t, a, b, "each terminal needs its own marker") +} + +// Cancelling the caller's context must end the session, exactly like an +// explicit Close. Nothing else in the adapter honours the context — the pump +// only reads the hijacked stream and the refresh rides a detached context — so +// without a watcher a cancelled context would leak the shell and pin the +// container (its marker stays fresh forever). +func TestDockerTerminalContextCancelEndsSession(t *testing.T) { + engine := newFakeDockerEngine() + engine.terminalBlocks = true + docker := newTestDockerClient(t, engine) + + // Signal the terminate exec through a channel: the watcher runs it on its + // own goroutine, so reading the exec slices here would race. + killCreated := make(chan struct{}) + var once sync.Once + engine.execCreateHook = func(opts client.ExecCreateOptions) { + if !opts.TTY { + once.Do(func() { close(killCreated) }) + } + } + + ctx, cancel := context.WithCancel(context.Background()) + session, err := docker.OpenTerminal(ctx, testHandle("c"), RemoteTerminalOptions{}) + require.NoError(t, err) + go drainTerminalOutput(session) + + cancel() + + select { + case <-session.(*dockerTerminalSession).closedCh: + case <-time.After(2 * time.Second): + t.Fatal("cancelling the context did not end the terminal session") + } + select { + case <-killCreated: + case <-time.After(2 * time.Second): + t.Fatal("cancelling the context did not run the terminate exec") + } +} + +// A PTY never runs the exec wrapper that refreshes the idle-sweep activity +// marker, so the terminal has to do it itself or the container is reclaimed +// mid-use at its TTL. +func TestDockerTerminalRefreshesActivityMarker(t *testing.T) { + prev := terminalTTLRefreshMin + terminalTTLRefreshMin = 20 * time.Millisecond + t.Cleanup(func() { terminalTTLRefreshMin = prev }) + + engine := newFakeDockerEngine() + engine.terminalBlocks = true + docker := newTerminalTestClient(t, engine, 30*time.Minute) + + // The refresh is a plain (non-TTY) exec; observe it through the hook so + // the background goroutine never races the test on the execOptions slice. + var once sync.Once + refreshed := make(chan struct{}) + engine.execCreateHook = func(options client.ExecCreateOptions) { + if !options.TTY { + once.Do(func() { close(refreshed) }) + } + } + + session, err := docker.OpenTerminal(context.Background(), testHandle("c"), + RemoteTerminalOptions{}) + require.NoError(t, err) + t.Cleanup(func() { _ = session.Close() }) + + select { + case <-refreshed: + case <-time.After(2 * time.Second): + t.Fatal("expected a marker-refresh exec while the terminal is open") + } +} + +// OpenTerminal must fail with a classified error, not a panic, on a bad handle. +func TestDockerOpenTerminalRejectsEmptyHandle(t *testing.T) { + docker := newTestDockerClient(t, newFakeDockerEngine()) + _, err := docker.OpenTerminal(context.Background(), nil, RemoteTerminalOptions{}) + require.Error(t, err) +} diff --git a/internal/sandbox/langfuse_test.go b/internal/sandbox/langfuse_test.go index 4711f182..485e7dc0 100644 --- a/internal/sandbox/langfuse_test.go +++ b/internal/sandbox/langfuse_test.go @@ -109,7 +109,7 @@ func TestWrapLangfuseRemoteClientPreservesDesktopTTLRefresh(t *testing.T) { } func TestWrapLangfuseRemoteClientDoesNotInventTerminalSupport(t *testing.T) { - // Docker advertises no terminal support; wrapping must not fake it. + // The fake advertises no terminal support; wrapping must not fake it. inner := newFakeRemoteClient(SandboxTypeDocker) wrapped := wrapLangfuseRemoteClient(inner) mgr, ok := TerminalManagerFrom(wrapped) diff --git a/internal/sandbox/sandbox.go b/internal/sandbox/sandbox.go index 8ec4e652..2b8a7314 100644 --- a/internal/sandbox/sandbox.go +++ b/internal/sandbox/sandbox.go @@ -5,6 +5,7 @@ package sandbox import ( "context" "errors" + "fmt" "time" ) @@ -165,6 +166,14 @@ var ( // again; the UI must get an explicit click first. Distinct from // ErrNoLiveSessionSandbox, which means there is no binding to resume. ErrSandboxPaused = errors.New("session sandbox is paused") + // ErrSandboxStopped is ErrSandboxPaused for a backend that never pauses + // (Docker): a bound sandbox that is not running is either a stopped + // container, which a resume restarts with its files intact, or one the + // idle sweep already deleted, which a resume replaces with a fresh one. + // The UI cannot promise "wake it up" there. It wraps ErrSandboxPaused, so + // every caller that only distinguishes "needs a confirmed click" keeps + // working unchanged. + ErrSandboxStopped = fmt.Errorf("%w: sandbox is stopped or was reclaimed", ErrSandboxPaused) // ErrSessionRewindLocked means another rewind already holds the session. ErrSessionRewindLocked = errors.New("sandbox: session rewind already in progress") // ErrSessionTurnActive means a chat turn already holds the session lease, diff --git a/internal/sandbox/session_manager.go b/internal/sandbox/session_manager.go index c7229053..33278887 100644 --- a/internal/sandbox/session_manager.go +++ b/internal/sandbox/session_manager.go @@ -962,7 +962,7 @@ func (m *SessionBoundManager) SessionFileStore() SessionFileStore { // 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). +// (E2B, Cube and Docker all do). func (m *SessionBoundManager) SessionTerminalManager() SessionTerminalManager { if m == nil || m.remoteDisabled() { return nil @@ -979,7 +979,7 @@ func (m *SessionBoundManager) SessionTerminalManager() SessionTerminalManager { // entry point lacks the config-pin context that agent-driven creation // relies on. A bound sandbox that is not confirmed running returns // ErrSandboxPaused unless opts.AllowResume is set — Connect would wake a -// paused instance. A backend that cannot stream PTYs (Docker) returns +// paused instance. A backend that cannot stream PTYs returns // ErrTerminalUnsupported, not "no sandbox". func (m *SessionBoundManager) OpenSessionTerminal( ctx context.Context, @@ -1046,6 +1046,9 @@ func (m *SessionBoundManager) RequireRunningSessionSandbox( return ErrNoLiveSessionSandbox } if state != RemoteStateRunning { + if m.client.Provider() == SandboxTypeDocker { + return ErrSandboxStopped + } return ErrSandboxPaused } return nil diff --git a/internal/sandbox/session_manager_terminal_test.go b/internal/sandbox/session_manager_terminal_test.go index f7619e54..c7a6db38 100644 --- a/internal/sandbox/session_manager_terminal_test.go +++ b/internal/sandbox/session_manager_terminal_test.go @@ -12,11 +12,22 @@ import ( func newSessionManagerTerminalTestHarness(t *testing.T) (*SessionBoundManager, *terminalFakeClient) { t.Helper() + return newSessionManagerTerminalTestHarnessFor(t, SandboxTypeCube) +} - client := &terminalFakeClient{fakeRemoteClient: newFakeRemoteClient(SandboxTypeCube)} +func newSessionManagerTerminalTestHarnessFor( + t *testing.T, provider SandboxType, +) (*SessionBoundManager, *terminalFakeClient) { + t.Helper() + + client := &terminalFakeClient{fakeRemoteClient: newFakeRemoteClient(provider)} client.capabilities.SupportsTerminals = true + // Docker containers sit behind no gateway, so their handles carry no + // inbound token, exactly like the real adapter. + client.omitsInboundTokenCarrier = provider == SandboxTypeDocker cfg := DefaultConfig() cfg.CubeTemplate = "tpl-test" + cfg.DockerImage = "weknora/sandbox:test" mgr, err := NewSessionBoundManager(SessionBoundManagerConfig{ Config: cfg, Client: client, @@ -92,6 +103,48 @@ func TestOpenSessionTerminalRefusesPausedSandboxWithoutResume(t *testing.T) { "lookup-only open must List a paused sandbox instead of Connect, which would resume it") } +// Docker never pauses: a bound container that is not running is stopped (a +// resume restarts it) or already deleted by the idle sweep (a resume replaces +// it). The UI needs to tell the user that, so Docker reports the distinct +// ErrSandboxStopped, still matching ErrSandboxPaused for every other caller. +func TestOpenSessionTerminalDockerNotRunningIsStopped(t *testing.T) { + cases := map[string]func(*testing.T, *fakeRemoteClient){ + "stopped container": func(t *testing.T, c *fakeRemoteClient) { + pauseAllFakeSandboxes(t, c) + }, + "deleted by the sweep (bound but missing from List)": clearAllFakeSandboxMetadata, + } + for name, makeNotRunning := range cases { + t.Run(name, func(t *testing.T) { + ctx := terminalTestContext() + mgr, client := newSessionManagerTerminalTestHarnessFor(t, SandboxTypeDocker) + + _, err := mgr.ExecShellCommand(ctx, "sess-1", "true", "", time.Second, nil) + require.NoError(t, err) + makeNotRunning(t, client.fakeRemoteClient) + + _, err = mgr.OpenSessionTerminal(ctx, "sess-1", RemoteTerminalOptions{}) + require.ErrorIs(t, err, ErrSandboxStopped) + require.ErrorIs(t, err, ErrSandboxPaused, + "callers that only need 'ask before resuming' must keep matching") + }) + } +} + +func TestOpenSessionTerminalPausableBackendIsNotStopped(t *testing.T) { + ctx := terminalTestContext() + mgr, client := newSessionManagerTerminalTestHarness(t) + + _, err := mgr.ExecShellCommand(ctx, "sess-1", "true", "", time.Second, nil) + require.NoError(t, err) + pauseAllFakeSandboxes(t, client.fakeRemoteClient) + + _, err = mgr.OpenSessionTerminal(ctx, "sess-1", RemoteTerminalOptions{}) + require.ErrorIs(t, err, ErrSandboxPaused) + require.NotErrorIs(t, err, ErrSandboxStopped, + "a paused Cube/E2B sandbox really is paused and wakes with its state") +} + func TestOpenSessionTerminalResumesPausedSandboxWhenAllowed(t *testing.T) { ctx := terminalTestContext() mgr, client := newSessionManagerTerminalTestHarness(t) diff --git a/internal/sandbox/terminal.go b/internal/sandbox/terminal.go index 95180342..4bb0bac9 100644 --- a/internal/sandbox/terminal.go +++ b/internal/sandbox/terminal.go @@ -70,6 +70,8 @@ type RemoteTerminalSession interface { Output() <-chan RemoteTerminalEvent // PID is the remote shell's process ID, when the provider exposes one. + // It doubles as the reattach handle: 0 means a reconnect cannot resume + // this shell and the browser must not redial on its own. PID() uint32 // Write feeds raw bytes (keystrokes) into the PTY. @@ -78,9 +80,11 @@ type RemoteTerminalSession interface { // 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 disconnects WeKnora from the PTY. A backend that can re-attach + // (Cube/E2B, via envd) leaves the remote shell running so a reconnect + // resumes it; a backend that cannot (Docker) terminates it, because the + // disconnect would otherwise strand the shell and its jobs. Safe to call + // more than once. Close() error } diff --git a/website-docs/03-features/22-skills-sandbox.md b/website-docs/03-features/22-skills-sandbox.md index 6c660c85..f65e0948 100644 --- a/website-docs/03-features/22-skills-sandbox.md +++ b/website-docs/03-features/22-skills-sandbox.md @@ -129,7 +129,7 @@ Cube/E2B 的 `config.network` 同时用于对话沙箱、技能安装和完整 | 标签页 | 内容 | 可用条件 | | --- | --- | --- | | 产物 | 本轮或全部轮次生成的可下载文件,可按文件名搜索 | 所有远程沙箱 | -| 终端 | 连接本会话沙箱的交互式 Shell(xterm),刷新页面后可重新接上仍在运行的终端 | Cube、E2B;Docker 不支持 | +| 终端 | 连接本会话沙箱的交互式 Shell(xterm)。Cube、E2B 刷新页面后可重新接上仍在运行的终端;Docker 断开即结束 Shell(nohup 启动的后台任务保留),重连会打开新 Shell | Cube、E2B、Docker | | 桌面 | 通过浏览器操作沙箱内的 XFCE 图形桌面,每个会话同时只允许一个连接 | Cube、E2B 的桌面模板,且配置开启 `desktop_enabled` | 打开面板不会创建或唤醒沙箱:沙箱正在运行时终端和桌面会直接连上;沙箱已暂停或尚未创建时,需要点「启动终端」「连接桌面」或「创建并启动」,唤醒或新建的沙箱会按空间配置计费。终端或桌面长时间无操作会自动断开,沙箱随后按提供商 TTL 暂停;断开时间由沙箱配置的「终端 / 桌面空闲断开(秒)」控制,默认 900 秒,范围 60 秒到 24 小时。技能更新触发沙箱重建后,原终端和桌面上未保存的内容会丢失。 diff --git a/website-docs/04-api/02-api-sandbox-skills.md b/website-docs/04-api/02-api-sandbox-skills.md index e718de48..aa7c2b86 100644 --- a/website-docs/04-api/02-api-sandbox-skills.md +++ b/website-docs/04-api/02-api-sandbox-skills.md @@ -191,7 +191,7 @@ WebSocket 握手,不走普通认证中间件: | `cols` / `rows` | 否 | 初始终端尺寸 | | `pty_id` | 否 | 重新接上之前 `ready` 帧返回的 Shell 进程 | -连接后,二进制帧双向传输终端输入输出;文本帧为 JSON 控制消息:服务端发送 `ready`(含 `pty_id`、`backend`)、`exited`(含 `exit_code`)和 `error`,客户端可发送 `{"type":"resize","cols":..,"rows":..}`。错误码包括 `SANDBOX_NOT_BOUND`、`SANDBOX_PAUSED`、`TERMINAL_UNSUPPORTED`、`IDLE_DISCONNECTED`、`AUTH_REVOKED`、`INTERNAL`。每个会话最多同时 5 个终端,超出返回 429。 +连接后,二进制帧双向传输终端输入输出;文本帧为 JSON 控制消息:服务端发送 `ready`(含 `pty_id`、`backend`、`reattachable`)、`exited`(含 `exit_code`)和 `error`,客户端可发送 `{"type":"resize","cols":..,"rows":..}`。`reattachable` 为 `false`(Docker)时没有 `pty_id`,断开即结束 Shell,客户端不应自动重连。错误码包括 `SANDBOX_NOT_BOUND`、`SANDBOX_PAUSED`、`SANDBOX_STOPPED`(不会暂停的 Docker 后端:容器已停止或已被空闲回收)、`TERMINAL_UNSUPPORTED`、`IDLE_DISCONNECTED`、`AUTH_REVOKED`、`INTERNAL`。每个会话最多同时 5 个终端,超出返回 429。 ## Lite 本机项目目录 diff --git a/website-docs/06-development/04-sandbox-deployment.md b/website-docs/06-development/04-sandbox-deployment.md index 9f31a6a5..3470f74c 100644 --- a/website-docs/06-development/04-sandbox-deployment.md +++ b/website-docs/06-development/04-sandbox-deployment.md @@ -69,7 +69,7 @@ Cube guest DNS 属于模板配置。更改 DNS/镜像后需重建模板才会进 ## 交互终端与图形桌面 -对话侧栏的终端和桌面都通过 WebSocket 连接会话沙箱,仅 Cube/E2B 支持,Docker 后端不提供。浏览器不能在 WebSocket 握手里携带认证头,因此都先用已登录的 POST 换取两分钟有效的短期票据,再把票据放在握手 query 中: +对话侧栏的终端和桌面都通过 WebSocket 连接会话沙箱。终端支持 Cube、E2B 和 Docker;桌面仅 Cube/E2B 支持。浏览器不能在 WebSocket 握手里携带认证头,因此都先用已登录的 POST 换取两分钟有效的短期票据,再把票据放在握手 query 中: | 能力 | 取票据 | WebSocket | | --- | --- | --- | @@ -80,6 +80,13 @@ Cube guest DNS 属于模板配置。更改 DNS/镜像后需重建模板才会进 终端和桌面在无操作时按配置的 `terminal_idle_disconnect_sec` 断开(默认 900 秒,最短 60 秒,最长 24 小时),之后沙箱按提供商 TTL 暂停。终端以键盘输入和 PTY 输出计活动,桌面以键鼠计活动。 +Docker 终端是一个 `TTY=true` 的 exec,Engine API 不支持重新附着,因此行为与 Cube/E2B 不同: + +- 终端打开期间会定期刷新空闲回收用的活动标记,容器不会因 `DockerIdleTTL` 被回收;关闭后按 `DockerIdleTTL` 正常回收。 +- 终端断开(关闭面板、空闲断开、网络中断)时,WeKnora 会像关闭终端窗口一样向该 Shell 及其子进程发送 SIGHUP,前台任务随之结束,`nohup` 启动的后台任务保留。 +- 前端不会对 Docker 终端自动重连,用户点「重新连接」会得到一个新 Shell。 +- 沙箱未运行时(容器已停止或已被空闲回收)提示「可能已被回收」,启动后若容器已被删除会新建沙箱,之前的文件不会保留。 + ### 图形桌面 仅 Cube/E2B 桌面模板支持对话侧栏桌面。首次打开时由后端启动桌面进程;配置需选择桌面模板并设置 `desktop_enabled`。技能已安装后不能原地切换底模。