import { afterEach, describe, expect, it, vi } from "vitest"; import { copyFileSync, linkSync, mkdtempSync, readFileSync, rmSync, symlinkSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import Fastify from "fastify"; import websocket from "@fastify/websocket"; import { buildClaudeArgs, notebookPath, parseClaudeLine } from "../src/chat/cli"; import { startTurn } from "../src/chat/process"; import { chatPlugin, parseChatMessage } from "../src/chat"; import { buildApp } from "../src/app"; import { loadConfig } from "../src/config"; import { loadSessionSecret, signSession } from "../src/auth/session"; import type { ChatEvent } from "@shellbook/core"; const dirs: string[] = []; const temp = () => { const dir = mkdtempSync(join(tmpdir(), "shellbook-chat-")); dirs.push(dir); return dir; }; afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); const fixture = resolve("test/fixtures/fake-claude.cjs"); const processOptions = { executable: process.execPath, prefixArgs: [fixture], timeoutMs: 3000 }; const run = (message: string, extra = {}) => { const events: ChatEvent[] = []; const sessions: string[] = []; const turn = startTurn({ ...processOptions, workspaceDir: process.cwd(), message, allowShell: false, emit: e => events.push(e), onSession: id => sessions.push(id), ...extra }); return { ...turn, events, sessions }; }; describe("chat CLI contract", () => { it("restricts tools, keeps prompts out of argv, resumes explicitly", () => { const args = buildClaudeArgs({ allowShell: false, sessionId: "abc", notebookPath: "notebooks/a.md" }); expect(args).toEqual(expect.arrayContaining(["-p", "--restricted", "--strict-mcp-config", "mcp__*", "--include-partial-messages", "--resume", "abc", "acceptEdits"])); expect(args[args.indexOf("--tools") + 1]).toBe("Read,Glob,Grep,Edit,Write,MultiEdit"); expect(args.join(" ")).not.toContain("bypassPermissions"); expect(args[args.indexOf("--append-system-prompt") + 1]).toContain("notebooks/a.md"); const shell = buildClaudeArgs({ allowShell: true }); expect(shell[shell.indexOf("--allowedTools") + 1]).toContain(",Bash"); }); it("parses captured-format fixture records without duplicating text or exposing tool contents", () => { const events = readFileSync(resolve("test/fixtures/chat.jsonl"), "utf8").trim().split("\n").flatMap(line => parseClaudeLine(line, process.cwd())); expect(events.filter(e => e.type === "delta")).toEqual([{ type: "delta", text: "Hello notebook" }]); expect(events).toContainEqual({ type: "tool", name: "Edit", path: "notebooks/setup/nginx.md" }); expect(events).toContainEqual({ type: "finished", costUsd: .002, durationMs: 1234 }); expect(JSON.stringify(events)).not.toContain("private contents"); expect(parseClaudeLine('{"type":"future"}', process.cwd())).toEqual([]); expect(() => parseClaudeLine("bad", process.cwd())).toThrow(); }); it.each(["../secret", "notebooks/../secret.md", "notebooks/a\\b.md", "/notebooks/a.md", "notebooks/x\n.md"])("rejects invalid notebook %s", path => expect(notebookPath(path)).toBe(false)); it.each(["null", "bad", '{"type":"send","message":"a","allowShell":"yes"}', JSON.stringify({ type: "send", message: "a".repeat(32001), allowShell: false })])("rejects invalid client frame %#", text => expect(parseChatMessage(text)).toBeUndefined()); }); describe("fake CLI lifecycle", () => { it("streams text, extracts session ID, and waits for exit", async () => { const turn = run("hello ' ; $(test)"); await turn.done; expect(turn.sessions).toContain("11111111-1111-4111-8111-111111111111"); expect(turn.events.at(-1)).toEqual({ type: "finished", costUsd: .002, durationMs: 1234 }); }); it.each(["login", "stderr-login"])("detects login failure: %s", async message => { const turn = run(message); await turn.done; expect(turn.events.at(-1)).toMatchObject({ type: "error", code: "login" }); }); it("detects missing CLI", async () => { const turn = run("a", { executable: join(temp(), "missing-claude"), prefixArgs: [] }); await turn.done; expect(turn.events.at(-1)).toMatchObject({ code: "missing" }); }); it("resolves the fake executable on PATH without a shell", async () => { const dir = temp(); const launcher = join(dir, process.platform === "win32" ? "claude.exe" : "claude"); if (process.platform === "win32") { try { linkSync(process.execPath, launcher); } catch { copyFileSync(process.execPath, launcher); } } else symlinkSync(process.execPath, launcher); const previous = process.env.PATH; process.env.PATH = dir + (process.platform === "win32" ? ";" : ":") + previous; try { const turn = run("hello", { executable: "claude" }); await turn.done; expect(turn.events.at(-1)?.type).toBe("finished"); } finally { process.env.PATH = previous; } }); it.each(["bad", "failed", "huge"])("fails safely on %s output", async message => { const turn = run(message); await turn.done; expect(turn.events.at(-1)?.type).toBe("error"); }); it("cancels and reaps the process", async () => { const turn = run("hang"); turn.cancel(); await turn.done; expect(turn.events.at(-1)).toEqual({ type: "finished", cancelled: true }); }); it("times out and reaps the process", async () => { const turn = run("hang", { timeoutMs: 100 }); await turn.done; expect(turn.events.at(-1)).toMatchObject({ code: "timeout" }); }); }); describe("chat route", () => { it("rejects unauthenticated upgrades and foreign origins", async () => { const dir = temp(); const app = await buildApp({ config: { dataDir: dir } }); try { expect((await app.inject("/api/chat")).statusCode).toBe(401); await expect(app.injectWS("/api/chat")).rejects.toThrow("401"); const cookie = `shellbook_session=${signSession(loadSessionSecret(dir), Date.now() + 60000)}`; expect((await app.inject({ url: "/api/chat", headers: { cookie, origin: "https://evil.example" } })).statusCode).toBe(403); } finally { await app.close(); } }); it("persists metadata, prevents concurrent turns, and cancels on disconnect", async () => { const dir = temp(); const config = loadConfig({ dataDir: dir, workspaceDir: process.cwd() }); const app = Fastify(); await app.register(websocket); await app.register(chatPlugin, { config, processOptions }); await app.ready(); const a = await app.injectWS("/api/chat"); const b = await app.injectWS("/api/chat"); const first: any[] = [], second: any[] = []; a.on("message", raw => first.push(JSON.parse(raw.toString()))); b.on("message", raw => second.push(JSON.parse(raw.toString()))); try { a.send(JSON.stringify({ type: "send", message: "hang", allowShell: false })); await vi.waitFor(() => expect(first.some(e => e.type === "conversation")).toBe(true)); const id = first.find(e => e.type === "conversation").conversation.id; b.send(JSON.stringify({ type: "send", message: "hello", allowShell: false, conversationId: id })); await vi.waitFor(() => expect(second.some(e => e.code === "busy")).toBe(true)); [...app.websocketServer.clients][0]!.terminate(); await vi.waitFor(() => expect(a.readyState).toBe(3)); b.send(JSON.stringify({ type: "send", message: "hello", allowShell: false })); await vi.waitFor(() => expect(second.some(e => e.type === "finished")).toBe(true)); const saved = JSON.parse(readFileSync(join(dir, "chat-conversations.json"), "utf8")); expect(saved).toHaveLength(2); expect(saved[1].sessionId).toBeTruthy(); expect(Object.keys(saved[1]).sort()).toEqual(["createdAt", "id", "sessionId", "title", "updatedAt"]); } finally { a.terminate(); b.terminate(); await app.close(); } const restart = Fastify(); await restart.register(websocket); await restart.register(chatPlugin, { config, processOptions }); try { await restart.ready(); } finally { await restart.close(); } }); });