import type { Socket } from "bun"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { PtySession } from "../../server/pty/session.ts"; import { GhosttyEngine, GhosttyModule } from "../../shared/ghostty/engine.ts"; /** * Runs a command on a real pseudo-terminal for tests, through server/pty/session.ts: the Rust PTY * host where it is built and passes its check, else the Node sidecar (node-pty in a real Node, never * in Bun). The command is the leader of the pty's session; this process only holds the PTY host. * * Kill guard: every wait ends at the run's deadline, and the deadline ends the run through the PTY * host's own handle (SIGTERM to the host this run started; the host hangs up the command's group and * kills what is left 2 s later). When this test process dies, the host's stdin closes and the host * does the same by itself. Nothing is ever signalled by pid number. * * `runSupervised` puts `supervise.ts` between the host and the entry: it reads the termios before and * after, and it alone signals the entry, through the handle of the child it started. */ export const PTY_DEADLINE_MS = 20_000; const SUPERVISOR = join(import.meta.dir, "supervise.ts"); export interface PtyOptions { command: string[]; /** the whole environment of the PTY host and the command: nothing is inherited */ env: Record; cols?: number; rows?: number; deadlineMs?: number; /** called with each piece of output as it arrives */ onData?: (text: string) => void; } export interface PtyRun { readonly host: "rust" | "node"; /** everything the command wrote to the pty so far, as UTF-8 */ output(): string; /** resolves once the output contains `match`; rejects at the deadline or when the command ended without it */ until(match: string | RegExp, what?: string): Promise; /** types into the pty, as a terminal's keyboard would */ type(text: string): void; resize(cols: number, rows: number): void; /** the PTY host's exit code once every byte was read; null after `stop` or the deadline */ readonly exited: Promise; /** hangs the pty up through the PTY host and waits for the end */ stop(): Promise; } const WASM = join(import.meta.dir, "..", "..", "shared", "ghostty", "ghostty-vt.wasm"); /** The cell grid the output leaves on a terminal of this size, one line a row, trailing blanks cut. */ export async function gridText(output: string, cols: number, rows: number): Promise { const module = new GhosttyModule(new WebAssembly.Instance(new WebAssembly.Module(await Bun.file(WASM).arrayBuffer()), {})); // laid out the way herdr-core lays graphemes out, as the screen's own panes are const engine = new GhosttyEngine(module, cols, rows, { widths: "core", images: false }); try { engine.write(new TextEncoder().encode(output)); const lines: string[] = Array.from({ length: rows }, () => ""); engine.frameAll((y, runs) => { lines[y] = runs.flatMap((run) => run.cells.map((cell) => cell.text)).join("").trimEnd(); }); return `${lines.join("\n")}\n`; } finally { engine.dispose(); } } const live = new Set<() => Promise>(); /** Ends every run still going, through each one's PTY host: for afterAll and a test's signal handlers. */ export async function stopAllPtyRuns(): Promise { await Promise.all([...live].map((stop) => stop())); } export function runOnPty(options: PtyOptions): PtyRun { const [command, ...args] = options.command; if (!command) throw new Error("runOnPty: no command"); const deadlineMs = options.deadlineMs ?? PTY_DEADLINE_MS; let output = ""; let ended = false; let timedOut = false; let code: number | null = null; const wakers = new Set<() => void>(); const wake = () => { for (const waker of [...wakers]) waker(); }; const session = new PtySession({ command, args, cols: options.cols ?? 80, rows: options.rows ?? 24, env: options.env, inheritEnv: false, onData: (data) => { output += data; options.onData?.(data); wake(); }, onExit: (exit) => { code = exit; }, }); const deadline = setTimeout(() => { timedOut = true; session.kill(); wake(); }, deadlineMs); const stop = async () => { session.kill(); await exited; }; const exited = session.exited.then(() => { ended = true; clearTimeout(deadline); live.delete(stop); wake(); return code; }); live.add(stop); return { host: session.host, output: () => output, type: (text) => { session.write(text); }, resize: (cols, rows) => { session.resize(cols, rows); }, exited, stop, until: (match, what) => new Promise((resolve, reject) => { const check = () => { if (typeof match === "string" ? output.includes(match) : match.test(output)) { wakers.delete(check); resolve(); } else if (timedOut || ended) { wakers.delete(check); const why = timedOut ? `the deadline of ${deadlineMs} ms passed` : "the command ended"; reject(new Error(`${why} before ${what ?? JSON.stringify(String(match))}; output: ${JSON.stringify(output.slice(-2000))}`)); } }; wakers.add(check); check(); }), }; } export interface Termios { canonical: boolean; echo: boolean; signals: boolean; /** `stty -a` as printed */ text: string; } export function parseStty(text: string): Termios { const words = new Set(text.split(/[\s;]+/)); return { canonical: words.has("icanon"), echo: words.has("echo"), signals: words.has("isig"), text }; } export interface EntryEnd { /** the entry's exit code; 128 + n when signal n ended it */ code: number; signal: string | null; before: Termios; /** null when the pty was gone and `stty` could not read it */ after: Termios | null; stderr: string; } export type EntrySignal = "SIGTERM" | "SIGINT" | "SIGHUP"; export interface SupervisedRun extends PtyRun { /** the supervisor started the entry */ readonly started: Promise; /** sends `name` to the entry, through the supervisor's handle on it */ signal(name: EntrySignal): void; /** the pty's termios now */ stty(): Promise; readonly ended: Promise; } interface Message { t: string; id?: number; text?: string | null; code?: number; signal?: string | null; before?: string | null; after?: string | null; stderr?: string } /** Runs `entry` on a pty under the supervisor (see the top of this file). */ export function runSupervised(options: Omit & { entry: string[] }): SupervisedRun { const folder = mkdtempSync(join(options.env["TMPDIR"] || tmpdir(), "pty-")); const path = join(folder, "s"); let conn: Socket | null = null; let connected = false; let reported = false; const queued: string[] = []; const send = (message: Record) => { const line = `${JSON.stringify(message)}\n`; if (conn) conn.write(line); else queued.push(line); }; let settleStarted!: { resolve: () => void; reject: (error: Error) => void }; let settleEnded!: { resolve: (end: EntryEnd) => void; reject: (error: Error) => void }; const started = new Promise((resolve, reject) => { settleStarted = { resolve, reject }; }); const ended = new Promise((resolve, reject) => { settleEnded = { resolve, reject }; }); // a run whose caller never asks is not an unhandled rejection started.catch(() => {}); ended.catch(() => {}); const asked = new Map void; reject: (error: Error) => void }>(); let nextId = 0; const fail = (why: string) => { const error = new Error(`${why}; output: ${JSON.stringify(run.output().slice(-2000))}`); settleStarted.reject(error); if (!reported) settleEnded.reject(error); for (const waiter of asked.values()) waiter.reject(error); asked.clear(); }; const handle = (message: Message) => { if (message.t === "started") settleStarted.resolve(); else if (message.t === "stty" && message.id !== undefined) { const waiter = asked.get(message.id); asked.delete(message.id); if (message.text) waiter?.resolve(parseStty(message.text)); else waiter?.reject(new Error("stty could not read the pty")); } else if (message.t === "ended") { reported = true; settleEnded.resolve({ code: message.code!, signal: message.signal ?? null, before: parseStty(message.before ?? ""), after: message.after ? parseStty(message.after) : null, stderr: message.stderr ?? "", }); } }; let buffered = ""; let socketClosed: () => void = () => {}; const closed = new Promise((resolve) => { socketClosed = resolve; }); const server = Bun.listen({ unix: path, socket: { open(socket) { conn = socket; connected = true; for (const line of queued.splice(0)) socket.write(line); }, data(_socket, data) { buffered += data.toString(); for (let at = buffered.indexOf("\n"); at !== -1; at = buffered.indexOf("\n")) { handle(JSON.parse(buffered.slice(0, at)) as Message); buffered = buffered.slice(at + 1); } }, close() { conn = null; // a request still open gets no answer any more, whether or not the end was reported fail(reported ? "the supervisor closed before answering" : "the supervisor ended without reporting the entry's end"); socketClosed(); }, }, }); const run = runOnPty({ ...options, command: [process.execPath, SUPERVISOR, path, ...options.entry] }); void run.exited.then(async () => { if (connected) await closed; else fail("the supervisor never connected"); server.stop(true); rmSync(folder, { recursive: true, force: true }); }); return { ...run, started, ended, signal: (name) => send({ t: "signal", name }), stty: () => new Promise((resolve, reject) => { const id = nextId++; asked.set(id, { resolve, reject }); send({ t: "stty", id }); }), }; }