feat(web): add xterm terminal panel (#5)

Use @xterm/xterm for terminal emulation and its official @xterm/addon-fit for container sizing. Lazy-load both on first open to keep them out of the main bundle. Preserve the mounted terminal on collapse and offer explicit reconnect; provide an echo transport for demos.
This commit is contained in:
Florian Schmidt
2026-11-16 00:21:17 +01:00
parent 08d5441cf2
commit a6429e0527
7 changed files with 336 additions and 9 deletions
+13 -3
View File
@@ -29,7 +29,9 @@ import type { Api } from "./api";
import { emptySession, eventReducer, stepKey } from "./events";
import { ParamsForm } from "./ParamsForm";
import { StepCard } from "./StepCard";
import { TerminalSlot } from "./TerminalSlot";
const TerminalSlot = lazy(() =>
import("./TerminalSlot").then((module) => ({ default: module.TerminalSlot })),
);
const Editor = lazy(() =>
import("./Editor").then((module) => ({ default: module.Editor })),
);
@@ -53,6 +55,7 @@ export function App({ api }: { api: Api }) {
const [values, setValues] = useState<ParamValues>({});
const [edit, setEdit] = useState(false);
const [terminal, setTerminal] = useState(false);
const [terminalOpened, setTerminalOpened] = useState(false);
const [conflict, setConflict] = useState(false);
const [error, setError] = useState("");
const [connected, setConnected] = useState(false);
@@ -348,7 +351,10 @@ export function App({ api }: { api: Api }) {
</button>
<button
aria-expanded={terminal}
onClick={() => setTerminal(!terminal)}
onClick={() => {
setTerminalOpened(true);
setTerminal(!terminal);
}}
>
Terminal {terminal ? "→" : "←"}
</button>
@@ -460,7 +466,11 @@ export function App({ api }: { api: Api }) {
</>
)}
</main>
{terminal && <TerminalSlot />}
{terminalOpened && (
<Suspense fallback={<p>Loading terminal...</p>}>
<TerminalSlot collapsed={!terminal} />
</Suspense>
)}
{confirm && (
<div className="modal-backdrop">
<section
+119 -5
View File
@@ -1,9 +1,123 @@
export function TerminalSlot() {
import { useEffect, useRef, useState } from "react";
import { Terminal } from "@xterm/xterm";
import { FitAddon } from "@xterm/addon-fit";
import "@xterm/xterm/css/xterm.css";
import { terminalTransport } from "./terminalTransport";
import type { TerminalTransport } from "./terminalTransport";
import type { TerminalClientMessage } from "@shellbook/core";
export function TerminalSlot({
collapsed = false,
connect = terminalTransport,
}: {
collapsed?: boolean;
connect?: (session: string) => TerminalTransport;
}) {
const container = useRef<HTMLDivElement>(null);
const refit = useRef<() => void>(() => {});
const [attempt, setAttempt] = useState(0);
const [state, setState] = useState("Connecting");
useEffect(() => {
let active = true;
let ready = false;
setState("Connecting");
const terminal = new Terminal({
cursorBlink: true,
fontSize: 13,
scrollback: 5000,
});
const fit = new FitAddon();
terminal.loadAddon(fit);
terminal.open(container.current!);
const media = window.matchMedia?.("(prefers-color-scheme: light)");
const theme = () => {
terminal.options.theme = media?.matches
? { background: "#ffffff", foreground: "#233244", cursor: "#197b59" }
: { background: "#10151c", foreground: "#dce3ec", cursor: "#86dab9" };
};
theme();
media?.addEventListener("change", theme);
let socket: TerminalTransport;
let timer: ReturnType<typeof setTimeout>;
const send = (message: TerminalClientMessage) => {
if (ready) socket.send(JSON.stringify(message));
};
const resize = () => {
clearTimeout(timer);
timer = setTimeout(() => {
if (!active || !container.current?.getBoundingClientRect().width)
return;
fit.fit();
send({
type: "resize",
cols: Math.min(1000, Math.max(1, terminal.cols)),
rows: Math.min(1000, Math.max(1, terminal.rows)),
});
}, 100);
};
refit.current = resize;
const observer =
typeof ResizeObserver === "undefined"
? undefined
: new ResizeObserver(resize);
observer?.observe(container.current!);
window.addEventListener("resize", resize);
const input = terminal.onData((data) => send({ type: "input", data }));
try {
socket = connect("main");
socket.onopen = () => {
if (active) {
ready = true;
setState("Connected");
resize();
}
};
socket.onmessage = (event) => {
if (active) terminal.write(event.data);
};
const disconnected = () => {
if (active) {
ready = false;
setState("Disconnected");
}
};
socket.onclose = disconnected;
socket.onerror = () => {
disconnected();
socket.close();
};
} catch {
setState("Disconnected");
}
return () => {
active = false;
ready = false;
clearTimeout(timer);
observer?.disconnect();
window.removeEventListener("resize", resize);
media?.removeEventListener("change", theme);
input.dispose();
socket?.close();
terminal.dispose();
};
}, [attempt, connect]);
useEffect(() => {
if (!collapsed) refit.current();
}, [collapsed]);
return (
<aside className="terminal" aria-label="Terminal panel">
<h2>Terminal</h2>
<p>Claude Code terminal · M4</p>
<div className="terminal-slot" />
<aside className="terminal" aria-label="Terminal panel" hidden={collapsed}>
<h2>Terminal · main</h2>
<p>
Run `claude` here — it edits notebooks in this workspace; the view
reloads live.
</p>
<div className="actions">
<span role="status">{state}</span>
{state === "Disconnected" && (
<button onClick={() => setAttempt((n) => n + 1)}>Reconnect</button>
)}
</div>
<div className="terminal-screen" ref={container} />
</aside>
);
}
+25
View File
@@ -439,3 +439,28 @@ a {
min-height: 200px;
}
}
.terminal[hidden] {
display: none;
}
.terminal {
position: sticky;
top: 0;
height: 100vh;
min-width: 0;
}
.terminal-screen {
height: calc(100% - 160px);
min-height: 220px;
}
.with-terminal {
grid-template-columns: 230px minmax(0, 1fr) minmax(300px, 40vw);
}
@media (max-width: 900px) {
.with-terminal {
grid-template-columns: 170px minmax(0, 1fr);
}
.terminal {
position: static;
height: 500px;
}
}
+40
View File
@@ -0,0 +1,40 @@
import type { TerminalClientMessage } from "@shellbook/core";
export interface TerminalTransport {
onopen: (() => void) | null;
onclose: (() => void) | null;
onerror: (() => void) | null;
onmessage: ((event: { data: string }) => void) | null;
send(data: string): void;
close(): void;
}
export function terminalTransport(session: string): TerminalTransport {
if (import.meta.env.VITE_MOCK !== "1")
return new WebSocket(
`${location.protocol === "https:" ? "wss:" : "ws:"}//${location.host}/api/terminal?session=${encodeURIComponent(session)}`,
) as unknown as TerminalTransport;
let closed = false;
const transport: TerminalTransport = {
onopen: null,
onclose: null,
onerror: null,
onmessage: null,
send(data) {
const message = JSON.parse(data) as TerminalClientMessage;
if (!closed && message.type === "input")
transport.onmessage?.({ data: message.data.replace(/\r/g, "\r\n") });
},
close() {
closed = true;
transport.onclose?.();
},
};
queueMicrotask(() => {
if (closed) return;
transport.onopen?.();
transport.onmessage?.({
data: "ShellBook demo terminal (echo only)\r\n$ ",
});
});
return transport;
}
+116
View File
@@ -0,0 +1,116 @@
import {
act,
fireEvent,
render,
screen,
waitFor,
} from "@testing-library/react";
import { afterEach, expect, it, vi } from "vitest";
const xterm = vi.hoisted(() => ({ instances: [] as any[] }));
vi.mock("@xterm/xterm", () => ({
Terminal: class {
cols = 80;
rows = 24;
options = {};
write = vi.fn();
dispose = vi.fn();
input?: (data: string) => void;
constructor() {
xterm.instances.push(this);
}
loadAddon() {}
open() {}
onData(callback: (data: string) => void) {
this.input = callback;
return { dispose: vi.fn() };
}
},
}));
vi.mock("@xterm/addon-fit", () => ({
FitAddon: class {
fit = vi.fn();
},
}));
import { TerminalSlot } from "../TerminalSlot";
class FakeSocket {
static instances: FakeSocket[] = [];
onopen?: () => void;
onclose?: () => void;
onerror?: () => void;
onmessage?: (event: { data: string }) => void;
send = vi.fn();
close = vi.fn();
constructor(public url: string) {
FakeSocket.instances.push(this);
}
}
afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();
FakeSocket.instances = [];
xterm.instances = [];
});
it("frames input and fitted resize, renders raw output and preserves connection when collapsed", async () => {
vi.stubGlobal("WebSocket", FakeSocket);
const { rerender, container } = render(<TerminalSlot />);
const socket = FakeSocket.instances[0]!;
expect(socket.url).toBe(`ws://${location.host}/api/terminal?session=main`);
const element = container.querySelector(".terminal-screen")!;
vi.spyOn(element, "getBoundingClientRect").mockReturnValue({
width: 500,
} as DOMRect);
act(() => socket.onopen?.());
expect(screen.getByRole("status")).toHaveTextContent("Connected");
await waitFor(() =>
expect(socket.send).toHaveBeenCalledWith(
JSON.stringify({ type: "resize", cols: 80, rows: 24 }),
),
);
act(() => xterm.instances[0].input("claude\r"));
expect(socket.send).toHaveBeenCalledWith(
JSON.stringify({ type: "input", data: "claude\r" }),
);
act(() => socket.onmessage?.({ data: "\u001b[31mraw output" }));
expect(xterm.instances[0].write).toHaveBeenCalledWith("\u001b[31mraw output");
rerender(<TerminalSlot collapsed />);
expect(container.querySelector("aside")).toHaveAttribute("hidden");
expect(socket.close).not.toHaveBeenCalled();
act(() => socket.onmessage?.({ data: "still receiving" }));
rerender(<TerminalSlot />);
expect(FakeSocket.instances).toHaveLength(1);
expect(xterm.instances[0].write).toHaveBeenCalledWith("still receiving");
expect(xterm.instances[0].dispose).not.toHaveBeenCalled();
});
it("offers explicit reconnect after close and cleans up the old connection", () => {
vi.stubGlobal("WebSocket", FakeSocket);
const view = render(<TerminalSlot />);
act(() => FakeSocket.instances[0]!.onclose?.());
fireEvent.click(screen.getByRole("button", { name: "Reconnect" }));
expect(FakeSocket.instances).toHaveLength(2);
expect(FakeSocket.instances[0]!.close).toHaveBeenCalledTimes(1);
act(() => FakeSocket.instances[1]!.onopen?.());
expect(screen.getByRole("status")).toHaveTextContent("Connected");
view.unmount();
expect(FakeSocket.instances[1]!.close).toHaveBeenCalledTimes(1);
});
it("uses a fake echo terminal in demo mode without a server", async () => {
vi.stubEnv("VITE_MOCK", "1");
const { terminalTransport } = await import("../terminalTransport");
try {
const socket = terminalTransport("main");
const opened = vi.fn();
const output = vi.fn();
socket.onopen = opened;
socket.onmessage = output;
await Promise.resolve();
expect(opened).toHaveBeenCalledOnce();
socket.send(JSON.stringify({ type: "input", data: "hello\r" }));
expect(output).toHaveBeenLastCalledWith({ data: "hello\r\n" });
socket.close();
socket.send(JSON.stringify({ type: "input", data: "closed" }));
expect(output).toHaveBeenCalledTimes(2);
} finally {
vi.unstubAllEnvs();
}
});