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
+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();
},
};
}