feat: improve inspector UI for processes and fix PTY terminal

- Simplify ProcessRunTab layout: compact form with collapsible Advanced section for timeout/maxOutputBytes
- Rewrite ProcessesTab: collapsible create form, lightweight list items with status dots, clean detail panel with tabs
- Extract error details: use problem.detail instead of generic "Stream Error" title for better error messages
- Fix GhosttyTerminal binary frame parsing: handle server's binary ArrayBuffer control frames (ready/exit/error)
- Enable WebSocket proxying in Vite dev server with ws: true
- Set TERM=xterm-256color default for TTY processes so tools like tmux, vim, htop work out of the box
- Remove orange gradient background from terminal container for cleaner look
- Remove orange left border from selected process list items
- Update inspector CSS with new process/terminal styles

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
This commit is contained in:
Nathan Flurry 2026-03-06 00:14:55 -08:00
parent c3a95c3611
commit 6dbc871db9
31 changed files with 6881 additions and 207 deletions

View file

@ -1,26 +1,4 @@
# Frontend Instructions
## Inspector Architecture
- Inspector source is `frontend/packages/inspector/`.
- `/ui/` must use ACP over HTTP (`/v2/rpc`) for session/prompt traffic.
- Primary flow:
- `initialize`
- `session/new`
- `session/prompt`
- `session/update` over SSE
- Keep backend/protocol changes in client bindings; avoid unnecessary full UI rewrites.
## Testing
Run inspector checks after transport or chat-flow changes:
```bash
pnpm --filter @sandbox-agent/inspector test
pnpm --filter @sandbox-agent/inspector test:agent-browser
```
## Docs Sync
- Update `docs/inspector.mdx` when `/ui/` behavior changes.
- Update `docs/sdks/typescript.mdx` when inspector SDK bindings or ACP transport behavior changes.
- When the user asks for UI changes, capture screenshots of the updated UI after implementation and verification.
- At the end, offer to open those screenshots for the user and provide absolute filesystem paths to the screenshot files.

View file

