Skip to content

Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.

feat(viz): local http server with SSE live reload

Shrish Dwivedif98481a2014e
diff --git a/src/viz/serve.ts b/src/viz/serve.ts
new file mode 100644
index 00000000..2a8a1e15
--- /dev/null
+++ b/src/viz/serve.ts
@@ -0,0 +1,148 @@
+/**
+ * The `graft viz` local server. Zero runtime dependencies: node:http serves
+ * the prebuilt viewer bundle, two JSON endpoints, and an SSE channel that
+ * pings the browser whenever the context dir changes on disk.
+ *
+ * GET / viewer (index.html, app.js, style.css from viewerDir)
+ * GET /api/context-graph assembled from .context/*.md on every request
+ * GET /api/code-graph .context/graph.json passthrough (404 until generated)
+ * GET /events SSE; fs.watch on the context dir, debounced 300ms
+ */
+import { createServer, type Server, type ServerResponse } from "node:http";
+import { readFileSync, existsSync, watch, type FSWatcher } from "node:fs";
+import { join } from "node:path";
+import { assembleContextGraph } from "./assemble.js";
+
+export interface VizServerOptions {
+ contextDir: string;
+ viewerDir: string;
+ port: number;
+ repoName: string;
+}
+
+export interface VizServer {
+ url: string;
+ close(): Promise<void>;
+}
+
+const PORT_ATTEMPTS = 10;
+const WATCH_DEBOUNCE_MS = 300;
+
+const STATIC_FILES: Record<string, { file: string; type: string }> = {
+ "/": { file: "index.html", type: "text/html; charset=utf-8" },
+ "/index.html": { file: "index.html", type: "text/html; charset=utf-8" },
+ "/app.js": { file: "app.js", type: "text/javascript; charset=utf-8" },
+ "/style.css": { file: "style.css", type: "text/css; charset=utf-8" },
+};
+
+function sendJson(res: ServerResponse, status: number, body: unknown): void {
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
+ res.end(JSON.stringify(body));
+}
+
+function listen(server: Server, port: number): Promise<boolean> {
+ return new Promise((resolve, reject) => {
+ const onError = (err: NodeJS.ErrnoException) => {
+ if (err.code === "EADDRINUSE") resolve(false);
+ else reject(err);
+ };
+ server.once("error", onError);
+ server.listen(port, "127.0.0.1", () => {
+ server.removeListener("error", onError);
+ resolve(true);
+ });
+ });
+}
+
+export async function startVizServer(opts: VizServerOptions): Promise<VizServer> {
+ const sseClients = new Set<ServerResponse>();
+
+ const server = createServer((req, res) => {
+ const path = (req.url ?? "/").split("?")[0];
+
+ const asset = STATIC_FILES[path];
+ if (asset) {
+ const file = join(opts.viewerDir, asset.file);
+ if (!existsSync(file)) {
+ res.writeHead(404, { "content-type": "text/plain" });
+ res.end("viewer bundle missing — run the package build");
+ return;
+ }
+ res.writeHead(200, { "content-type": asset.type });
+ res.end(readFileSync(file));
+ return;
+ }
+
+ if (path === "/api/context-graph") {
+ const graph = assembleContextGraph(opts.contextDir);
+ sendJson(res, 200, { ...graph, meta: { ...graph.meta, repoName: opts.repoName } });
+ return;
+ }
+
+ if (path === "/api/code-graph") {
+ const file = join(opts.contextDir, "graph.json");
+ if (!existsSync(file)) {
+ sendJson(res, 404, { error: "no graph.json in this context dir — run `graft graph` first" });
+ return;
+ }
+ try {
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
+ if (parsed?.meta?.version !== 1) {
+ sendJson(res, 404, { error: "graph.json has an unsupported version — regenerate with `graft graph`" });
+ return;
+ }
+ sendJson(res, 200, parsed);
+ } catch {
+ sendJson(res, 404, { error: "graph.json is unreadable — regenerate with `graft graph`" });
+ }
+ return;
+ }
+
+ if (path === "/events") {
+ res.writeHead(200, {
+ "content-type": "text/event-stream",
+ "cache-control": "no-cache",
+ connection: "keep-alive",
+ });
+ res.write(": connected\n\n");
+ sseClients.add(res);
+ req.on("close", () => sseClients.delete(res));
+ return;
+ }
+
+ res.writeHead(404, { "content-type": "text/plain" });
+ res.end("not found");
+ });
+
+ let port = opts.port;
+ let bound = false;
+ for (let i = 0; i < PORT_ATTEMPTS && !bound; i++) {
+ port = opts.port + i;
+ bound = await listen(server, port);
+ }
+ if (!bound) {
+ throw new Error(`no free port in ${opts.port}–${opts.port + PORT_ATTEMPTS - 1}`);
+ }
+
+ let watcher: FSWatcher | undefined;
+ let debounce: NodeJS.Timeout | undefined;
+ if (existsSync(opts.contextDir)) {
+ watcher = watch(opts.contextDir, () => {
+ clearTimeout(debounce);
+ debounce = setTimeout(() => {
+ for (const client of sseClients) client.write("data: change\n\n");
+ }, WATCH_DEBOUNCE_MS);
+ });
+ }
+
+ return {
+ url: `http://127.0.0.1:${port}`,
+ close(): Promise<void> {
+ clearTimeout(debounce);
+ watcher?.close();
+ for (const client of sseClients) client.end();
+ sseClients.clear();
+ return new Promise((resolve, reject) => server.close((err) => (err ? reject(err) : resolve())));
+ },
+ };
+}
diff --git a/test/viz-serve.test.ts b/test/viz-serve.test.ts
new file mode 100644
index 00000000..d8c91649
--- /dev/null
+++ b/test/viz-serve.test.ts
@@ -0,0 +1,99 @@
+/**
+ * Tests for the viz server: endpoint shapes, code-graph gating, port fallback,
+ * and SSE live-reload on context-dir changes.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, writeFileSync, mkdirSync, rmSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+import { createServer } from "node:http";
+import { startVizServer } from "../src/viz/serve.js";
+
+function makeDirs(): { contextDir: string; viewerDir: string; root: string } {
+ const root = mkdtempSync(join(tmpdir(), "graftviz-srv-"));
+ const contextDir = join(root, ".context");
+ const viewerDir = join(root, "viewer");
+ mkdirSync(contextDir);
+ mkdirSync(viewerDir);
+ writeFileSync(join(viewerDir, "index.html"), "<title>stub</title>\n");
+ writeFileSync(join(viewerDir, "app.js"), "// stub\n");
+ writeFileSync(join(viewerDir, "style.css"), "/* stub */\n");
+ writeFileSync(
+ join(contextDir, "alpha.md"),
+ `---\nname: Alpha\nslug: alpha\ntype: system\nsources: []\nlinks: []\n---\nbody\n`,
+ );
+ return { contextDir, viewerDir, root };
+}
+
+test("viz server serves viewer, context graph, and gates code graph", async () => {
+ const { contextDir, viewerDir, root } = makeDirs();
+ const srv = await startVizServer({ contextDir, viewerDir, port: 4831, repoName: "fixture" });
+ try {
+ const html = await fetch(`${srv.url}/`).then((r) => r.text());
+ assert.match(html, /stub/);
+
+ const graph = await fetch(`${srv.url}/api/context-graph`).then((r) => r.json());
+ assert.equal(graph.meta.nodeCount, 1);
+ assert.equal(graph.meta.repoName, "fixture");
+ assert.equal(graph.nodes[0].id, "alpha");
+
+ // no graph.json yet → 404 with an explanatory error
+ const missing = await fetch(`${srv.url}/api/code-graph`);
+ assert.equal(missing.status, 404);
+ const body = await missing.json();
+ assert.match(body.error, /graft graph/);
+
+ // valid graph.json → passthrough
+ writeFileSync(
+ join(contextDir, "graph.json"),
+ JSON.stringify({ meta: { version: 1, nodeCount: 0, edgeCount: 0, languages: [] }, nodes: [], edges: [] }),
+ );
+ const code = await fetch(`${srv.url}/api/code-graph`).then((r) => r.json());
+ assert.equal(code.meta.version, 1);
+ } finally {
+ await srv.close();
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test("viz server falls back to the next free port", async () => {
+ const { contextDir, viewerDir, root } = makeDirs();
+ const blocker = createServer(() => {});
+ await new Promise<void>((res) => blocker.listen(4841, "127.0.0.1", res));
+ const srv = await startVizServer({ contextDir, viewerDir, port: 4841, repoName: "fixture" });
+ try {
+ assert.match(srv.url, /:4842$/);
+ } finally {
+ await srv.close();
+ await new Promise((res) => blocker.close(res));
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test("viz server emits an SSE event when the context dir changes", async () => {
+ const { contextDir, viewerDir, root } = makeDirs();
+ const srv = await startVizServer({ contextDir, viewerDir, port: 4851, repoName: "fixture" });
+ try {
+ const controller = new AbortController();
+ const res = await fetch(`${srv.url}/events`, {
+ headers: { accept: "text/event-stream" },
+ signal: controller.signal,
+ });
+ const reader = res.body!.getReader();
+ // trigger a change after the stream is open
+ setTimeout(() => writeFileSync(join(contextDir, "alpha.md"), "---\nname: Alpha2\nslug: alpha\n---\n"), 150);
+ const deadline = Date.now() + 5000;
+ let seen = "";
+ while (Date.now() < deadline && !seen.includes("data: change")) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ seen += new TextDecoder().decode(value);
+ }
+ controller.abort();
+ assert.match(seen, /data: change/);
+ } finally {
+ await srv.close();
+ rmSync(root, { recursive: true, force: true });
+ }
+});