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
+1
View File
@@ -22,6 +22,7 @@ export async function buildApp(options: AppOptions = {}): Promise<FastifyInstanc
await app.register(websocket);
await app.register(workspacePlugin, { config: loadConfig(options.config) });
await app.register(runsPlugin, { config: loadConfig(options.config), hub: options.events ?? new EventsHub() });
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();
},
};
}