feat(server): add persistent terminal and notebook watcher (#5)

Use node-pty for native terminal support and chokidar for recursive cross-platform watching with atomic-save normalization. Validate terminal messages, detach clients safely, and expose debounced typed notebook events.
This commit is contained in:
Florian Schmidt
2026-11-16 00:04:45 +01:00
parent d06f4336ae
commit 7cf1ef82ba
9 changed files with 408 additions and 1 deletions
+3 -1
View File
@@ -12,7 +12,9 @@
"dependencies": {
"@fastify/websocket": "^11.0.1",
"@shellbook/core": "workspace:*",
"fastify": "^5.1.0"
"fastify": "^5.1.0",
"node-pty": "^1.1.0",
"chokidar": "^4.0.3"
},
"devDependencies": {
"tsx": "^4.19.2"
+1
View File
@@ -15,6 +15,7 @@ export interface AppOptions {
export async function buildApp(options: AppOptions = {}): Promise<FastifyInstance> {
const app = Fastify({ logger: options.logger ?? false });
await app.register(websocket);
await app.register((await import("./terminal/index")).terminalPlugin);
app.get("/api/health", async () => ({ ok: true }));
+30
View File
@@ -0,0 +1,30 @@
# Terminal integration
`terminalPlugin` registers `/api/terminal?session=<name>` after `@fastify/websocket`.
Names must match `[a-z0-9-]{1,32}`. Each connection spawns its own
`tmux new-session -A -s shellbook-<name>` attach client. A disconnect kills that
client only; the session and its shell survive. Run `claude` in that shell using
the user's own CLI login. Multiple tabs may attach to the same session.
Options: `workspaceDir`, `extraEnv` (string map, e.g. `ANTHROPIC_BASE_URL`), and
`ptyFactory` for testing or platform adapters. The default workspace is
`SHELLBOOK_WORKSPACE`, falling back to `./workspace`, resolved at registration.
The workspace directory must already exist. Environment values are inherited
and then overridden by `extraEnv`; input and native spawn exceptions are never
logged. tmux keeps the environment of existing sessions: changing environment
configuration does not rewrite an already running shell's environment.
Terminal frames use the core protocol, with raw text output. Invalid/binary
messages close with 1008; input is limited to 64 KiB and dimensions to integer
values 1..1000. Slow output consumers are disconnected at 1 MiB buffered output.
The app's authentication layer must protect WebSocket upgrades too.
## Deployment
Install `tmux` and the real Claude Code CLI separately. The locked node-pty 1.1.0
package ships macOS/Windows prebuilds but **no Linux prebuilds** (verified in its
published package). On Debian 13 x64 / Node 22 install `python3` and
`build-essential` before `pnpm install`; node-pty falls back to `node-gyp rebuild`.
This checkout's installation and fake-PTY tests were run on Windows / Node 22;
the optional real-tmux test runs only when `tmux -V` succeeds. Debian compilation
and a real Claude login still require Linux verification.
+93
View File
@@ -0,0 +1,93 @@
import { createRequire } from "node:module";
import { resolve } from "node:path";
import type { FastifyPluginAsync } from "fastify";
import type { IPty, IPtyForkOptions } from "node-pty";
import type { TerminalClientMessage } from "@shellbook/core";
export type TerminalPty = Pick<IPty, "write" | "resize" | "kill" | "onData" | "onExit">;
export type PtyFactory = (file: string, args: string[], options: IPtyForkOptions) => TerminalPty;
export interface TerminalOptions {
/** Defaults to SHELLBOOK_WORKSPACE, then ./workspace. */
workspaceDir?: string;
extraEnv?: Record<string, string>;
ptyFactory?: PtyFactory;
}
export function isSessionName(value: unknown): value is string {
return typeof value === "string" && /^[a-z0-9-]{1,32}$/.test(value);
}
/** Limits bound PTY resource use and reject non-integral/zero terminal sizes. */
export function parseTerminalMessage(text: string): TerminalClientMessage | undefined {
let value: unknown;
try { value = JSON.parse(text); } catch { return undefined; }
if (!value || typeof value !== "object") return undefined;
const m = value as Record<string, unknown>;
if (m.type === "input" && typeof m.data === "string" && m.data.length <= 64 * 1024) {
return { type: "input", data: m.data };
}
if (m.type === "resize" && Number.isInteger(m.cols) && Number.isInteger(m.rows)
&& (m.cols as number) >= 1 && (m.cols as number) <= 1000
&& (m.rows as number) >= 1 && (m.rows as number) <= 1000) {
return { type: "resize", cols: m.cols as number, rows: m.rows as number };
}
return undefined;
}
const require = createRequire(import.meta.url);
export const nativePtyFactory: PtyFactory = (file, args, options) =>
(require("node-pty") as typeof import("node-pty")).spawn(file, args, options);
/** Each socket owns only a tmux attach client. Never send kill-session to tmux. */
export const terminalPlugin: FastifyPluginAsync<TerminalOptions> = async (app, options) => {
const spawn = options.ptyFactory ?? nativePtyFactory;
const cwd = resolve(options.workspaceDir ?? process.env.SHELLBOOK_WORKSPACE ?? "workspace");
app.get<{ Querystring: { session?: string } }>("/api/terminal", {
websocket: true,
preValidation: async (request, reply) => {
if (!isSessionName(request.query.session)) {
return reply.code(400).send({ error: "Invalid terminal session name" });
}
},
}, (socket, request) => {
let pty: TerminalPty;
try {
pty = spawn("tmux", ["new-session", "-A", "-s", `shellbook-${request.query.session}`], {
name: "xterm-256color", cols: 80, rows: 24, cwd,
env: { ...process.env, ...options.extraEnv },
});
} catch {
// No exception details: native errors may include environment values.
socket.close(1011, "Terminal unavailable");
return;
}
let disposed = false;
const subscriptions: Array<{ dispose(): void }> = [];
const cleanup = (kill: boolean) => {
if (disposed) return;
disposed = true;
for (const subscription of subscriptions) subscription.dispose();
if (kill) { try { pty.kill(); } catch { /* Already exited. */ } }
};
socket.on("close", () => cleanup(true));
socket.on("error", () => { cleanup(true); socket.close(); });
socket.on("message", (data: { toString(): string }, binary: boolean) => {
if (disposed) return;
const message = binary ? undefined : parseTerminalMessage(data.toString());
if (!message) { cleanup(true); socket.close(1008, "Invalid terminal message"); return; }
try {
if (message.type === "input") pty.write(message.data);
else pty.resize(message.cols, message.rows);
} catch { cleanup(true); socket.close(1011, "Terminal unavailable"); }
});
subscriptions.push(pty.onData((data) => {
if (socket.readyState !== 1) return;
// Disconnect slow clients rather than accumulate unbounded terminal output.
if (socket.bufferedAmount > 1024 * 1024) {
cleanup(true); socket.close(1013, "Terminal client too slow"); return;
}
socket.send(data, (error?: Error) => { if (error) { cleanup(true); socket.close(); } });
}));
subscriptions.push(pty.onExit(() => { cleanup(false); socket.close(1000, "Terminal exited"); }));
});
};
+16
View File
@@ -0,0 +1,16 @@
# Notebook event source
`createNotebookWatcher(workspaceDir, { debounceMs?, onError? })` watches
`workspaceDir/notebooks` recursively. Await `ready` before relying on events;
existing files do not trigger an initial reload. `on(listener)` returns an
unsubscribe function. `close()` stops watching and cancels pending notifications.
Errors reject readiness during startup and reach `onError` (stderr by default),
including errors after readiness. Owners should report failures through their logger.
Subscribe the `/api/events` broadcaster to this source; it does not create an
HTTP route itself. Events are the core protocol's `file.changed` and
`file.deleted`, with paths relative to `notebooks/` and forward slashes.
Adds are changes, deletes are deletions, and a per-path debounce (100 ms default)
keeps the most recent event. Non-Markdown files are ignored; symlinks are not followed.
Chokidar 4 provides recursive Linux/Windows watching and normalizes atomic editor
saves, avoiding platform-specific recursion and rename handling with raw fs.watch.
+58
View File
@@ -0,0 +1,58 @@
import { relative, resolve, isAbsolute, sep } from "node:path";
import { watch } from "chokidar";
import type { ServerEvent } from "@shellbook/core";
export type NotebookFileEvent = Extract<ServerEvent, { type: "file.changed" | "file.deleted" }>;
export interface NotebookWatcher {
/** Resolves after the initial scan; existing files do not emit changes. */
ready: Promise<void>;
/** Returns an unsubscribe function. */
on(listener: (event: NotebookFileEvent) => void): () => void;
close(): Promise<void>;
}
/** Watches workspace/notebooks recursively, including newly created directories.
* Chokidar normalizes cross-platform events and editor atomic renames; v4 has no glob dependency.
*/
export function createNotebookWatcher(workspaceDir: string, options: {
debounceMs?: number;
onError?: (error: unknown) => void;
} = {}): NotebookWatcher {
const root = resolve(workspaceDir, "notebooks");
const listeners = new Set<(event: NotebookFileEvent) => void>();
const pending = new Map<string, ReturnType<typeof setTimeout>>();
let closed = false;
const watcher = watch(root, { ignoreInitial: true, followSymlinks: false, atomic: true });
const ready = new Promise<void>((resolveReady, reject) => {
watcher.once("ready", resolveReady);
watcher.on("error", (error) => {
reject(error);
if (options.onError) options.onError(error);
else console.error("Notebook watcher error", error);
});
});
// Callers can await ready; avoid an unhandled rejection before they attach.
void ready.catch(() => {});
const schedule = (type: NotebookFileEvent["type"], file: string) => {
const path = relative(root, file).split(sep).join("/");
if (closed || !path.endsWith(".md") || path.startsWith("../") || isAbsolute(path)) return;
clearTimeout(pending.get(path));
pending.set(path, setTimeout(() => {
pending.delete(path);
for (const listener of listeners) listener({ type, path });
}, options.debounceMs ?? 100));
};
watcher.on("add", (file) => schedule("file.changed", file));
watcher.on("change", (file) => schedule("file.changed", file));
watcher.on("unlink", (file) => schedule("file.deleted", file));
return {
ready,
on(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; },
async close() {
closed = true;
for (const timer of pending.values()) clearTimeout(timer);
pending.clear(); listeners.clear();
await watcher.close();
},
};
}
+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 }); }
});