@ -2648,6 +2648,402 @@
flex-shrink: 0;
}
/* ── Process form buttons ── */
.process-run-form .button.primary,
.process-create-form .button.primary {
width: auto;
}
.process-detail > .button {
align-self: flex-start;
}
/* ── Run Once tab ── */
.process-run-container {
display: flex;
flex-direction: column;
gap: 16px;
}
.process-run-form {
display: flex;
flex-direction: column;
gap: 10px;
}
.process-run-row {
display: flex;
gap: 10px;
}
.process-run-field {
display: flex;
flex-direction: column;
gap: 4px;
}
.process-run-field-grow {
flex: 1;
min-width: 0;
}
.process-run-field .setup-input {
width: 100%;
}
.process-run-field textarea.setup-input {
resize: vertical;
min-height: 42px;
}
.process-advanced-toggle {
display: inline-flex;
align-items: center;
gap: 4px;
background: none;
border: none;
color: var(--muted);
font-size: 11px;
cursor: pointer;
padding: 2px 0;
align-self: flex-start;
}
.process-advanced-toggle:hover {
color: var(--text-secondary);
}
.process-run-result {
border: 1px solid var(--border);
border-radius: var(--radius);
overflow: hidden;
}
.process-run-result-header {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 12px;
border-bottom: 1px solid var(--border);
background: var(--surface);
}
.process-run-output {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0;
}
.process-run-output-section {
display: flex;
flex-direction: column;
min-width: 0;
}
.process-run-output-section + .process-run-output-section {
border-left: 1px solid var(--border);
}
.process-run-output-label {
padding: 6px 12px;
font-size: 10px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.3px;
color: var(--muted);
border-bottom: 1px solid rgba(255, 255, 255, 0.06);
background: var(--surface-2);
}
.process-run-output-section .process-log-block {
border: none;
border-radius: 0;
min-height: 80px;
}
/* ── Processes tab ── */
.processes-container {
display: flex;
flex-direction: column;
gap: 20px;
}
.processes-section {
display: flex;
flex-direction: column;
gap: 8px;
}
.processes-section-toggle {
display: inline-flex;
align-items: center;
gap: 4px;
background: none;
border: none;
color: var(--text);
font-size: 12px;
font-weight: 600;
cursor: pointer;
padding: 2px 0;
align-self: flex-start;
}
.processes-section-toggle:hover {
color: var(--accent);
}
.processes-section-label {
font-size: 12px;
font-weight: 600;
color: var(--text);
}
.processes-list-header {
display: flex;
align-items: center;
justify-content: space-between;
}
.process-create-form {
display: flex;
flex-direction: column;
gap: 10px;
padding: 12px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
}
.process-checkbox-row {
display: flex;
flex-wrap: wrap;
gap: 14px;
}
.process-checkbox {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 11px;
color: var(--text-secondary);
cursor: pointer;
}
.process-checkbox input {
margin: 0;
}
/* Process list items */
.process-list {
display: flex;
flex-direction: column;
gap: 2px;
}
.process-list-item {
display: flex;
flex-direction: column;
gap: 4px;
padding: 8px 10px;
border-radius: var(--radius-sm);
cursor: pointer;
transition: background var(--transition);
}
.process-list-item:hover {
background: var(--surface);
}
.process-list-item.selected {
background: var(--surface);
}
.process-list-item-main {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
}
.process-status-dot {
width: 6px;
height: 6px;
border-radius: 50%;
flex-shrink: 0;
background: var(--muted);
}
.process-status-dot.running {
background: var(--success);
}
.process-status-dot.exited {
background: var(--muted);
}
.process-list-item-cmd {
font-size: 12px;
color: var(--text);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
min-width: 0;
}
.process-list-item-meta {
display: flex;
align-items: center;
gap: 8px;
font-size: 10px;
color: var(--muted);
padding-left: 14px;
}
.process-list-item-id {
font-family: ui-monospace, SFMono-Regular, 'SF Mono', Consolas, monospace;
opacity: 0.7;
}
.process-list-item-actions {
display: flex;
gap: 4px;
padding-left: 14px;
margin-top: 2px;
}
.process-list-item-actions .button {
padding: 4px 8px;
font-size: 11px;
}
/* Process detail panel */
.process-detail {
padding: 12px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
display: flex;
flex-direction: column;
gap: 10px;
}
.process-detail-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.process-detail-cmd {
font-size: 12px;
color: var(--text);
word-break: break-word;
}
.process-detail-meta {
display: flex;
flex-wrap: wrap;
gap: 6px 14px;
font-size: 11px;
color: var(--muted);
}
.process-detail-logs {
display: flex;
flex-direction: column;
gap: 6px;
}
.process-detail-logs-header {
display: flex;
align-items: center;
justify-content: space-between;
}
.process-detail-logs-header .button {
padding: 4px 8px;
font-size: 11px;
}
/* Terminal (shared) */
.process-terminal-shell {
margin-top: 4px;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 10px;
overflow: hidden;
background: rgba(0, 0, 0, 0.3);
}
.process-terminal-meta {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 8px 12px;
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
background: rgba(0, 0, 0, 0.2);
font-size: 11px;
color: var(--text-secondary);
}
.process-terminal-status {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--muted);
}
.process-terminal-status.ready {
color: var(--success);
}
.process-terminal-status.error {
color: var(--danger);
}
.process-terminal-status.closed {
color: var(--warning);
}
.process-terminal-host {
min-height: 320px;
max-height: 480px;
overflow: hidden;
padding: 10px;
}
.process-terminal-host > div {
width: 100%;
height: 100%;
}
.process-terminal-empty {
margin-top: 4px;
padding: 10px 12px;
border: 1px dashed rgba(255, 255, 255, 0.1);
border-radius: var(--radius-sm);
color: var(--muted);
font-size: 11px;
}
/* Log block (shared) */
.process-log-block {
margin: 0;
min-height: 80px;
max-height: 280px;
overflow: auto;
padding: 10px 12px;
border-radius: var(--radius);
border: 1px solid rgba(255, 255, 255, 0.08);
background: rgba(9, 9, 11, 0.95);
color: #e4e4e7;
font-family: ui-monospace, SFMono-Regular, 'SF Mono', Consolas, monospace;
font-size: 11px;
line-height: 1.55;
white-space: pre-wrap;
word-break: break-word;
}
.pill {
display: inline-flex;
align-items: center;
@ -3026,6 +3422,26 @@
flex-shrink: 0;
}
@media (max-width: 900px) {
.process-run-row {
flex-direction: column;
}
.process-run-output {
grid-template-columns: 1fr;
}
.process-run-output-section + .process-run-output-section {
border-left: none;
border-top: 1px solid var(--border);
}
.process-terminal-meta {
flex-direction: column;
align-items: flex-start;
}
}
/* Scrollbar - match landing page */
* {
scrollbar-width: thin;

View file

@ -23,6 +23,7 @@
},
"dependencies": {
"@sandbox-agent/persist-indexeddb": "workspace:*",
"ghostty-web": "^0.4.0",
"lucide-react": "^0.469.0",
"react": "^18.3.1",
"react-dom": "^18.3.1"

View file

@ -1,15 +1,17 @@
import { ChevronLeft, ChevronRight, Cloud, PlayCircle, Server, Terminal, Wrench } from "lucide-react";
import { ChevronLeft, ChevronRight, Cloud, Play, PlayCircle, Server, Terminal, Wrench } from "lucide-react";
import type { AgentInfo, SandboxAgent, SessionEvent } from "sandbox-agent";
type AgentModeInfo = { id: string; name: string; description: string };
import AgentsTab from "./AgentsTab";
import EventsTab from "./EventsTab";
import McpTab from "./McpTab";
import ProcessesTab from "./ProcessesTab";
import ProcessRunTab from "./ProcessRunTab";
import SkillsTab from "./SkillsTab";
import RequestLogTab from "./RequestLogTab";
import type { RequestLog } from "../../types/requestLog";
export type DebugTab = "log" | "events" | "agents" | "mcp" | "skills";
export type DebugTab = "log" | "events" | "agents" | "mcp" | "skills" | "processes" | "run-process";
const DebugPanel = ({
debugTab,
@ -81,6 +83,14 @@ const DebugPanel = ({
<Server className="button-icon" style={{ marginRight: 4, width: 12, height: 12 }} />
MCP
</button>
<button className={`debug-tab ${debugTab === "processes" ? "active" : ""}`} onClick={() => onDebugTabChange("processes")}>
<Terminal className="button-icon" style={{ marginRight: 4, width: 12, height: 12 }} />
Processes
</button>
<button className={`debug-tab ${debugTab === "run-process" ? "active" : ""}`} onClick={() => onDebugTabChange("run-process")}>
<Play className="button-icon" style={{ marginRight: 4, width: 12, height: 12 }} />
Run Once
</button>
<button className={`debug-tab ${debugTab === "skills" ? "active" : ""}`} onClick={() => onDebugTabChange("skills")}>
<Wrench className="button-icon" style={{ marginRight: 4, width: 12, height: 12 }} />
Skills
@ -122,6 +132,14 @@ const DebugPanel = ({
<McpTab getClient={getClient} />
)}
{debugTab === "processes" && (
<ProcessesTab getClient={getClient} />
)}
{debugTab === "run-process" && (
<ProcessRunTab getClient={getClient} />
)}
{debugTab === "skills" && (
<SkillsTab getClient={getClient} />
)}

View file

@ -0,0 +1,165 @@
import { ChevronDown, ChevronRight, Loader2, Play } from "lucide-react";
import { useState } from "react";
import { SandboxAgentError } from "sandbox-agent";
import type { ProcessRunResponse, SandboxAgent } from "sandbox-agent";
const parseArgs = (value: string): string[] => value.split("\n").map((part) => part.trim()).filter(Boolean);
const ProcessRunTab = ({
getClient,
}: {
getClient: () => SandboxAgent;
}) => {
const [command, setCommand] = useState("");
const [argsText, setArgsText] = useState("");
const [cwd, setCwd] = useState("");
const [timeoutMs, setTimeoutMs] = useState("30000");
const [maxOutputBytes, setMaxOutputBytes] = useState("");
const [showAdvanced, setShowAdvanced] = useState(false);
const [running, setRunning] = useState(false);
const [error, setError] = useState<string | null>(null);
const [result, setResult] = useState<ProcessRunResponse | null>(null);
const handleRun = async () => {
const trimmedCommand = command.trim();
if (!trimmedCommand) {
setError("Command is required.");
return;
}
setRunning(true);
setError(null);
try {
const response = await getClient().runProcess({
command: trimmedCommand,
args: parseArgs(argsText),
cwd: cwd.trim() || undefined,
timeoutMs: timeoutMs.trim() ? Number(timeoutMs) : undefined,
maxOutputBytes: maxOutputBytes.trim() ? Number(maxOutputBytes) : undefined,
});
setResult(response);
} catch (runError) {
const detail = runError instanceof SandboxAgentError ? runError.problem?.detail : undefined;
setError(detail || (runError instanceof Error ? runError.message : "Unable to run process."));
setResult(null);
} finally {
setRunning(false);
}
};
return (
<div className="process-run-container">
<div className="process-run-form">
<div className="process-run-row">
<div className="process-run-field process-run-field-grow">
<label className="label">Command</label>
<input
className="setup-input mono"
value={command}
onChange={(event) => {
setCommand(event.target.value);
setError(null);
}}
placeholder="bash"
/>
</div>
<div className="process-run-field process-run-field-grow">
<label className="label">Working Directory</label>
<input
className="setup-input mono"
value={cwd}
onChange={(event) => {
setCwd(event.target.value);
setError(null);
}}
placeholder="/workspace"
/>
</div>
</div>
<div className="process-run-field">
<label className="label">Arguments</label>
<textarea
className="setup-input mono"
rows={2}
value={argsText}
onChange={(event) => {
setArgsText(event.target.value);
setError(null);
}}
placeholder={"One argument per line, e.g.\n-lc"}
/>
</div>
<button
className="process-advanced-toggle"
onClick={() => setShowAdvanced((prev) => !prev)}
type="button"
>
{showAdvanced ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
Advanced
</button>
{showAdvanced && (
<div className="process-run-row">
<div className="process-run-field process-run-field-grow">
<label className="label">Timeout (ms)</label>
<input
className="setup-input mono"
value={timeoutMs}
onChange={(event) => {
setTimeoutMs(event.target.value);
setError(null);
}}
placeholder="30000"
/>
</div>
<div className="process-run-field process-run-field-grow">
<label className="label">Max Output Bytes</label>
<input
className="setup-input mono"
value={maxOutputBytes}
onChange={(event) => {
setMaxOutputBytes(event.target.value);
setError(null);
}}
placeholder="Default"
/>
</div>
</div>
)}
{error ? <div className="banner error">{error}</div> : null}
<button className="button primary small" onClick={() => void handleRun()} disabled={running} style={{ alignSelf: "flex-start" }}>
{running ? <Loader2 className="button-icon spinner-icon" /> : <Play className="button-icon" />}
{running ? "Running..." : "Run"}
</button>
</div>
{result ? (
<div className="process-run-result">
<div className="process-run-result-header">
<span className={`pill ${result.timedOut ? "warning" : result.exitCode === 0 ? "success" : "danger"}`}>
{result.timedOut ? "Timed Out" : `exit ${result.exitCode ?? "?"}`}
</span>
<span className="card-meta">{result.durationMs}ms</span>
</div>
<div className="process-run-output">
<div className="process-run-output-section">
<div className="process-run-output-label">stdout{result.stdoutTruncated ? " (truncated)" : ""}</div>
<pre className="process-log-block">{result.stdout || "(empty)"}</pre>
</div>
<div className="process-run-output-section">
<div className="process-run-output-label">stderr{result.stderrTruncated ? " (truncated)" : ""}</div>
<pre className="process-log-block">{result.stderr || "(empty)"}</pre>
</div>
</div>
</div>
) : null}
</div>
);
};
export default ProcessRunTab;

View file

@ -0,0 +1,430 @@
import { ChevronDown, ChevronRight, Loader2, Play, RefreshCw, Skull, SquareTerminal, Trash2 } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { SandboxAgentError } from "sandbox-agent";
import type { ProcessInfo, SandboxAgent } from "sandbox-agent";
import GhosttyTerminal from "../processes/GhosttyTerminal";
const extractErrorMessage = (error: unknown, fallback: string): string => {
if (error instanceof SandboxAgentError && error.problem?.detail) return error.problem.detail;
if (error instanceof Error) return error.message;
return fallback;
};
const decodeBase64Utf8 = (value: string): string => {
try {
const bytes = Uint8Array.from(window.atob(value), (char) => char.charCodeAt(0));
return new TextDecoder().decode(bytes);
} catch {
return value;
}
};
const formatDateTime = (value: number | null | undefined): string => {
if (!value) {
return "Unknown";
}
return new Date(value).toLocaleString();
};
const parseArgs = (value: string): string[] => value.split("\n").map((part) => part.trim()).filter(Boolean);
const formatCommandSummary = (process: Pick<ProcessInfo, "command" | "args">): string => {
return [process.command, ...process.args].join(" ").trim();
};
const canOpenTerminal = (process: ProcessInfo | null | undefined): boolean => {
return Boolean(process && process.status === "running" && process.interactive && process.tty);
};
const ProcessesTab = ({
getClient,
}: {
getClient: () => SandboxAgent;
}) => {
const [processes, setProcesses] = useState<ProcessInfo[]>([]);
const [loading, setLoading] = useState(false);
const [refreshing, setRefreshing] = useState(false);
const [error, setError] = useState<string | null>(null);
const [command, setCommand] = useState("");
const [argsText, setArgsText] = useState("");
const [cwd, setCwd] = useState("");
const [interactive, setInteractive] = useState(true);
const [tty, setTty] = useState(true);
const [creating, setCreating] = useState(false);
const [createError, setCreateError] = useState<string | null>(null);
const [showCreateForm, setShowCreateForm] = useState(true);
const [selectedProcessId, setSelectedProcessId] = useState<string | null>(null);
const [logsText, setLogsText] = useState("");
const [logsLoading, setLogsLoading] = useState(false);
const [logsError, setLogsError] = useState<string | null>(null);
const [terminalOpen, setTerminalOpen] = useState(false);
const [actingProcessId, setActingProcessId] = useState<string | null>(null);
const loadProcesses = useCallback(async (mode: "initial" | "refresh" = "initial") => {
if (mode === "initial") {
setLoading(true);
} else {
setRefreshing(true);
}
setError(null);
try {
const response = await getClient().listProcesses();
setProcesses(response.processes);
setSelectedProcessId((current) => {
if (!current) {
return response.processes[0]?.id ?? null;
}
return response.processes.some((listedProcess) => listedProcess.id === current)
? current
: response.processes[0]?.id ?? null;
});
} catch (loadError) {
setError(extractErrorMessage(loadError, "Unable to load processes."));
} finally {
setLoading(false);
setRefreshing(false);
}
}, [getClient]);
const loadSelectedLogs = useCallback(async (process: ProcessInfo | null) => {
if (!process) {
setLogsText("");
setLogsError(null);
return;
}
setLogsLoading(true);
setLogsError(null);
try {
const response = await getClient().getProcessLogs(process.id, {
stream: process.tty ? "pty" : "combined",
tail: 200,
});
const text = response.entries.map((logEntry) => decodeBase64Utf8(logEntry.data)).join("");
setLogsText(text);
} catch (loadError) {
setLogsError(extractErrorMessage(loadError, "Unable to load process logs."));
setLogsText("");
} finally {
setLogsLoading(false);
}
}, [getClient]);
useEffect(() => {
void loadProcesses();
}, [loadProcesses]);
const selectedProcess = useMemo(
() => processes.find((process) => process.id === selectedProcessId) ?? null,
[processes, selectedProcessId]
);
useEffect(() => {
void loadSelectedLogs(selectedProcess);
if (!canOpenTerminal(selectedProcess)) {
setTerminalOpen(false);
}
}, [loadSelectedLogs, selectedProcess]);
const handleCreateProcess = async () => {
const trimmedCommand = command.trim();
if (!trimmedCommand) {
setCreateError("Command is required.");
return;
}
setCreating(true);
setCreateError(null);
try {
const created = await getClient().createProcess({
command: trimmedCommand,
args: parseArgs(argsText),
cwd: cwd.trim() || undefined,
interactive,
tty,
});
await loadProcesses("refresh");
setSelectedProcessId(created.id);
setTerminalOpen(created.interactive && created.tty);
setCommand("");
setArgsText("");
setCwd("");
setInteractive(true);
setTty(true);
} catch (createFailure) {
setCreateError(extractErrorMessage(createFailure, "Unable to create process."));
} finally {
setCreating(false);
}
};
const handleAction = async (processId: string, action: "stop" | "kill" | "delete") => {
setActingProcessId(`${action}:${processId}`);
setError(null);
try {
const client = getClient();
if (action === "stop") {
await client.stopProcess(processId, { waitMs: 2_000 });
} else if (action === "kill") {
await client.killProcess(processId, { waitMs: 2_000 });
} else {
await client.deleteProcess(processId);
}
await loadProcesses("refresh");
} catch (actionError) {
setError(extractErrorMessage(actionError, `Unable to ${action} process.`));
} finally {
setActingProcessId(null);
}
};
return (
<div className="processes-container">
{/* Create form */}
<div className="processes-section">
<button
className="processes-section-toggle"
onClick={() => setShowCreateForm((prev) => !prev)}
type="button"
>
{showCreateForm ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
<span>Create Process</span>
</button>
{showCreateForm && (
<div className="process-create-form">
<div className="process-run-row">
<div className="process-run-field process-run-field-grow">
<label className="label">Command</label>
<input
className="setup-input mono"
value={command}
onChange={(event) => {
setCommand(event.target.value);
setCreateError(null);
}}
placeholder="bash"
/>
</div>
<div className="process-run-field process-run-field-grow">
<label className="label">Working Directory</label>
<input
className="setup-input mono"
value={cwd}
onChange={(event) => {
setCwd(event.target.value);
setCreateError(null);
}}
placeholder="/workspace"
/>
</div>
</div>
<div className="process-run-field">
<label className="label">Arguments</label>
<textarea
className="setup-input mono"
rows={2}
value={argsText}
onChange={(event) => {
setArgsText(event.target.value);
setCreateError(null);
}}
placeholder={"One argument per line"}
/>
</div>
<div className="process-checkbox-row">
<label className="process-checkbox">
<input
type="checkbox"
checked={interactive}
onChange={(event) => {
setInteractive(event.target.checked);
if (!event.target.checked) {
setTty(false);
}
}}
/>
<span>interactive</span>
</label>
<label className="process-checkbox">
<input
type="checkbox"
checked={tty}
onChange={(event) => {
setTty(event.target.checked);
if (event.target.checked) {
setInteractive(true);
}
}}
/>
<span>tty</span>
</label>
</div>
{createError ? <div className="banner error">{createError}</div> : null}
<button className="button primary small" onClick={() => void handleCreateProcess()} disabled={creating} style={{ alignSelf: "flex-start" }}>
{creating ? <Loader2 className="button-icon spinner-icon" /> : <Play className="button-icon" />}
{creating ? "Creating..." : "Create"}
</button>
</div>
)}
</div>
{/* Process list */}
<div className="processes-section">
<div className="processes-list-header">
<span className="processes-section-label">Processes</span>
<button className="button secondary small" onClick={() => void loadProcesses("refresh")} disabled={loading || refreshing}>
<RefreshCw className={`button-icon ${loading || refreshing ? "spinner-icon" : ""}`} size={12} />
Refresh
</button>
</div>
{error ? <div className="banner error">{error}</div> : null}
{loading ? <div className="card-meta">Loading...</div> : null}
{!loading && processes.length === 0 ? <div className="card-meta">No processes yet.</div> : null}
<div className="process-list">
{processes.map((process) => {
const isSelected = selectedProcessId === process.id;
const isStopping = actingProcessId === `stop:${process.id}`;
const isKilling = actingProcessId === `kill:${process.id}`;
const isDeleting = actingProcessId === `delete:${process.id}`;
return (
<div
key={process.id}
className={`process-list-item ${isSelected ? "selected" : ""}`}
onClick={() => {
setSelectedProcessId(process.id);
setTerminalOpen(false);
}}
>
<div className="process-list-item-main">
<span className={`process-status-dot ${process.status}`} />
<span className="process-list-item-cmd mono">{formatCommandSummary(process)}</span>
{process.interactive && process.tty && (
<span className="pill neutral" style={{ fontSize: 9 }}>tty</span>
)}
</div>
<div className="process-list-item-meta">
<span>PID {process.pid ?? "?"}</span>
<span className="process-list-item-id">{process.id.slice(0, 8)}</span>
</div>
<div className="process-list-item-actions">
{canOpenTerminal(process) ? (
<button
className="button secondary small"
onClick={(e) => {
e.stopPropagation();
setSelectedProcessId(process.id);
setTerminalOpen(true);
}}
>
<SquareTerminal className="button-icon" size={12} />
Terminal
</button>
) : null}
{process.status === "running" ? (
<>
<button
className="button secondary small"
onClick={(e) => { e.stopPropagation(); void handleAction(process.id, "stop"); }}
disabled={Boolean(actingProcessId)}
>
{isStopping ? <Loader2 className="button-icon spinner-icon" size={12} /> : null}
Stop
</button>
<button
className="button secondary small"
onClick={(e) => { e.stopPropagation(); void handleAction(process.id, "kill"); }}
disabled={Boolean(actingProcessId)}
>
{isKilling ? <Loader2 className="button-icon spinner-icon" size={12} /> : <Skull className="button-icon" size={12} />}
Kill
</button>
</>
) : null}
{process.status === "exited" ? (
<button
className="button secondary small"
onClick={(e) => { e.stopPropagation(); void handleAction(process.id, "delete"); }}
disabled={Boolean(actingProcessId)}
>
{isDeleting ? <Loader2 className="button-icon spinner-icon" size={12} /> : <Trash2 className="button-icon" size={12} />}
Delete
</button>
) : null}
</div>
</div>
);
})}
</div>
</div>
{/* Selected process detail */}
{selectedProcess ? (
<div className="processes-section">
<div className="processes-section-label">Detail</div>
<div className="process-detail">
<div className="process-detail-header">
<span className="process-detail-cmd mono">{formatCommandSummary(selectedProcess)}</span>
<span className={`pill ${selectedProcess.status === "running" ? "success" : "neutral"}`}>{selectedProcess.status}</span>
</div>
<div className="process-detail-meta">
<span>PID: {selectedProcess.pid ?? "?"}</span>
<span>Created: {formatDateTime(selectedProcess.createdAtMs)}</span>
{selectedProcess.exitedAtMs ? <span>Exited: {formatDateTime(selectedProcess.exitedAtMs)}</span> : null}
{selectedProcess.exitCode != null ? <span>Exit code: {selectedProcess.exitCode}</span> : null}
<span className="mono" style={{ opacity: 0.6 }}>{selectedProcess.id}</span>
</div>
{/* Terminal */}
{terminalOpen && canOpenTerminal(selectedProcess) ? (
<GhosttyTerminal
client={getClient()}
processId={selectedProcess.id}
onExit={() => {
void loadProcesses("refresh");
}}
/>
) : canOpenTerminal(selectedProcess) ? (
<button
className="button secondary small"
onClick={() => setTerminalOpen(true)}
style={{ marginTop: 8 }}
>
<SquareTerminal className="button-icon" size={12} />
Open Terminal
</button>
) : selectedProcess.interactive && selectedProcess.tty ? (
<div className="process-terminal-empty">
Terminal available while process is running.
</div>
) : null}
{/* Logs */}
<div className="process-detail-logs">
<div className="process-detail-logs-header">
<span className="label">Logs</span>
<button className="button secondary small" onClick={() => void loadSelectedLogs(selectedProcess)} disabled={logsLoading}>
{logsLoading ? <Loader2 className="button-icon spinner-icon" size={12} /> : <RefreshCw className="button-icon" size={12} />}
Refresh
</button>
</div>
{logsError ? <div className="banner error">{logsError}</div> : null}
<pre className="process-log-block">{logsText || (logsLoading ? "Loading..." : "(no output)")}</pre>
</div>
</div>
</div>
) : null}
</div>
);
};
export default ProcessesTab;

View file

@ -0,0 +1,263 @@
import { AlertCircle, Loader2, PlugZap, SquareTerminal } from "lucide-react";
import { FitAddon, Terminal, init } from "ghostty-web";
import { useEffect, useRef, useState } from "react";
import type { ProcessTerminalServerFrame, SandboxAgent } from "sandbox-agent";
type ConnectionState = "connecting" | "ready" | "closed" | "error";
const terminalTheme = {
background: "#09090b",
foreground: "#f4f4f5",
cursor: "#f97316",
cursorAccent: "#09090b",
selectionBackground: "#27272a",
black: "#18181b",
red: "#f87171",
green: "#4ade80",
yellow: "#fbbf24",
blue: "#60a5fa",
magenta: "#f472b6",
cyan: "#22d3ee",
white: "#e4e4e7",
brightBlack: "#3f3f46",
brightRed: "#fb7185",
brightGreen: "#86efac",
brightYellow: "#fde047",
brightBlue: "#93c5fd",
brightMagenta: "#f9a8d4",
brightCyan: "#67e8f9",
brightWhite: "#fafafa",
};
const toUint8Array = async (data: Blob | ArrayBuffer): Promise<Uint8Array> => {
if (data instanceof ArrayBuffer) {
return new Uint8Array(data);
}
return new Uint8Array(await data.arrayBuffer());
};
const isServerFrame = (value: unknown): value is ProcessTerminalServerFrame => {
if (!value || typeof value !== "object") {
return false;
}
const type = (value as { type?: unknown }).type;
return type === "ready" || type === "exit" || type === "error";
};
const GhosttyTerminal = ({
client,
processId,
onExit,
}: {
client: SandboxAgent;
processId: string;
onExit?: () => void;
}) => {
const hostRef = useRef<HTMLDivElement | null>(null);
const [connectionState, setConnectionState] = useState<ConnectionState>("connecting");
const [statusMessage, setStatusMessage] = useState("Connecting to PTY...");
const [exitCode, setExitCode] = useState<number | null>(null);
useEffect(() => {
let cancelled = false;
let terminal: Terminal | null = null;
let fitAddon: FitAddon | null = null;
let socket: WebSocket | null = null;
let resizeRaf = 0;
let removeDataListener: { dispose(): void } | null = null;
let removeResizeListener: { dispose(): void } | null = null;
const sendFrame = (payload: unknown) => {
if (!socket || socket.readyState !== WebSocket.OPEN) {
return;
}
socket.send(JSON.stringify(payload));
};
const syncSize = () => {
if (!terminal) {
return;
}
sendFrame({
type: "resize",
cols: terminal.cols,
rows: terminal.rows,
});
};
const connect = async () => {
try {
await init();
if (cancelled || !hostRef.current) {
return;
}
terminal = new Terminal({
allowTransparency: true,
cursorBlink: true,
cursorStyle: "block",
fontFamily: "ui-monospace, SFMono-Regular, SF Mono, Menlo, monospace",
fontSize: 13,
smoothScrollDuration: 90,
theme: terminalTheme,
});
fitAddon = new FitAddon();
terminal.open(hostRef.current);
terminal.loadAddon(fitAddon);
fitAddon.fit();
fitAddon.observeResize();
terminal.focus();
removeDataListener = terminal.onData((data) => {
sendFrame({ type: "input", data });
});
removeResizeListener = terminal.onResize(() => {
if (resizeRaf) {
window.cancelAnimationFrame(resizeRaf);
}
resizeRaf = window.requestAnimationFrame(syncSize);
});
const nextSocket = client.connectProcessTerminalWebSocket(processId);
socket = nextSocket;
nextSocket.binaryType = "arraybuffer";
const tryParseControlFrame = (raw: string | ArrayBuffer | Blob): ProcessTerminalServerFrame | null => {
let text: string | undefined;
if (typeof raw === "string") {
text = raw;
} else if (raw instanceof ArrayBuffer) {
// Server may send JSON control frames as binary; try to decode small messages as JSON.
if (raw.byteLength < 256) {
try {
text = new TextDecoder().decode(raw);
} catch {
// not decodable, treat as terminal data
}
}
}
if (!text) return null;
try {
const parsed = JSON.parse(text);
return isServerFrame(parsed) ? parsed : null;
} catch {
return null;
}
};
const handleControlFrame = (frame: ProcessTerminalServerFrame): void => {
if (frame.type === "ready") {
setConnectionState("ready");
setStatusMessage("Connected");
syncSize();
return;
}
if (frame.type === "exit") {
setConnectionState("closed");
setExitCode(frame.exitCode ?? null);
setStatusMessage(
frame.exitCode == null ? "Process exited." : `Process exited with code ${frame.exitCode}.`
);
onExit?.();
return;
}
if (frame.type === "error") {
setConnectionState("error");
setStatusMessage(frame.message);
}
};
nextSocket.addEventListener("message", (event) => {
if (cancelled || !terminal) {
return;
}
const controlFrame = tryParseControlFrame(event.data);
if (controlFrame) {
handleControlFrame(controlFrame);
return;
}
void toUint8Array(event.data).then((bytes) => {
if (!cancelled && terminal) {
terminal.write(bytes);
}
});
});
nextSocket.addEventListener("close", () => {
if (cancelled) {
return;
}
setConnectionState((current) => (current === "error" ? current : "closed"));
setStatusMessage((current) => (current === "Connected" ? "Terminal disconnected." : current));
});
nextSocket.addEventListener("error", () => {
if (cancelled) {
return;
}
setConnectionState("error");
setStatusMessage("WebSocket connection failed.");
});
} catch (error) {
if (cancelled) {
return;
}
setConnectionState("error");
setStatusMessage(error instanceof Error ? error.message : "Failed to initialize Ghostty terminal.");
}
};
void connect();
return () => {
cancelled = true;
if (resizeRaf) {
window.cancelAnimationFrame(resizeRaf);
}
removeDataListener?.dispose();
removeResizeListener?.dispose();
if (socket?.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify({ type: "close" }));
socket.close();
} else if (socket?.readyState === WebSocket.CONNECTING) {
const pendingSocket = socket;
pendingSocket.addEventListener("open", () => {
pendingSocket.close();
}, { once: true });
}
terminal?.dispose();
};
}, [client, onExit, processId]);
return (
<div className="process-terminal-shell">
<div className="process-terminal-meta">
<div className="inline-row">
<SquareTerminal size={13} />
<span>Ghostty PTY</span>
</div>
<div className={`process-terminal-status ${connectionState}`}>
{connectionState === "connecting" ? <Loader2 size={12} className="spinner-icon" /> : null}
{connectionState === "ready" ? <PlugZap size={12} /> : null}
{connectionState === "error" ? <AlertCircle size={12} /> : null}
<span>{statusMessage}</span>
{exitCode != null ? <span className="mono">exit={exitCode}</span> : null}
</div>
</div>
<div
ref={hostRef}
className="process-terminal-host"
role="presentation"
onClick={() => {
hostRef.current?.querySelector("textarea")?.focus();
}}
/>
</div>
);
};
export default GhosttyTerminal;

View file

@ -10,6 +10,7 @@ export default defineConfig(({ command }) => ({
"/v1": {
target: "http://localhost:2468",
changeOrigin: true,
ws: true,
},
},
},