import { useEffect, useRef, useState } from "react";
import { Terminal } from "@xterm/xterm";
import { FitAddon } from "@xterm/addon-fit";
import "@xterm/xterm/css/xterm.css";
import { host, listen } from "../lib/agent";
import { Button, Pill } from "./ui";
// A terminal inside one of this machine's nodes: xterm in the window, a pty
// on the Rust side running the bundled `zc node shell <node> [container]`.
// The shell is in the node's own container, never on this machine itself.
export function NodeTerminal({ node, title, container, onClose }: { node: string; title: string; container: string | null; onClose: () => void }) {
const box = useRef<HTMLDivElement>(null);
const [state, setState] = useState<"opening" | "open" | "closed" | "error">("opening");
const [message, setMessage] = useState<string | null>(null);
useEffect(() => {
const el = box.current;
if (!el) return;
const css = getComputedStyle(document.documentElement);
const token = (name: string, fallback: string) => {
const v = css.getPropertyValue(name).trim();
return v ? `oklch(${v})` : fallback;
};
const term = new Terminal({
fontFamily: '"IBM Plex Mono", ui-monospace, Menlo, monospace',
fontSize: 12,
cursorBlink: true,
scrollback: 5000,
theme: { background: "#141110", foreground: "#ece7e3", cursor: token("--wine-bright", "#e0577b"), selectionBackground: "#5b2a3a" },
});
const fit = new FitAddon();
term.loadAddon(fit);
term.open(el);
// xterm has no size until its first paint, and none after dispose.
let disposed = false;
const refit = () => {
if (disposed) return;
try {
fit.fit();
} catch {
/* not laid out yet */
}
};
refit();
const raf = requestAnimationFrame(refit);
term.focus();
let id: number | null = null;
const offs: (() => void)[] = [];
listen<{ id: number; data: string }>("terminal-data", (e) => e.id === id && term.write(e.data)).then((f) => (disposed ? f() : offs.push(f)));
listen<{ id: number; code: number | null }>("terminal-exit", (e) => {
if (e.id !== id) return;
id = null;
setState("closed");
setMessage(e.code ? `The shell ended (exit ${e.code}).` : "The shell ended.");
}).then((f) => (disposed ? f() : offs.push(f)));
host.terminalOpen(node, container, term.cols, term.rows).then(
(n) => {
if (disposed) {
host.terminalClose(n).catch(() => {});
return;
}
id = n;
setState("open");
},
(e) => {
setState("error");
setMessage(String((e as { message?: string }).message ?? e));
},
);
const input = term.onData((d) => id !== null && host.terminalWrite(id, d).catch(() => {}));
const resize = term.onResize(({ cols, rows }) => id !== null && host.terminalResize(id, cols, rows).catch(() => {}));
const ro = new ResizeObserver(refit);
ro.observe(el);
return () => {
disposed = true;
cancelAnimationFrame(raf);
ro.disconnect();
input.dispose();
resize.dispose();
offs.forEach((f) => f());
if (id !== null) host.terminalClose(id).catch(() => {});
// After its pending paint: xterm 5.5 throws from a viewport refresh it
// already queued when it is disposed in the same frame.
window.setTimeout(() => term.dispose(), 100);
};
}, [node, container]);
return (
<section className="grid min-w-0 gap-2 rounded-md border border-hairline bg-surface px-3.5 py-3" aria-label={`Terminal in ${title}`}>
<div className="flex flex-wrap items-center justify-between gap-2">
<h5 className="m-0 flex items-center gap-2 text-[12.5px] font-semibold">
Terminal · {title}
{container && <span className="font-mono text-[11px] font-normal text-fg-dim">{container}</span>}
{state === "opening" && <Pill>Opening…</Pill>}
{state === "open" && <Pill tone="ok">Connected</Pill>}
{state === "closed" && <Pill>Closed</Pill>}
{state === "error" && <Pill tone="warn">Couldn't open</Pill>}
</h5>
<Button size="sm" onClick={onClose}>
Close terminal
</Button>
</div>
{message && <span className={"text-[12px] " + (state === "error" ? "text-wine-bright" : "text-fg-dim")}>{message}</span>}
<div ref={box} className="h-[300px] overflow-hidden rounded-sm bg-[#141110] p-2" />
<span className="text-[11.5px] text-fg-dim">This shell runs inside the node's container, with the node's limits. It cannot see your files.</span>
</section>
);
}