feat: refine process API — WebSocket binary protocol, SDK terminal session, updated tests

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Nathan Flurry 2026-03-06 12:12:24 -08:00
parent 6c91323ca6
commit 636eefb553
11 changed files with 700 additions and 512 deletions

View file

@ -1,7 +1,7 @@
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";
import type { SandboxAgent } from "sandbox-agent";
type ConnectionState = "connecting" | "ready" | "closed" | "error";
@ -29,21 +29,6 @@ const terminalTheme = {
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,
@ -62,24 +47,16 @@ const GhosttyTerminal = ({
let cancelled = false;
let terminal: Terminal | null = null;
let fitAddon: FitAddon | null = null;
let socket: WebSocket | null = null;
let session: ReturnType<SandboxAgent["connectProcessTerminal"]> | 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) {
if (!terminal || !session) {
return;
}
sendFrame({
type: "resize",
session.resize({
cols: terminal.cols,
rows: terminal.rows,
});
@ -110,7 +87,7 @@ const GhosttyTerminal = ({
terminal.focus();
removeDataListener = terminal.onData((data) => {
sendFrame({ type: "input", data });
session?.sendInput(data);
});
removeResizeListener = terminal.onResize(() => {
@ -120,38 +97,29 @@ const GhosttyTerminal = ({
resizeRaf = window.requestAnimationFrame(syncSize);
});
const nextSocket = client.connectProcessTerminalWebSocket(processId);
socket = nextSocket;
nextSocket.binaryType = "arraybuffer";
const nextSession = client.connectProcessTerminal(processId);
session = nextSession;
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
}
}
nextSession.onReady((frame) => {
if (cancelled) {
return;
}
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();
}
});
nextSession.onData((bytes) => {
if (cancelled || !terminal) {
return;
}
terminal.write(bytes);
});
nextSession.onExit((frame) => {
if (cancelled) {
return;
}
if (frame.type === "exit") {
@ -161,47 +129,24 @@ const GhosttyTerminal = ({
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", () => {
nextSession.onError((error) => {
if (cancelled) {
return;
}
setConnectionState("error");
setStatusMessage(error instanceof Error ? error.message : error.message);
});
nextSession.onClose(() => {
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;
@ -220,15 +165,7 @@ const GhosttyTerminal = ({
}
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 });
}
session?.close();
terminal?.dispose();
};
}, [client, onExit, processId]);