Merge branch 't3/server-terminal-watcher'

# Conflicts:
#	apps/server/package.json
#	apps/server/src/app.ts
#	pnpm-lock.yaml
This commit is contained in:
Florian Schmidt
2026-11-16 00:08:35 +01:00
15 changed files with 696 additions and 0 deletions
+129
View File
@@ -0,0 +1,129 @@
import { once } from "node:events";
import { resolve } from "node:path";
import { execFileSync, spawnSync } from "node:child_process";
import Fastify from "fastify";
import websocket from "@fastify/websocket";
import { describe, expect, it, vi } from "vitest";
import { buildApp } from "../src/app";
import { isSessionName, parseTerminalMessage, terminalPlugin, nativePtyFactory, type TerminalPty } from "../src/terminal/index";
function fakePty() {
let output: (text: string) => void = () => {};
let exit: () => void = () => {};
const dataDispose = vi.fn();
const exitDispose = vi.fn();
const pty: TerminalPty = {
write: vi.fn(), resize: vi.fn(), kill: vi.fn(),
onData: (listener) => { output = listener; return { dispose: dataDispose }; },
onExit: (listener) => { exit = () => listener({ exitCode: 0 }); return { dispose: exitDispose }; },
};
return { pty, output: (text: string) => output(text), exit: () => exit(), dataDispose, exitDispose };
}
describe("terminal validation", () => {
it.each(["a", "abc-123", "a".repeat(32)])("accepts session %s", (name) => expect(isSessionName(name)).toBe(true));
it.each([undefined, "", "A", "../x", "x;y", "a_b", "a".repeat(33), ["a"], "a\n"])("rejects session %s", (name) => expect(isSessionName(name)).toBe(false));
it.each([
{ type: "input", data: "echo hello\r" }, { type: "input", data: "" },
{ type: "resize", cols: 120, rows: 40 },
])("accepts %j", (message) => expect(parseTerminalMessage(JSON.stringify(message))).toEqual(message));
it.each(["no", "null", "[]", '{}', '{"type":"input","data":1}',
'{"type":"resize","cols":0,"rows":24}', '{"type":"resize","cols":80.5,"rows":24}',
'{"type":"resize","cols":80,"rows":1001}', '{"type":"resize","cols":"80","rows":24}',
JSON.stringify({ type: "input", data: "a".repeat(65537) }),
])("rejects invalid frame %#", (text) => expect(parseTerminalMessage(text)).toBeUndefined());
});
describe("terminal plugin", () => {
it("is registered by buildApp and rejects invalid sessions", async () => {
const app = await buildApp();
try {
expect(app.hasRoute({ method: "GET", url: "/api/terminal" })).toBe(true);
expect((await app.inject("/api/terminal?session=BAD")).statusCode).toBe(400);
} finally { await app.close(); }
});
it("attaches independent clients, forwards raw output/input/resize, and cleans up only each attach", async () => {
const app = Fastify();
await app.register(websocket);
const first = fakePty(); const second = fakePty();
const factory = vi.fn().mockReturnValueOnce(first.pty).mockReturnValueOnce(second.pty);
await app.register(terminalPlugin, { workspaceDir: ".", extraEnv: { TERMINAL_TEST: "extra" }, ptyFactory: factory });
await app.ready();
const a = await app.injectWS("/api/terminal?session=main");
const b = await app.injectWS("/api/terminal?session=main");
try {
expect(factory).toHaveBeenCalledTimes(2);
expect(factory.mock.calls[0]).toEqual(["tmux", ["new-session", "-A", "-s", "shellbook-main"],
expect.objectContaining({ cwd: resolve("."), env: expect.objectContaining({ ...process.env, TERMINAL_TEST: "extra" }) })]);
a.send(JSON.stringify({ type: "input", data: "claude\r" }));
a.send(JSON.stringify({ type: "resize", cols: 100, rows: 30 }));
await vi.waitFor(() => expect(first.pty.resize).toHaveBeenCalledWith(100, 30));
expect(first.pty.write).toHaveBeenCalledWith("claude\r");
const received = once(a, "message");
first.output("\u001b[32mhello\r\n");
expect((await received)[0].toString()).toBe("\u001b[32mhello\r\n");
// injectWS uses in-memory Duplexify streams whose close handshake does not
// finish like a TCP socket. Terminate the server peer to model a lost tab.
const peers = [...app.websocketServer.clients];
peers[0].terminate();
await vi.waitFor(() => expect(first.pty.kill).toHaveBeenCalledTimes(1));
expect(second.pty.kill).not.toHaveBeenCalled();
expect(first.dataDispose).toHaveBeenCalledOnce();
const closed = once(b, "close"); second.exit(); await closed;
expect(second.pty.kill).not.toHaveBeenCalled();
expect(second.exitDispose).toHaveBeenCalledOnce();
} finally { a.terminate(); b.terminate(); await app.close(); }
});
it.each(["malformed", JSON.stringify({ type: "resize", cols: -1, rows: 30 })])("closes invalid messages without forwarding", async (message) => {
const app = Fastify(); await app.register(websocket);
const fake = fakePty();
await app.register(terminalPlugin, { ptyFactory: () => fake.pty }); await app.ready();
const socket = await app.injectWS("/api/terminal?session=test");
try {
const closed = once(socket, "close"); socket.send(message);
expect((await closed)[0]).toBe(1008);
expect(fake.pty.kill).toHaveBeenCalledOnce();
expect(fake.pty.write).not.toHaveBeenCalled(); expect(fake.pty.resize).not.toHaveBeenCalled();
} finally { socket.terminate(); await app.close(); }
});
it("closes cleanly when spawning fails", async () => {
const app = Fastify(); await app.register(websocket);
await app.register(terminalPlugin, { ptyFactory: () => { throw new Error("missing tmux"); } }); await app.ready();
const socket = await app.injectWS("/api/terminal?session=test");
try { expect((await once(socket, "close"))[0]).toBe(1011); }
finally { socket.terminate(); await app.close(); }
});
it("cleans up the attach client after a real TCP WebSocket close handshake", async () => {
const app = Fastify(); await app.register(websocket);
const fake = fakePty();
await app.register(terminalPlugin, { ptyFactory: () => fake.pty });
const address = await app.listen({ host: "127.0.0.1", port: 0 });
const socket = new WebSocket(address.replace("http:", "ws:") + "/api/terminal?session=tcp");
try {
await new Promise<void>((resolve, reject) => {
socket.addEventListener("open", () => resolve(), { once: true });
socket.addEventListener("error", reject, { once: true });
});
const closed = new Promise<void>((resolve) => socket.addEventListener("close", () => resolve(), { once: true }));
socket.close(); await closed;
await vi.waitFor(() => expect(fake.pty.kill).toHaveBeenCalledOnce());
expect(fake.dataDispose).toHaveBeenCalledOnce();
} finally { socket.close(); await app.close(); }
});
});
const hasTmux = spawnSync("tmux", ["-V"]).status === 0;
it.skipIf(!hasTmux)("real tmux session survives the attach client's exit and reattaches", async () => {
const name = `shellbook-test-${process.pid}-${Date.now()}`;
let pty: TerminalPty | undefined;
try {
pty = nativePtyFactory("tmux", ["new-session", "-A", "-s", name], { cwd: process.cwd(), cols: 80, rows: 24, env: { ...process.env, TERM: "xterm-256color" } });
await vi.waitFor(() => expect(spawnSync("tmux", ["has-session", "-t", name]).status).toBe(0));
pty.kill(); pty = undefined;
expect(spawnSync("tmux", ["has-session", "-t", name]).status).toBe(0);
pty = nativePtyFactory("tmux", ["new-session", "-A", "-s", name], { cols: 80, rows: 24, env: { ...process.env, TERM: "xterm-256color" } });
let output = ""; pty.onData((data) => { output += data; });
pty.write("printf 'shellbook-%s\\n' 'reattached'\r");
await vi.waitFor(() => expect(output).toContain("shellbook-reattached"));
} finally { pty?.kill(); try { execFileSync("tmux", ["kill-session", "-t", name]); } catch { /* Test cleanup only. */ } }
});
+46
View File
@@ -0,0 +1,46 @@
import { mkdtemp, mkdir, writeFile, rm, rename } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect, it, vi } from "vitest";
import { createNotebookWatcher, type NotebookFileEvent } from "../src/watch/index";
it("watches nested Markdown, debounces writes, handles atomic saves/deletes and unsubscribes", async () => {
const dir = await mkdtemp(join(tmpdir(), "shellbook-watch-"));
await mkdir(join(dir, "notebooks", "setup"), { recursive: true });
const file = join(dir, "notebooks", "setup", "test.md");
await writeFile(file, "initial");
const watcher = createNotebookWatcher(dir, { debounceMs: 100 });
const events: NotebookFileEvent[] = [];
const off = watcher.on((event) => events.push(event));
try {
await watcher.ready;
expect(events).toEqual([]);
await writeFile(file, "first"); await writeFile(file, "second");
await vi.waitFor(() => expect(events).toEqual([{ type: "file.changed", path: "setup/test.md" }]));
await writeFile(`${file}.tmp`, "replacement"); await rename(`${file}.tmp`, file);
await vi.waitFor(() => expect(events).toHaveLength(2));
expect(events[1]).toEqual({ type: "file.changed", path: "setup/test.md" });
await rm(file);
await vi.waitFor(() => expect(events[2]).toEqual({ type: "file.deleted", path: "setup/test.md" }));
await mkdir(join(dir, "notebooks", "new"));
await writeFile(join(dir, "notebooks", "new", "added.md"), "new");
await vi.waitFor(() => expect(events[3]).toEqual({ type: "file.changed", path: "new/added.md" }));
await writeFile(join(dir, "notebooks", "ignored.txt"), "ignore");
await writeFile(join(dir, "outside.md"), "ignore");
await new Promise((r) => setTimeout(r, 300)); expect(events).toHaveLength(4);
off(); await writeFile(file, "unsubscribed");
await new Promise((r) => setTimeout(r, 300)); expect(events).toHaveLength(4);
} finally { await watcher.close(); await rm(dir, { recursive: true, force: true }); }
});
it("starts before notebooks exists and cancels pending notifications on close", async () => {
const dir = await mkdtemp(join(tmpdir(), "shellbook-watch-"));
const watcher = createNotebookWatcher(dir, { debounceMs: 500 });
const listener = vi.fn(); watcher.on(listener);
try {
await watcher.ready; await mkdir(join(dir, "notebooks"));
await writeFile(join(dir, "notebooks", "new.md"), "new");
await new Promise((r) => setTimeout(r, 100)); await watcher.close();
await new Promise((r) => setTimeout(r, 600)); expect(listener).not.toHaveBeenCalled();
} finally { await watcher.close(); await rm(dir, { recursive: true, force: true }); }
});