diff --git a/app/api/openshell/terminal/route.ts b/app/api/openshell/terminal/route.ts index e6eec27..186d510 100644 --- a/app/api/openshell/terminal/route.ts +++ b/app/api/openshell/terminal/route.ts @@ -1,56 +1,190 @@ import { NextResponse } from 'next/server' +import { randomUUID } from 'node:crypto' import { DEFAULT_EXEC_TIMEOUT_MS, MAX_COMMAND_LENGTH, runSandboxCommand, validateSandboxId, validateTerminalCommand } from '../../../lib/openshellHost' -export async function GET(request: Request) { - const { searchParams } = new URL(request.url) - const sandboxId = searchParams.get('sandboxId') || 'unknown' +type TranscriptEntry = { + id: string + command: string + stdout: string + stderr: string + exitCode: number + executionMode?: string + ranAt: string +} - return NextResponse.json({ - ok: true, +type TerminalSession = { + sessionId: string + sandboxId: string + createdAt: string + updatedAt: string + cwd?: string + transcript: TranscriptEntry[] +} + +const sessions = new Map() +const MAX_TRANSCRIPT = 100 + +function ensureSession(sessionId: string, sandboxId: string) { + const existing = sessions.get(sessionId) + if (existing) { + if (existing.sandboxId !== sandboxId) { + throw new Error('sessionId does not match sandboxId') + } + return existing + } + + const now = new Date().toISOString() + const created: TerminalSession = { + sessionId, sandboxId, - attached: false, + createdAt: now, + updatedAt: now, + cwd: undefined, + transcript: [], + } + sessions.set(sessionId, created) + return created +} + +function sanitizePromptPath(cwd?: string) { + if (!cwd) return '~' + return cwd +} + +function buildWrappedCommand(command: string, cwd?: string) { + const trimmed = validateTerminalCommand(command) + const cdPrefix = cwd ? `cd ${quoteForSingleQuotedShell(cwd)} >/dev/null 2>&1 || exit 98; ` : '' + const shellBody = `${cdPrefix}${trimmed}; __cmd_exit=$?; printf '\n__OPENCLAW_PWD__=%s\n' "$PWD"; exit $__cmd_exit` + return shellBody +} + +function quoteForSingleQuotedShell(value: string) { + return `'${value.replace(/'/g, `'"'"'`)}'` +} + +function extractPwd(stdout: string) { + const match = stdout.match(/\n__OPENCLAW_PWD__=(.*)\n?$/) + if (!match) { + return { cleanedStdout: stdout.trim(), cwd: undefined } + } + + const cwd = match[1]?.trim() || undefined + const cleanedStdout = stdout.slice(0, match.index).trimEnd() + return { cleanedStdout, cwd } +} + +function serializeSession(session: TerminalSession) { + return { + ok: true, interactive: false, - mode: 'bounded-command-runner', - note: 'Embedded PTY transport is still not live. This route now supports bounded one-shot command execution via POST while interactive terminal attach remains pending.', - suggestedCommand: `openshell sandbox exec ${sandboxId} -- /bin/sh`, + terminalLike: true, + mode: 'session-backed-command-terminal', + session: { + sessionId: session.sessionId, + sandboxId: session.sandboxId, + cwd: session.cwd, + createdAt: session.createdAt, + updatedAt: session.updatedAt, + prompt: `${session.sandboxId}:${sanitizePromptPath(session.cwd)}$`, + transcript: session.transcript, + }, limits: { timeoutMs: DEFAULT_EXEC_TIMEOUT_MS, maxCommandLength: MAX_COMMAND_LENGTH, }, - }) + note: 'Dashboard terminal is session-backed and command-scoped. It preserves transcript and working directory across commands, but it is not a raw PTY stream yet.', + } +} + +export async function GET(request: Request) { + const { searchParams } = new URL(request.url) + const sandboxId = searchParams.get('sandboxId') || '' + const sessionId = searchParams.get('sessionId') || '' + + if (!sandboxId) { + return NextResponse.json({ + ok: false, + interactive: false, + mode: 'session-backed-command-terminal', + error: 'sandboxId is required', + }, { status: 400 }) + } + + try { + const validatedSandboxId = validateSandboxId(sandboxId) + + if (!sessionId) { + const createdSession = ensureSession(randomUUID(), validatedSandboxId) + return NextResponse.json(serializeSession(createdSession)) + } + + const session = sessions.get(sessionId) + if (!session || session.sandboxId !== validatedSandboxId) { + return NextResponse.json({ + ok: false, + interactive: false, + mode: 'session-backed-command-terminal', + error: 'session not found', + }, { status: 404 }) + } + + return NextResponse.json(serializeSession(session)) + } catch (error) { + const message = error instanceof Error ? error.message : 'Failed to inspect terminal session' + const status = message.includes('sandboxId') ? 400 : 500 + return NextResponse.json({ + ok: false, + interactive: false, + mode: 'session-backed-command-terminal', + error: message, + }, { status }) + } } export async function POST(request: Request) { try { const body = await request.json() const sandboxInput = typeof body?.sandboxId === 'string' ? body.sandboxId : '' + const sessionInput = typeof body?.sessionId === 'string' ? body.sessionId : '' const commandInput = typeof body?.command === 'string' ? body.command : '' const sandboxId = validateSandboxId(sandboxInput) const command = validateTerminalCommand(commandInput) - const result = await runSandboxCommand(sandboxId, command) + const sessionId = sessionInput || randomUUID() + const session = ensureSession(sessionId, sandboxId) + + const wrappedCommand = buildWrappedCommand(command, session.cwd) + const result = await runSandboxCommand(sandboxId, wrappedCommand) + const { cleanedStdout, cwd } = extractPwd(result.stdout) + + session.cwd = cwd || session.cwd + session.updatedAt = new Date().toISOString() + session.transcript.push({ + id: randomUUID(), + command, + stdout: cleanedStdout, + stderr: result.stderr.trim(), + exitCode: result.exitCode, + executionMode: result.mode, + ranAt: session.updatedAt, + }) + if (session.transcript.length > MAX_TRANSCRIPT) { + session.transcript.splice(0, session.transcript.length - MAX_TRANSCRIPT) + } const ok = result.exitCode === 0 return NextResponse.json({ + ...serializeSession(session), ok, - sandboxId, - interactive: false, - mode: 'bounded-command-runner', - executionMode: result.mode, command, exitCode: result.exitCode, - stdout: result.stdout.trim(), + executionMode: result.mode, + stdout: cleanedStdout, stderr: result.stderr.trim(), note: ok - ? result.mode === 'shell' - ? 'Bounded sandbox command execution succeeded. Interactive PTY transport is still pending.' - : 'Sandbox reachability fallback succeeded, but command execution still requires a shell-capable image.' - : `Bounded sandbox command exited non-zero (${result.exitCode}). Interactive PTY transport is still pending, but stderr/stdout below reflect the real sandbox response.`, - limits: { - timeoutMs: DEFAULT_EXEC_TIMEOUT_MS, - maxCommandLength: MAX_COMMAND_LENGTH, - }, + ? 'Command completed and terminal session state was updated.' + : `Command exited non-zero (${result.exitCode}); transcript preserved for inspection.`, }, { status: ok ? 200 : 502 }) } catch (error) { const message = error instanceof Error ? error.message : 'Failed to run sandbox command' @@ -58,13 +192,14 @@ export async function POST(request: Request) { || message === 'command is required' || message.includes('sandboxId must be a valid lowercase DNS-style identifier') || message.includes('command exceeds') + || message.includes('sessionId does not match sandboxId') ? 400 : 500 return NextResponse.json({ ok: false, interactive: false, - mode: 'bounded-command-runner', + mode: 'session-backed-command-terminal', error: message, }, { status }) } diff --git a/app/operator-terminal/page.tsx b/app/operator-terminal/page.tsx index ea3ff55..b3033ea 100644 --- a/app/operator-terminal/page.tsx +++ b/app/operator-terminal/page.tsx @@ -37,6 +37,26 @@ interface ReadinessResponse { error?: string } +interface TranscriptEntry { + id: string + command: string + stdout: string + stderr: string + exitCode: number + executionMode?: string + ranAt: string +} + +interface TerminalSessionPayload { + sessionId: string + sandboxId: string + cwd?: string + createdAt: string + updatedAt: string + prompt: string + transcript: TranscriptEntry[] +} + interface CommandRunResponse { ok: boolean command?: string @@ -46,6 +66,7 @@ interface CommandRunResponse { stderr?: string error?: string note?: string + session?: TerminalSessionPayload } type LoadState = 'idle' | 'loading' | 'ready' | 'error' @@ -62,9 +83,11 @@ export default function OperatorTerminalPage() { const [data, setData] = useState(null) const [lastCheckedAt, setLastCheckedAt] = useState(null) const [copyMessage, setCopyMessage] = useState('') - const [commandInput, setCommandInput] = useState('pwd && whoami') + 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 refreshReadiness = useCallback(async () => { if (!sandboxId) { @@ -94,10 +117,43 @@ export default function OperatorTerminalPage() { } }, [sandboxId]) + const ensureTerminalSession = useCallback(async () => { + if (!sandboxId) { + setTerminalSession(null) + setSessionState('idle') + return + } + + setSessionState('loading') + 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 result = await response.json() + + if (!response.ok || !result.ok || !result.session) { + throw new Error(result.error || 'Failed to initialize dashboard terminal session.') + } + + setTerminalSession(result.session) + setSessionState('ready') + } catch (error) { + setSessionState('error') + setTerminalSession(null) + setCommandResult({ ok: false, error: error instanceof Error ? error.message : 'Failed to initialize terminal session.' }) + } + }, [sandboxId, terminalSession?.sessionId]) + useEffect(() => { refreshReadiness() }, [refreshReadiness]) + useEffect(() => { + ensureTerminalSession() + }, [ensureTerminalSession]) + const readiness = useMemo(() => { if (!sandboxId) { return { @@ -119,7 +175,7 @@ export default function OperatorTerminalPage() { return { tone: 'border-[var(--status-running)] text-[var(--status-running)]', label: 'TERMINAL PATH VERIFIED', - detail: 'The dashboard confirmed the pod is ready and a bounded backend shell exec succeeded. Interactive PTY embedding is still not wired up, but this path now proves command execution reachability without requiring a second manual probe.', + detail: 'The backend confirmed pod readiness and shell reachability. The dashboard terminal below is session-backed and preserves transcript plus working directory across commands.', } } @@ -127,15 +183,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. Treat the page as degraded and try the local SSH attach path.', + 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.', } } if (state === 'ready' && data?.ok && data?.podExists) { return { tone: 'border-[var(--status-running)] text-[var(--status-running)]', - label: 'READY FOR LOCAL SSH ATTACH', - detail: 'The dashboard confirmed pod metadata. Use the attach commands below while persistent PTY transport is still pending.', + label: 'READY FOR DASHBOARD TERMINAL', + detail: 'Pod metadata is present and the dashboard terminal session can be used for command-scoped work.', } } @@ -173,11 +229,16 @@ export default function OperatorTerminalPage() { }, 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({ @@ -186,22 +247,23 @@ export default function OperatorTerminalPage() { }) setCommandState('error') } - }, [commandInput, sandboxId]) + }, [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 (
-
+

Operator path

Operator Terminal

-

- Truthful operator render for the current terminal path. This page still does not pretend to host an embedded PTY, but it now checks pod readiness and bounded shell reachability together before telling you how to attach. +

+ 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.

{readiness.detail}

-
+
+
+
+

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. +

+
+
+ {sessionState === 'loading' ? 'Initializing session…' : sessionState === 'ready' ? terminalSession?.prompt : sessionState === 'error' ? 'Session unavailable' : 'Idle'} +
+
+ +
+
+
+ {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()}
+
+ )) + )} +
+
+ +
+