"use client" import Link from 'next/link' import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useSearchParams } from 'next/navigation' import 'xterm/css/xterm.css' import { ensureDashboardSessionId, HYDRATION_SAFE_DASHBOARD_SESSION_ID } from '../lib/dashboardSession' 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 dashboardSessionId: string replay?: string websocketUrl: string sshHostAlias?: 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 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') const requestedDashboardSessionId = searchParams.get('dashboardSessionId') const [dashboardSessionId, setDashboardSessionId] = useState( () => requestedDashboardSessionId?.trim() || HYDRATION_SAFE_DASHBOARD_SESSION_ID ) 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) useEffect(() => { setDashboardSessionId(ensureDashboardSessionId(requestedDashboardSessionId)) }, [requestedDashboardSessionId]) 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 () => { setTerminalState('connecting') setTerminalStatus(sandboxId ? `Initializing live terminal session for ${sandboxId}…` : 'Initializing host-mode live terminal session…') try { const response = await fetch('/api/openshell/terminal/live', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sandboxId, sessionId: liveSession?.sessionId, dashboardSessionId }), }) 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, dashboardSessionId: result.dashboardSessionId || dashboardSessionId, replay: result.replay, websocketUrl: result.websocketUrl, sshHostAlias: result.sshHostAlias, }) } catch (error) { setTerminalState('error') setTerminalStatus(error instanceof Error ? error.message : 'Failed to initialize live terminal session.') } }, [dashboardSessionId, 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() term.focus() terminalRef.current = term fitAddonRef.current = fitAddon const focusTerminal = () => term.focus() terminalContainerRef.current.addEventListener('click', focusTerminal) 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) terminalContainerRef.current?.removeEventListener('click', focusTerminal) } })().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 terminal connected for ${liveSession.sandboxId}.`) fitAddonRef.current?.fit() term.focus() 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' && 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: 'HOST MODE', detail: 'No sandbox query was provided. The dashboard terminal stays in host mode and keeps dashboard-session diagnostics for reconnect behavior.' } if (state === 'loading') return { tone: 'border-[var(--status-pending)] text-[var(--status-pending)]', label: 'CHECKING READINESS', detail: 'Verifying pod metadata and shell reachability.' } 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 wired for a live terminal 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 shell 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

{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.'}

OpenShell operator terminal

Back to Dashboard

Sandbox

{sandboxId || 'HOST'}

Dashboard Session

{dashboardSessionId.slice(0, 8)}

Status

{readiness.label}

{lastCheckedAt &&

Last checked {lastCheckedAt}

}

{readiness.detail}

Live Dashboard Terminal

Browser terminal backed by the dashboard terminal server.

{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}
}
) } export default function OperatorTerminalPage() { return (
Loading operator terminal…
}>
) }