diff --git a/app/api/openshell/terminal/live/route.ts b/app/api/openshell/terminal/live/route.ts new file mode 100644 index 0000000..9e25bd5 --- /dev/null +++ b/app/api/openshell/terminal/live/route.ts @@ -0,0 +1,39 @@ +import { NextResponse } from 'next/server' + +const TERMINAL_SERVER_URL = process.env.TERMINAL_SERVER_URL || 'http://127.0.0.1:3011' + +export async function POST(request: Request) { + try { + const body = await request.json() + const response = await fetch(`${TERMINAL_SERVER_URL}/session`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + sandboxId: body?.sandboxId, + sessionId: body?.sessionId, + }), + cache: 'no-store', + }) + + const result = await response.json() + if (!response.ok) { + return NextResponse.json({ ok: false, error: result.error || 'Failed to initialize live terminal session.' }, { status: 502 }) + } + + const wsBase = TERMINAL_SERVER_URL.replace(/^http/, 'ws') + return NextResponse.json({ + ok: true, + sessionId: result.sessionId, + sandboxId: result.sandboxId, + replay: result.replay, + websocketUrl: `${wsBase}/ws?sessionId=${encodeURIComponent(result.sessionId)}&sandboxId=${encodeURIComponent(result.sandboxId)}`, + }) + } catch (error) { + return NextResponse.json({ + ok: false, + error: error instanceof Error ? error.message : 'Failed to reach terminal server.', + }, { status: 500 }) + } +} diff --git a/app/operator-terminal/page.tsx b/app/operator-terminal/page.tsx index b3033ea..b1f587f 100644 --- a/app/operator-terminal/page.tsx +++ b/app/operator-terminal/page.tsx @@ -2,7 +2,10 @@ import Link from 'next/link' import { useSearchParams } from 'next/navigation' -import { useCallback, useEffect, useMemo, useState } from 'react' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { Terminal } from 'xterm' +import { FitAddon } from 'xterm-addon-fit' +import 'xterm/css/xterm.css' interface ReadinessPodSummary { containers?: string[] @@ -37,36 +40,11 @@ interface ReadinessResponse { error?: string } -interface TranscriptEntry { - id: string - command: string - stdout: string - stderr: string - exitCode: number - executionMode?: string - ranAt: string -} - -interface TerminalSessionPayload { +interface LiveTerminalSession { sessionId: string sandboxId: string - cwd?: string - createdAt: string - updatedAt: string - prompt: string - transcript: TranscriptEntry[] -} - -interface CommandRunResponse { - ok: boolean - command?: string - executionMode?: string - exitCode?: number - stdout?: string - stderr?: string - error?: string - note?: string - session?: TerminalSessionPayload + replay?: string + websocketUrl: string } type LoadState = 'idle' | 'loading' | 'ready' | 'error' @@ -83,11 +61,14 @@ export default function OperatorTerminalPage() { const [data, setData] = useState(null) const [lastCheckedAt, setLastCheckedAt] = useState(null) const [copyMessage, setCopyMessage] = useState('') - const [commandInput, setCommandInput] = useState('pwd') - const [commandState, setCommandState] = useState<'idle' | 'running' | 'done' | 'error'>('idle') - const [commandResult, setCommandResult] = useState(null) - const [sessionState, setSessionState] = useState<'idle' | 'loading' | 'ready' | 'error'>('idle') - const [terminalSession, setTerminalSession] = useState(null) + 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) { @@ -117,42 +98,168 @@ export default function OperatorTerminalPage() { } }, [sandboxId]) - const ensureTerminalSession = useCallback(async () => { + const ensureLiveSession = useCallback(async () => { if (!sandboxId) { - setTerminalSession(null) - setSessionState('idle') + setLiveSession(null) + setTerminalState('idle') return } - setSessionState('loading') + setTerminalState('connecting') + setTerminalStatus('Initializing live PTY session…') + try { - const currentSessionId = terminalSession?.sessionId - const url = currentSessionId - ? `/api/openshell/terminal?sandboxId=${encodeURIComponent(sandboxId)}&sessionId=${encodeURIComponent(currentSessionId)}` - : `/api/openshell/terminal?sandboxId=${encodeURIComponent(sandboxId)}` - const response = await fetch(url, { cache: 'no-store' }) + 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 || !result.session) { - throw new Error(result.error || 'Failed to initialize dashboard terminal session.') + if (!response.ok || !result.ok) { + throw new Error(result.error || 'Failed to initialize live terminal session.') } - - setTerminalSession(result.session) - setSessionState('ready') + setLiveSession({ + sessionId: result.sessionId, + sandboxId: result.sandboxId, + replay: result.replay, + websocketUrl: result.websocketUrl, + }) } catch (error) { - setSessionState('error') - setTerminalSession(null) - setCommandResult({ ok: false, error: error instanceof Error ? error.message : 'Failed to initialize terminal session.' }) + setTerminalState('error') + setTerminalStatus(error instanceof Error ? error.message : 'Failed to initialize live terminal session.') } - }, [sandboxId, terminalSession?.sessionId]) + }, [sandboxId, liveSession?.sessionId]) useEffect(() => { refreshReadiness() }, [refreshReadiness]) useEffect(() => { - ensureTerminalSession() - }, [ensureTerminalSession]) + ensureLiveSession() + }, [ensureLiveSession]) + + useEffect(() => { + if (!terminalContainerRef.current || terminalRef.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) + + return () => { + window.removeEventListener('resize', handleResize) + socketRef.current?.close() + term.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) { @@ -174,8 +281,8 @@ export default function OperatorTerminalPage() { if (state === 'ready' && data?.ok && data?.podReady && data?.sshReachable) { return { tone: 'border-[var(--status-running)] text-[var(--status-running)]', - label: 'TERMINAL PATH VERIFIED', - detail: 'The backend confirmed pod readiness and shell reachability. The dashboard terminal below is session-backed and preserves transcript plus working directory across commands.', + 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.', } } @@ -183,15 +290,15 @@ export default function OperatorTerminalPage() { return { tone: 'border-[var(--status-pending)] text-[var(--status-pending)]', label: 'DEGRADED: POD UP, SHELL UNCONFIRMED', - detail: 'The pod exists, but the bounded shell probe did not succeed from the dashboard backend. You can still inspect the terminal panel below, but local SSH remains the stronger recovery path.', + 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 DASHBOARD TERMINAL', - detail: 'Pod metadata is present and the dashboard terminal session can be used for command-scoped work.', + label: 'READY FOR LIVE TERMINAL', + detail: 'Pod metadata is present and the dashboard live terminal can attempt a real PTY session.', } } @@ -211,49 +318,10 @@ export default function OperatorTerminalPage() { } }, []) - const runCommand = useCallback(async () => { - if (!sandboxId) { - setCommandState('error') - setCommandResult({ ok: false, error: 'Select a sandbox before running a command.' }) - return - } - - setCommandState('running') - setCommandResult(null) - - try { - const response = await fetch('/api/openshell/terminal', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - sandboxId, - sessionId: terminalSession?.sessionId, - command: commandInput, - }), - }) - const result: CommandRunResponse = await response.json() - setCommandResult(result) - if (result.session) { - setTerminalSession(result.session) - setSessionState('ready') - } - setCommandState(response.ok && result.ok ? 'done' : 'error') - } catch (error) { - setCommandResult({ - ok: false, - error: error instanceof Error ? error.message : 'Failed to run dashboard command.', - }) - setCommandState('error') - } - }, [commandInput, sandboxId, terminalSession?.sessionId]) - 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 - const transcript = terminalSession?.transcript || [] return (
@@ -263,7 +331,7 @@ export default function OperatorTerminalPage() {

Operator path

Operator Terminal

- Dashboard terminal for the selected sandbox. This is not pretending to be a raw PTY: it is a session-backed shell view that keeps working directory and transcript across commands so you can actually use the dashboard as a terminal surface. + 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.

-

Dashboard Terminal

+

Live Dashboard Terminal

- Session-backed shell surface. Each command runs through the backend against the sandbox, and the page keeps transcript plus cwd so the experience behaves like a terminal instead of isolated one-shot boxes. + xterm-backed live terminal. Supports typed input, streamed output, resize, and session reconnect.

-
- {sessionState === 'loading' ? 'Initializing session…' : sessionState === 'ready' ? terminalSession?.prompt : sessionState === 'error' ? 'Session unavailable' : 'Idle'} -
+
{terminalStatus}
-
-
-
- {terminalSession?.prompt || `${sandboxId || 'sandbox'}:~$`} -
-
- {terminalSession?.sessionId ? `session ${terminalSession.sessionId.slice(0, 8)}` : 'no session'} -
-
- -
- {transcript.length === 0 ? ( -
No terminal transcript yet. Run a command below to start the session.
- ) : ( - transcript.map((entry) => ( -
-
{terminalSession?.prompt || `${sandboxId || 'sandbox'}:~$`} {entry.command}
-
{entry.stdout || ''}
- {entry.stderr && ( -
{entry.stderr}
- )} -
exit {entry.exitCode}{entry.executionMode ? ` · ${entry.executionMode}` : ''} · {new Date(entry.ranAt).toLocaleTimeString()}
-
- )) - )} -
+
+
-
-