From fc62bd6272e6f6f0c41ed069e281b7fc5370ba57 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 26 Apr 2026 21:36:20 +0000 Subject: [PATCH] Improve terminal reconnect handling --- app/api/openshell/terminal/live/route.ts | 6 ++- app/operator-terminal/page.tsx | 51 +++++++++++++++++++----- 2 files changed, 46 insertions(+), 11 deletions(-) diff --git a/app/api/openshell/terminal/live/route.ts b/app/api/openshell/terminal/live/route.ts index 39aad2a..130d0ec 100644 --- a/app/api/openshell/terminal/live/route.ts +++ b/app/api/openshell/terminal/live/route.ts @@ -4,7 +4,7 @@ import { resolveRuntimeAuthority } from '@/app/lib/runtimeAuthority' const TERMINAL_SERVER_URL = process.env.TERMINAL_SERVER_URL || 'http://127.0.0.1:3011' const TERMINAL_WS_PROXY_PATH = '/api/openshell/terminal/live/ws' -const TERMINAL_WS_PROXY_PORT = process.env.TERMINAL_WS_PROXY_PORT || process.env.OPENCLAW_DASHBOARD_WS_PROXY_PORT || '3001' +const TERMINAL_WS_PROXY_PORT = process.env.TERMINAL_WS_PROXY_PORT || '' const PUBLIC_BROWSER_HOST = process.env.PUBLIC_BROWSER_HOST || process.env.PUBLIC_WS_HOST || null const PUBLIC_BASE_URL = process.env.PUBLIC_BASE_URL || null @@ -77,7 +77,9 @@ function getBrowserWebSocketUrl(request: Request, params: { const baseProtocol = (forwardedProto && forwardedProto.trim()) || requestUrl.protocol.replace(/:$/, '') const protocol = baseProtocol === 'https' ? 'wss:' : 'ws:' const websocketHost = new URL(`${protocol}//${host}`) - websocketHost.port = TERMINAL_WS_PROXY_PORT + if (TERMINAL_WS_PROXY_PORT.trim()) { + websocketHost.port = TERMINAL_WS_PROXY_PORT.trim() + } const websocketUrl = new URL(TERMINAL_WS_PROXY_PATH, websocketHost) websocketUrl.searchParams.set('sessionId', params.sessionId) websocketUrl.searchParams.set('sandboxId', params.sandboxId) diff --git a/app/operator-terminal/page.tsx b/app/operator-terminal/page.tsx index 2dced42..2fb7768 100644 --- a/app/operator-terminal/page.tsx +++ b/app/operator-terminal/page.tsx @@ -46,6 +46,7 @@ interface LiveTerminalSession { replay?: string websocketUrl: string sshHostAlias?: string + reconnectKey?: string } type XTermModule = typeof import('xterm') @@ -58,7 +59,6 @@ const defaultAlias = (sandboxId: string | null) => `ssh openshell-${sandboxId || const defaultFallback = (sandboxId: string | null) => `ssh openshell-${sandboxId || 'my-assistant'}` const defaultLoginShell = (sandboxId: string | null) => `env PATH=$HOME/.local/bin:$PATH bash -l -c 'ssh openshell-${sandboxId || 'my-assistant'}'` const DEFAULT_SHELL_HINT = 'If your non-interactive shell misses local tooling, retry from a login shell or prepend PATH=$HOME/.local/bin:$PATH before ssh.' - function OperatorTerminalInner() { const searchParams = useSearchParams() const sandboxId = searchParams.get('sandboxId') @@ -73,6 +73,7 @@ function OperatorTerminalInner() { const [terminalState, setTerminalState] = useState<'idle' | 'connecting' | 'connected' | 'error'>('idle') const [terminalStatus, setTerminalStatus] = useState('Terminal not connected yet.') const [liveSession, setLiveSession] = useState(null) + const [terminalReady, setTerminalReady] = useState(false) const [showRecovery, setShowRecovery] = useState(false) const terminalContainerRef = useRef(null) @@ -81,11 +82,15 @@ function OperatorTerminalInner() { const socketRef = useRef(null) const liveSessionIdRef = useRef('') const liveSessionRequestRef = useRef | null>(null) + const reconnectCounterRef = useRef(0) + const resizeObserverRef = useRef(null) useEffect(() => { setDashboardSessionId(ensureDashboardSessionId(requestedDashboardSessionId)) }, [requestedDashboardSessionId]) + const terminalDescription = sandboxId ? 'Live operator terminal for the selected sandbox, brokered through the dashboard-owned terminal bridge.' : 'Live operator terminal for host mode, brokered through the dashboard-owned terminal bridge.' + const refreshReadiness = useCallback(async () => { if (!sandboxId) { setState('idle') @@ -109,8 +114,14 @@ function OperatorTerminalInner() { } }, [sandboxId]) - const ensureLiveSession = useCallback(async () => { + const ensureLiveSession = useCallback(async ({ reset = false }: { reset?: boolean } = {}) => { if (liveSessionRequestRef.current) return liveSessionRequestRef.current + if (reset) { + reconnectCounterRef.current += 1 + liveSessionIdRef.current = '' + socketRef.current?.close() + socketRef.current = null + } setTerminalState('connecting') setTerminalStatus(sandboxId ? `Initializing live terminal session for ${sandboxId}…` @@ -134,6 +145,7 @@ function OperatorTerminalInner() { replay: result.replay, websocketUrl: result.websocketUrl, sshHostAlias: result.sshHostAlias, + reconnectKey: String(reconnectCounterRef.current), }) })() @@ -171,23 +183,32 @@ function OperatorTerminalInner() { const fitAddon = new FitAddon() term.loadAddon(fitAddon) term.open(terminalContainerRef.current) - fitAddon.fit() + requestAnimationFrame(() => fitAddon.fit()) term.focus() terminalRef.current = term fitAddonRef.current = fitAddon + setTerminalReady(true) const focusTerminal = () => term.focus() terminalContainerRef.current.addEventListener('click', focusTerminal) const handleResize = () => { - fitAddon.fit() + try { + fitAddon.fit() + } catch { + return + } if (socketRef.current?.readyState === WebSocket.OPEN) { socketRef.current.send(JSON.stringify({ type: 'resize', cols: term.cols, rows: term.rows })) } } window.addEventListener('resize', handleResize) + resizeObserverRef.current = new ResizeObserver(handleResize) + resizeObserverRef.current.observe(terminalContainerRef.current) cleanupResize = () => { window.removeEventListener('resize', handleResize) + resizeObserverRef.current?.disconnect() + resizeObserverRef.current = null terminalContainerRef.current?.removeEventListener('click', focusTerminal) } })().catch((error) => { @@ -202,12 +223,17 @@ function OperatorTerminalInner() { terminalRef.current?.dispose() terminalRef.current = null fitAddonRef.current = null + setTerminalReady(false) } }, []) useEffect(() => { - if (!liveSession?.websocketUrl || !terminalRef.current) return + if (!terminalReady || !liveSession?.websocketUrl || !terminalRef.current) return const term = terminalRef.current + const previousSocket = socketRef.current + if (previousSocket && previousSocket.readyState !== WebSocket.CLOSED) { + previousSocket.close() + } term.reset() if (liveSession.replay) term.write(liveSession.replay) @@ -220,7 +246,11 @@ function OperatorTerminalInner() { socket.addEventListener('open', () => { setTerminalState('connected') setTerminalStatus(`Live terminal connected for ${liveSession.sandboxId}.`) - fitAddonRef.current?.fit() + try { + fitAddonRef.current?.fit() + } catch { + // xterm fit can throw if the tab is backgrounded during initial layout. + } term.focus() socket.send(JSON.stringify({ type: 'resize', cols: term.cols, rows: term.rows })) }) @@ -243,13 +273,15 @@ function OperatorTerminalInner() { }) socket.addEventListener('close', () => { + if (socketRef.current !== socket) return setTerminalState((current) => current === 'error' ? current : 'idle') setTerminalStatus('Terminal disconnected. Refresh session to reconnect.') }) socket.addEventListener('error', () => { + if (socketRef.current !== socket) return setTerminalState('error') - setTerminalStatus('Terminal websocket error.') + setTerminalStatus('Terminal websocket error. Check that the dashboard websocket path is routed in production, then reconnect.') }) return () => { @@ -257,7 +289,7 @@ function OperatorTerminalInner() { socket.close() if (socketRef.current === socket) socketRef.current = null } - }, [liveSession]) + }, [liveSession, terminalReady]) const readiness = useMemo(() => { if (!sandboxId) return { tone: 'border-[var(--status-pending)] text-[var(--status-pending)]', label: 'HOST MODE', detail: 'No sandbox query was provided. The dashboard terminal stays in host mode and keeps dashboard-session diagnostics for reconnect behavior.' } @@ -285,6 +317,7 @@ function OperatorTerminalInner() {

OpenShell Control

Operator Terminal

+

{terminalDescription}

Back to Dashboard @@ -310,7 +343,7 @@ function OperatorTerminalInner() {
- + {liveSession?.sessionId ? `session ${liveSession.sessionId.slice(0, 8)}` : 'no session'}