"use client" import Link from 'next/link' import { useSearchParams } from 'next/navigation' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import 'xterm/css/xterm.css' interface ReadinessPodSummary { containers?: string[] images?: string[] runningStatuses?: string[] phase?: string readyCondition?: string } interface ReadinessResponse { ok: boolean sandboxId?: string podExists?: boolean podReady?: boolean sshReachable?: boolean degraded?: boolean attach?: { alias?: string aliasCommand?: string fallbackCommand?: string loginShellCommand?: string shellHint?: string } pod?: ReadinessPodSummary shellProbe?: { ok?: boolean output?: string stderr?: string error?: string } note?: string error?: string } interface LiveTerminalSession { sessionId: string sandboxId: string replay?: string websocketUrl: string } type XTermModule = typeof import('xterm') type FitAddonModule = typeof import('xterm-addon-fit') type XTermInstance = InstanceType type FitAddonInstance = InstanceType type LoadState = 'idle' | 'loading' | 'ready' | 'error' const defaultAlias = (sandboxId: string | null) => `ssh openshell-${sandboxId || 'my-assistant'}` const defaultFallback = (sandboxId: string | null) => `ssh -i ~/.ssh/id_ed25519_openclaw_labmac openshell-${sandboxId || 'my-assistant'}` const defaultLoginShell = (sandboxId: string | null) => `env PATH=/opt/homebrew/bin:$PATH zsh -l -c 'ssh openshell-${sandboxId || 'my-assistant'}'` const DEFAULT_SHELL_HINT = 'If your non-interactive shell misses Homebrew tooling, retry from a login shell or prepend PATH=/opt/homebrew/bin:$PATH before ssh.' export default function OperatorTerminalPage() { const searchParams = useSearchParams() const sandboxId = searchParams.get('sandboxId') const [state, setState] = useState(sandboxId ? 'loading' : 'idle') const [data, setData] = useState(null) const [lastCheckedAt, setLastCheckedAt] = useState(null) const [copyMessage, setCopyMessage] = useState('') const [terminalState, setTerminalState] = useState<'idle' | 'connecting' | 'connected' | 'error'>('idle') const [terminalStatus, setTerminalStatus] = useState('Terminal not connected yet.') const [liveSession, setLiveSession] = useState(null) const terminalContainerRef = useRef(null) const terminalRef = useRef(null) const fitAddonRef = useRef(null) const socketRef = useRef(null) const refreshReadiness = useCallback(async () => { if (!sandboxId) { setState('idle') setData(null) return } setState('loading') setCopyMessage('') try { const response = await fetch(`/api/openshell/terminal/readiness?sandboxId=${encodeURIComponent(sandboxId)}`, { cache: 'no-store', }) const result: ReadinessResponse = await response.json() setData(result) setState(response.ok && result.ok ? 'ready' : 'error') setLastCheckedAt(new Date().toLocaleTimeString()) } catch (error) { setData({ ok: false, error: error instanceof Error ? error.message : 'Failed to inspect sandbox readiness.', }) setState('error') setLastCheckedAt(new Date().toLocaleTimeString()) } }, [sandboxId]) const ensureLiveSession = useCallback(async () => { if (!sandboxId) { setLiveSession(null) setTerminalState('idle') return } setTerminalState('connecting') setTerminalStatus('Initializing live PTY session…') try { const response = await fetch('/api/openshell/terminal/live', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ sandboxId, sessionId: liveSession?.sessionId, }), }) const result = await response.json() if (!response.ok || !result.ok) { throw new Error(result.error || 'Failed to initialize live terminal session.') } setLiveSession({ sessionId: result.sessionId, sandboxId: result.sandboxId, replay: result.replay, websocketUrl: result.websocketUrl, }) } catch (error) { setTerminalState('error') setTerminalStatus(error instanceof Error ? error.message : 'Failed to initialize live terminal session.') } }, [sandboxId, liveSession?.sessionId]) useEffect(() => { refreshReadiness() }, [refreshReadiness]) useEffect(() => { ensureLiveSession() }, [ensureLiveSession]) useEffect(() => { if (!terminalContainerRef.current || terminalRef.current) { return } let disposed = false let cleanupResize: (() => void) | null = null ;(async () => { const [{ Terminal }, { FitAddon }] = await Promise.all([ import('xterm'), import('xterm-addon-fit'), ]) if (disposed || !terminalContainerRef.current) { return } const term = new Terminal({ cursorBlink: true, fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace', fontSize: 13, theme: { background: '#000000', foreground: '#f5f5f5', cursor: '#76b900', }, scrollback: 5000, allowTransparency: false, }) const fitAddon = new FitAddon() term.loadAddon(fitAddon) term.open(terminalContainerRef.current) fitAddon.fit() terminalRef.current = term fitAddonRef.current = fitAddon const handleResize = () => { fitAddon.fit() if (socketRef.current?.readyState === WebSocket.OPEN) { socketRef.current.send(JSON.stringify({ type: 'resize', cols: term.cols, rows: term.rows, })) } } window.addEventListener('resize', handleResize) cleanupResize = () => window.removeEventListener('resize', handleResize) })().catch((error) => { setTerminalState('error') setTerminalStatus(error instanceof Error ? error.message : 'Failed to load terminal renderer.') }) return () => { disposed = true cleanupResize?.() socketRef.current?.close() terminalRef.current?.dispose() terminalRef.current = null fitAddonRef.current = null } }, []) useEffect(() => { if (!liveSession?.websocketUrl || !terminalRef.current) { return } const term = terminalRef.current term.reset() if (liveSession.replay) { term.write(liveSession.replay) } const socket = new WebSocket(liveSession.websocketUrl) socketRef.current = socket const inputDisposable = term.onData((data) => { if (socket.readyState === WebSocket.OPEN) { socket.send(JSON.stringify({ type: 'input', data })) } }) socket.addEventListener('open', () => { setTerminalState('connected') setTerminalStatus(`Live PTY connected for ${liveSession.sandboxId}.`) if (fitAddonRef.current) { fitAddonRef.current.fit() } socket.send(JSON.stringify({ type: 'resize', cols: term.cols, rows: term.rows, })) }) socket.addEventListener('message', (event) => { try { const message = JSON.parse(event.data) if (message.type === 'ready') { if (message.replay) { term.reset() term.write(message.replay) } } else if (message.type === 'data' && typeof message.data === 'string') { term.write(message.data) } else if (message.type === 'exit') { setTerminalState('error') setTerminalStatus(`Terminal exited with code ${message.exitCode ?? 'unknown'}.`) } } catch { // ignore malformed frames } }) socket.addEventListener('close', () => { setTerminalState((current) => current === 'error' ? current : 'idle') setTerminalStatus('Terminal disconnected. Refresh session to reconnect.') }) socket.addEventListener('error', () => { setTerminalState('error') setTerminalStatus('Terminal websocket error.') }) return () => { inputDisposable.dispose() socket.close() if (socketRef.current === socket) { socketRef.current = null } } }, [liveSession]) const readiness = useMemo(() => { if (!sandboxId) { return { tone: 'border-[var(--status-pending)] text-[var(--status-pending)]', label: 'NO SANDBOX SELECTED', detail: 'Return to the dashboard and choose a sandbox before opening Operator Terminal.', } } if (state === 'loading') { return { tone: 'border-[var(--status-pending)] text-[var(--status-pending)]', label: 'CHECKING READINESS', detail: 'Verifying pod metadata and bounded shell reachability so the page can report terminal truth in one pass.', } } if (state === 'ready' && data?.ok && data?.podReady && data?.sshReachable) { return { tone: 'border-[var(--status-running)] text-[var(--status-running)]', label: 'LIVE TERMINAL PATH VERIFIED', detail: 'The backend confirmed pod readiness and shell reachability, and the dashboard is now wired for a live PTY transport.', } } if (state === 'ready' && data?.ok && data?.podExists && data?.degraded) { return { tone: 'border-[var(--status-pending)] text-[var(--status-pending)]', label: 'DEGRADED: POD UP, SHELL UNCONFIRMED', detail: 'The pod exists, but the readiness probe did not fully succeed. The live terminal may still connect, but direct SSH remains the stronger fallback.', } } if (state === 'ready' && data?.ok && data?.podExists) { return { tone: 'border-[var(--status-running)] text-[var(--status-running)]', label: 'READY FOR LIVE TERMINAL', detail: 'Pod metadata is present and the dashboard live terminal can attempt a real PTY session.', } } return { tone: 'border-[var(--status-stopped)] text-[var(--status-stopped)]', label: 'READINESS CHECK FAILED', detail: 'The dashboard could not confirm pod metadata or shell reachability. Use the recovery commands below, then retry.', } }, [sandboxId, state, data]) const copyCommand = useCallback(async (command: string) => { try { await navigator.clipboard.writeText(command) setCopyMessage(`Copied: ${command}`) } catch { setCopyMessage(`Copy failed. Use: ${command}`) } }, []) const aliasCommand = data?.attach?.aliasCommand || defaultAlias(sandboxId) const fallbackCommand = data?.attach?.fallbackCommand || defaultFallback(sandboxId) const loginShellCommand = data?.attach?.loginShellCommand || defaultLoginShell(sandboxId) const shellHint = data?.attach?.shellHint || DEFAULT_SHELL_HINT return (

Operator path

Operator Terminal

Real live terminal surface for the selected sandbox. Browser keys flow into a PTY-backed shell process and output streams back live into the dashboard.

Back to Dashboard

Sandbox

{sandboxId || 'UNSELECTED'}

Status

{readiness.label}

{lastCheckedAt &&

Last checked {lastCheckedAt}

}

{readiness.detail}

Live Dashboard Terminal

xterm-backed live terminal. Supports typed input, streamed output, resize, and session reconnect.

{terminalStatus}
{liveSession?.sessionId ? `session ${liveSession.sessionId.slice(0, 8)}` : 'no session'}

Direct Attach Fallbacks

If the live dashboard terminal is degraded, these remain the authoritative escape hatches.

Preferred attach command

{aliasCommand}

Fallback if alias or agent config is missing

{fallbackCommand}

{shellHint}

Login-shell retry for Homebrew/path issues

{loginShellCommand}
{copyMessage && (
{copyMessage}
)}

Readiness Evidence

Live pod introspection and bounded shell evidence from the backend.

Pod phase / ready

{data?.pod?.phase || 'Unknown'} / {data?.pod?.readyCondition || 'Unknown'}

Containers

{data?.pod?.containers?.length ? data.pod.containers.join(', ') : 'Unavailable'}

Images

{data?.pod?.images?.length ? data.pod.images.join(', ') : 'Unavailable'}

Shell probe

Readiness-side shell evidence.

{data?.shellProbe?.ok ? 'Probe passed' : 'Probe not confirmed'}

Probe stdout

{data?.shellProbe?.output || 'No backend shell output captured yet.'}

Probe stderr / status

{data?.shellProbe?.error || data?.shellProbe?.stderr || data?.note || 'No stderr.'}
) }