Improve terminal reconnect handling
This commit is contained in:
@@ -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_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_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_BROWSER_HOST = process.env.PUBLIC_BROWSER_HOST || process.env.PUBLIC_WS_HOST || null
|
||||||
const PUBLIC_BASE_URL = process.env.PUBLIC_BASE_URL || 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 baseProtocol = (forwardedProto && forwardedProto.trim()) || requestUrl.protocol.replace(/:$/, '')
|
||||||
const protocol = baseProtocol === 'https' ? 'wss:' : 'ws:'
|
const protocol = baseProtocol === 'https' ? 'wss:' : 'ws:'
|
||||||
const websocketHost = new URL(`${protocol}//${host}`)
|
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)
|
const websocketUrl = new URL(TERMINAL_WS_PROXY_PATH, websocketHost)
|
||||||
websocketUrl.searchParams.set('sessionId', params.sessionId)
|
websocketUrl.searchParams.set('sessionId', params.sessionId)
|
||||||
websocketUrl.searchParams.set('sandboxId', params.sandboxId)
|
websocketUrl.searchParams.set('sandboxId', params.sandboxId)
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ interface LiveTerminalSession {
|
|||||||
replay?: string
|
replay?: string
|
||||||
websocketUrl: string
|
websocketUrl: string
|
||||||
sshHostAlias?: string
|
sshHostAlias?: string
|
||||||
|
reconnectKey?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
type XTermModule = typeof import('xterm')
|
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 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 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.'
|
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() {
|
function OperatorTerminalInner() {
|
||||||
const searchParams = useSearchParams()
|
const searchParams = useSearchParams()
|
||||||
const sandboxId = searchParams.get('sandboxId')
|
const sandboxId = searchParams.get('sandboxId')
|
||||||
@@ -73,6 +73,7 @@ function OperatorTerminalInner() {
|
|||||||
const [terminalState, setTerminalState] = useState<'idle' | 'connecting' | 'connected' | 'error'>('idle')
|
const [terminalState, setTerminalState] = useState<'idle' | 'connecting' | 'connected' | 'error'>('idle')
|
||||||
const [terminalStatus, setTerminalStatus] = useState<string>('Terminal not connected yet.')
|
const [terminalStatus, setTerminalStatus] = useState<string>('Terminal not connected yet.')
|
||||||
const [liveSession, setLiveSession] = useState<LiveTerminalSession | null>(null)
|
const [liveSession, setLiveSession] = useState<LiveTerminalSession | null>(null)
|
||||||
|
const [terminalReady, setTerminalReady] = useState(false)
|
||||||
const [showRecovery, setShowRecovery] = useState(false)
|
const [showRecovery, setShowRecovery] = useState(false)
|
||||||
|
|
||||||
const terminalContainerRef = useRef<HTMLDivElement | null>(null)
|
const terminalContainerRef = useRef<HTMLDivElement | null>(null)
|
||||||
@@ -81,11 +82,15 @@ function OperatorTerminalInner() {
|
|||||||
const socketRef = useRef<WebSocket | null>(null)
|
const socketRef = useRef<WebSocket | null>(null)
|
||||||
const liveSessionIdRef = useRef<string>('')
|
const liveSessionIdRef = useRef<string>('')
|
||||||
const liveSessionRequestRef = useRef<Promise<void> | null>(null)
|
const liveSessionRequestRef = useRef<Promise<void> | null>(null)
|
||||||
|
const reconnectCounterRef = useRef(0)
|
||||||
|
const resizeObserverRef = useRef<ResizeObserver | null>(null)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setDashboardSessionId(ensureDashboardSessionId(requestedDashboardSessionId))
|
setDashboardSessionId(ensureDashboardSessionId(requestedDashboardSessionId))
|
||||||
}, [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 () => {
|
const refreshReadiness = useCallback(async () => {
|
||||||
if (!sandboxId) {
|
if (!sandboxId) {
|
||||||
setState('idle')
|
setState('idle')
|
||||||
@@ -109,8 +114,14 @@ function OperatorTerminalInner() {
|
|||||||
}
|
}
|
||||||
}, [sandboxId])
|
}, [sandboxId])
|
||||||
|
|
||||||
const ensureLiveSession = useCallback(async () => {
|
const ensureLiveSession = useCallback(async ({ reset = false }: { reset?: boolean } = {}) => {
|
||||||
if (liveSessionRequestRef.current) return liveSessionRequestRef.current
|
if (liveSessionRequestRef.current) return liveSessionRequestRef.current
|
||||||
|
if (reset) {
|
||||||
|
reconnectCounterRef.current += 1
|
||||||
|
liveSessionIdRef.current = ''
|
||||||
|
socketRef.current?.close()
|
||||||
|
socketRef.current = null
|
||||||
|
}
|
||||||
setTerminalState('connecting')
|
setTerminalState('connecting')
|
||||||
setTerminalStatus(sandboxId
|
setTerminalStatus(sandboxId
|
||||||
? `Initializing live terminal session for ${sandboxId}…`
|
? `Initializing live terminal session for ${sandboxId}…`
|
||||||
@@ -134,6 +145,7 @@ function OperatorTerminalInner() {
|
|||||||
replay: result.replay,
|
replay: result.replay,
|
||||||
websocketUrl: result.websocketUrl,
|
websocketUrl: result.websocketUrl,
|
||||||
sshHostAlias: result.sshHostAlias,
|
sshHostAlias: result.sshHostAlias,
|
||||||
|
reconnectKey: String(reconnectCounterRef.current),
|
||||||
})
|
})
|
||||||
})()
|
})()
|
||||||
|
|
||||||
@@ -171,23 +183,32 @@ function OperatorTerminalInner() {
|
|||||||
const fitAddon = new FitAddon()
|
const fitAddon = new FitAddon()
|
||||||
term.loadAddon(fitAddon)
|
term.loadAddon(fitAddon)
|
||||||
term.open(terminalContainerRef.current)
|
term.open(terminalContainerRef.current)
|
||||||
fitAddon.fit()
|
requestAnimationFrame(() => fitAddon.fit())
|
||||||
term.focus()
|
term.focus()
|
||||||
terminalRef.current = term
|
terminalRef.current = term
|
||||||
fitAddonRef.current = fitAddon
|
fitAddonRef.current = fitAddon
|
||||||
|
setTerminalReady(true)
|
||||||
|
|
||||||
const focusTerminal = () => term.focus()
|
const focusTerminal = () => term.focus()
|
||||||
terminalContainerRef.current.addEventListener('click', focusTerminal)
|
terminalContainerRef.current.addEventListener('click', focusTerminal)
|
||||||
|
|
||||||
const handleResize = () => {
|
const handleResize = () => {
|
||||||
|
try {
|
||||||
fitAddon.fit()
|
fitAddon.fit()
|
||||||
|
} catch {
|
||||||
|
return
|
||||||
|
}
|
||||||
if (socketRef.current?.readyState === WebSocket.OPEN) {
|
if (socketRef.current?.readyState === WebSocket.OPEN) {
|
||||||
socketRef.current.send(JSON.stringify({ type: 'resize', cols: term.cols, rows: term.rows }))
|
socketRef.current.send(JSON.stringify({ type: 'resize', cols: term.cols, rows: term.rows }))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
window.addEventListener('resize', handleResize)
|
window.addEventListener('resize', handleResize)
|
||||||
|
resizeObserverRef.current = new ResizeObserver(handleResize)
|
||||||
|
resizeObserverRef.current.observe(terminalContainerRef.current)
|
||||||
cleanupResize = () => {
|
cleanupResize = () => {
|
||||||
window.removeEventListener('resize', handleResize)
|
window.removeEventListener('resize', handleResize)
|
||||||
|
resizeObserverRef.current?.disconnect()
|
||||||
|
resizeObserverRef.current = null
|
||||||
terminalContainerRef.current?.removeEventListener('click', focusTerminal)
|
terminalContainerRef.current?.removeEventListener('click', focusTerminal)
|
||||||
}
|
}
|
||||||
})().catch((error) => {
|
})().catch((error) => {
|
||||||
@@ -202,12 +223,17 @@ function OperatorTerminalInner() {
|
|||||||
terminalRef.current?.dispose()
|
terminalRef.current?.dispose()
|
||||||
terminalRef.current = null
|
terminalRef.current = null
|
||||||
fitAddonRef.current = null
|
fitAddonRef.current = null
|
||||||
|
setTerminalReady(false)
|
||||||
}
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!liveSession?.websocketUrl || !terminalRef.current) return
|
if (!terminalReady || !liveSession?.websocketUrl || !terminalRef.current) return
|
||||||
const term = terminalRef.current
|
const term = terminalRef.current
|
||||||
|
const previousSocket = socketRef.current
|
||||||
|
if (previousSocket && previousSocket.readyState !== WebSocket.CLOSED) {
|
||||||
|
previousSocket.close()
|
||||||
|
}
|
||||||
term.reset()
|
term.reset()
|
||||||
if (liveSession.replay) term.write(liveSession.replay)
|
if (liveSession.replay) term.write(liveSession.replay)
|
||||||
|
|
||||||
@@ -220,7 +246,11 @@ function OperatorTerminalInner() {
|
|||||||
socket.addEventListener('open', () => {
|
socket.addEventListener('open', () => {
|
||||||
setTerminalState('connected')
|
setTerminalState('connected')
|
||||||
setTerminalStatus(`Live terminal connected for ${liveSession.sandboxId}.`)
|
setTerminalStatus(`Live terminal connected for ${liveSession.sandboxId}.`)
|
||||||
|
try {
|
||||||
fitAddonRef.current?.fit()
|
fitAddonRef.current?.fit()
|
||||||
|
} catch {
|
||||||
|
// xterm fit can throw if the tab is backgrounded during initial layout.
|
||||||
|
}
|
||||||
term.focus()
|
term.focus()
|
||||||
socket.send(JSON.stringify({ type: 'resize', cols: term.cols, rows: term.rows }))
|
socket.send(JSON.stringify({ type: 'resize', cols: term.cols, rows: term.rows }))
|
||||||
})
|
})
|
||||||
@@ -243,13 +273,15 @@ function OperatorTerminalInner() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
socket.addEventListener('close', () => {
|
socket.addEventListener('close', () => {
|
||||||
|
if (socketRef.current !== socket) return
|
||||||
setTerminalState((current) => current === 'error' ? current : 'idle')
|
setTerminalState((current) => current === 'error' ? current : 'idle')
|
||||||
setTerminalStatus('Terminal disconnected. Refresh session to reconnect.')
|
setTerminalStatus('Terminal disconnected. Refresh session to reconnect.')
|
||||||
})
|
})
|
||||||
|
|
||||||
socket.addEventListener('error', () => {
|
socket.addEventListener('error', () => {
|
||||||
|
if (socketRef.current !== socket) return
|
||||||
setTerminalState('error')
|
setTerminalState('error')
|
||||||
setTerminalStatus('Terminal websocket error.')
|
setTerminalStatus('Terminal websocket error. Check that the dashboard websocket path is routed in production, then reconnect.')
|
||||||
})
|
})
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
@@ -257,7 +289,7 @@ function OperatorTerminalInner() {
|
|||||||
socket.close()
|
socket.close()
|
||||||
if (socketRef.current === socket) socketRef.current = null
|
if (socketRef.current === socket) socketRef.current = null
|
||||||
}
|
}
|
||||||
}, [liveSession])
|
}, [liveSession, terminalReady])
|
||||||
|
|
||||||
const readiness = useMemo(() => {
|
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.' }
|
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() {
|
|||||||
<div>
|
<div>
|
||||||
<p className="text-[10px] uppercase tracking-[0.25em] text-[var(--foreground-dim)] font-mono">OpenShell Control</p>
|
<p className="text-[10px] uppercase tracking-[0.25em] text-[var(--foreground-dim)] font-mono">OpenShell Control</p>
|
||||||
<h1 className="text-xl font-semibold uppercase tracking-wider mt-2">Operator Terminal</h1>
|
<h1 className="text-xl font-semibold uppercase tracking-wider mt-2">Operator Terminal</h1>
|
||||||
|
<p className="mt-2 max-w-2xl text-xs text-[var(--foreground-dim)]">{terminalDescription}</p>
|
||||||
</div>
|
</div>
|
||||||
<Link href="/" className="px-4 py-2 rounded-sm bg-[var(--background-tertiary)] text-[var(--foreground)] text-xs font-mono uppercase tracking-wider hover:bg-[var(--background-panel)]">Back to Dashboard</Link>
|
<Link href="/" className="px-4 py-2 rounded-sm bg-[var(--background-tertiary)] text-[var(--foreground)] text-xs font-mono uppercase tracking-wider hover:bg-[var(--background-panel)]">Back to Dashboard</Link>
|
||||||
</div>
|
</div>
|
||||||
@@ -310,7 +343,7 @@ function OperatorTerminalInner() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-black p-3"><div ref={terminalContainerRef} className="h-[68vh] min-h-[460px] w-full" /></div>
|
<div className="rounded-sm border border-[var(--border-subtle)] bg-black p-3"><div ref={terminalContainerRef} className="h-[68vh] min-h-[460px] w-full" /></div>
|
||||||
<div className="flex items-center gap-3 flex-wrap">
|
<div className="flex items-center gap-3 flex-wrap">
|
||||||
<button onClick={ensureLiveSession} disabled={terminalState === 'connecting'} className="px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)] disabled:opacity-50 disabled:cursor-not-allowed">{terminalState === 'connecting' ? 'Connecting…' : 'Reconnect Live Terminal'}</button>
|
<button onClick={() => ensureLiveSession({ reset: true })} disabled={terminalState === 'connecting'} className="px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)] disabled:opacity-50 disabled:cursor-not-allowed">{terminalState === 'connecting' ? 'Connecting…' : 'Reconnect Live Terminal'}</button>
|
||||||
<button onClick={refreshReadiness} disabled={!sandboxId} className="px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)] disabled:opacity-50 disabled:cursor-not-allowed">Refresh Readiness</button>
|
<button onClick={refreshReadiness} disabled={!sandboxId} className="px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)] disabled:opacity-50 disabled:cursor-not-allowed">Refresh Readiness</button>
|
||||||
<button onClick={() => setShowRecovery((current) => !current)} className="px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)]">{showRecovery ? 'Hide Recovery' : 'Recovery Commands'}</button>
|
<button onClick={() => setShowRecovery((current) => !current)} className="px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)]">{showRecovery ? 'Hide Recovery' : 'Recovery Commands'}</button>
|
||||||
<span className="text-[11px] text-[var(--foreground-dim)] font-mono">{liveSession?.sessionId ? `session ${liveSession.sessionId.slice(0, 8)}` : 'no session'}</span>
|
<span className="text-[11px] text-[var(--foreground-dim)] font-mono">{liveSession?.sessionId ? `session ${liveSession.sessionId.slice(0, 8)}` : 'no session'}</span>
|
||||||
|
|||||||
Reference in New Issue
Block a user