diff --git a/.agents/mind/architecture.md b/.agents/mind/architecture.md index 513599e..d26c8bc 100644 --- a/.agents/mind/architecture.md +++ b/.agents/mind/architecture.md @@ -2,7 +2,7 @@ - [2026-11-15] **Custom app instead of marimo/Atuin/Runme.** Need: literal, copyable shell + SSH run + checks + params + dynamic downloads + Claude Code CLI next to the notebook. No existing tool covers all; marimo hid commands behind Python. - [2026-11-15] **TypeScript monorepo** (core / server / web). One language; node-pty + xterm.js is the proven path for the embedded Claude terminal. -- [2026-11-15] **AI = real `claude` CLI in a tmux-backed terminal panel.** Uses the user's subscription legitimately; marimo's ACP panel was deprecated and API-key chat is not wanted. +- [2026-11-15] **AI = real `claude` CLI in chat or tmux terminal (#8).** Chat uses per-turn headless stream-json with explicit resume; restricted file tools, optional Bash, dedicated authenticated WebSocket. Subscription login stays with the CLI; no SDK/API-key chat. - [2026-11-15] **Workspace (notebooks, hosts.yaml) is a separate git repo** from the app code; the app ships a `CLAUDE.md` format guide into it. - [2026-11-16] **buildApp wiring:** auth registered first and on by default (`auth:false` only in tests); one EventsHub feeds /api/events from runs and the notebook watcher (`watchNotebooks`); terminal cwd = config.workspaceDir. - [2026-11-16] **Secrets on SSH:** exported via `export NAME=` lines on stdin before the script (sshd AcceptEnv unreliable); redacted from streamed output, captures and audit. diff --git a/.agents/mind/gotchas.md b/.agents/mind/gotchas.md index a97d91f..441eea2 100644 --- a/.agents/mind/gotchas.md +++ b/.agents/mind/gotchas.md @@ -8,5 +8,6 @@ - [2026-11-16] **Exit codes vs errors:** a non-zero script exit is a normal result (check ❌) and goes only in run.finished; run.error is for transport/setup failures. - [2026-11-16] **Notebook root symlinks (#9):** validating only child components after realpath(root) permits a symlinked notebooks root. Notebook reads and mutations validate the root itself before walking children; regression-covered. Workspace CLI/filesystem writers remain trusted against concurrent path swaps. +- [2026-11-16] **Chat CLI permissions (#8):** allowedTools only auto-approves; tools + restricted mode (2.1.248+) enforce the file/tool boundary. Synthetic fixture tests never invoke the real CLI; deployment must verify installed-version/login compatibility. ## Archive diff --git a/AGENTS.md b/AGENTS.md index 7f3403c..95a19a0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,8 +18,9 @@ hosts over SSH. Spec: `docs/spec.md` — read it before any design change. - **Strict SSH host key checking.** Unknown keys require explicit user confirmation (TOFU). - **`check` steps must be side-effect free**; only `run` steps change hosts. - Notebooks stay valid, readable Markdown in any renderer (Gitea/GitHub). -- AI integration uses the real Claude Code CLI in a terminal (user's own login). No - embedding of subscription credentials, no SDK-based chat on subscription auth. +- AI integration uses the real `claude` CLI with the user's own login: interactively + in the terminal panel or headless (`-p`, stream-json) behind the chat panel. No + embedding of subscription credentials, API-key requirement, or SDK-based chat. ## Stack and layout diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts index c9a81b3..970dd02 100644 --- a/apps/server/src/app.ts +++ b/apps/server/src/app.ts @@ -8,6 +8,7 @@ import { terminalPlugin, type TerminalOptions } from "./terminal"; import { createNotebookWatcher } from "./watch"; import { registerAuth, type AuthOptions } from "./auth"; import { registerStatic } from "./static"; +import { chatPlugin } from "./chat"; export interface AppOptions { logger?: boolean; @@ -43,6 +44,7 @@ export async function buildApp(options: AppOptions = {}): Promise`. Add `,Bash` to both tool lists only +when the toggle is enabled; append `--resume ` on follow-ups. +`--allowedTools` auto-approves; `--tools` actually restricts built-ins. +`--restricted` confines file tools to working directories and ignores user/project +settings (requires Claude Code **2.1.248+**). MCP is disabled. No bypass mode. +Restricted mode still reads workspace CLAUDE.md. Unlike `--bare`, this preserves +subscription authentication. The default CLI environment is inherited; no auth +files or tokens are read or copied by ShellBook. Unsupported flags fail closed. +Optional Bash has service-user authority; this toggle is not an OS sandbox. + +The user prompt is a single newline-delimited user JSON record on stdin; never +part of argv or a shell string. Init/result session IDs enable explicit resume. +Only text deltas are rendered (assistant snapshots would duplicate them). +Result errors and bounded stderr detect missing login without forwarding raw +records or environment details. Cost is a CLI estimate and can be cumulative +across a resumed session. Terminal recovery says to run `claude`, then `/login`. + +Tests use a synthetic captured-format JSONL fixture and a small Node executable +fixture, invoked through Node for portable Windows execution, including a fake +`claude` launcher resolved through PATH (no real CLI or credentials). +The fixture is representative protocol data, not a live recording. +Real installed CLI compatibility, subscription login, Linux process trees and +the visual layout still need deployment verification. diff --git a/apps/server/src/chat/cli.ts b/apps/server/src/chat/cli.ts new file mode 100644 index 0000000..09ea8bb --- /dev/null +++ b/apps/server/src/chat/cli.ts @@ -0,0 +1,50 @@ +import type { ChatEvent } from "@shellbook/core"; +import { isAbsolute, relative, resolve } from "node:path"; + +export function notebookPath(value: unknown): value is string { + return typeof value === "string" && /^notebooks\/(?:[^/\\\x00-\x1f]+\/)*[^/\\\x00-\x1f]+\.md$/.test(value) + && !value.split("/").some(part => part === "." || part === ".."); +} + +export function buildClaudeArgs(options: { sessionId?: string; notebookPath?: string; allowShell: boolean }): string[] { + const tools = "Read,Glob,Grep,Edit,Write,MultiEdit" + (options.allowShell ? ",Bash" : ""); + const args = ["-p", "--output-format", "stream-json", "--input-format", "stream-json", "--verbose", + "--include-partial-messages", "--restricted", "--strict-mcp-config", "--disallowedTools", "mcp__*", + "--tools", tools, "--allowedTools", tools, "--permission-mode", "acceptEdits", + "--append-system-prompt", `You are inside ShellBook. Follow the workspace CLAUDE.md notebook format. Write notebooks in notebooks/**/*.md. Never include secrets in notebooks or responses. Open notebook: ${options.notebookPath ?? "none"}.`]; + if (options.sessionId) args.push("--resume", options.sessionId); + return args; +} + +export type ParsedEvent = ChatEvent | { type: "session"; sessionId: string }; +const loginPattern = /not logged in|please (?:run|use).*\/login|authentication[_ ](?:error|required)|invalid.*(?:api key|oauth)|login required|failed to authenticate/i; +export const needsLogin = (text: string) => loginPattern.test(text); + +/** Whitelist fields: never forward full CLI records, tool inputs, or stderr. */ +export function parseClaudeLine(line: string, workspace: string): ParsedEvent[] { + const m = JSON.parse(line); + if (!m || typeof m !== "object") throw new Error("Invalid CLI record"); + const result: ParsedEvent[] = []; + if (typeof m.session_id === "string" && /^[a-zA-Z0-9-]{1,128}$/.test(m.session_id)) result.push({ type: "session", sessionId: m.session_id }); + if (m.type === "stream_event" && m.event?.type === "content_block_delta" && m.event.delta?.type === "text_delta" && typeof m.event.delta.text === "string") { + result.push({ type: "delta", text: m.event.delta.text }); + } + if (m.type === "assistant" && Array.isArray(m.message?.content)) { + for (const block of m.message.content) { + if (block.type !== "tool_use" || typeof block.name !== "string") continue; + let target: string | undefined; + const file = block.input?.file_path ?? block.input?.path; + if (typeof file === "string") { + const local = relative(workspace, resolve(workspace, file)).replaceAll("\\", "/"); + if (!isAbsolute(local) && !local.startsWith("../") && notebookPath(local)) target = local; + } + result.push({ type: "tool", name: block.name.slice(0, 80), ...(target ? { path: target } : {}) }); + } + } + if (m.type === "result") { + if (m.is_error || m.subtype !== "success") { + result.push({ type: "error", code: needsLogin(JSON.stringify(m)) ? "login" : "cli", message: needsLogin(JSON.stringify(m)) ? "Claude needs a login. Open Terminal, run claude, then /login." : "Claude could not complete this turn." }); + } else result.push({ type: "finished", ...(typeof m.total_cost_usd === "number" ? { costUsd: m.total_cost_usd } : {}), ...(typeof m.duration_ms === "number" ? { durationMs: m.duration_ms } : {}) }); + } + return result; +} diff --git a/apps/server/src/chat/index.ts b/apps/server/src/chat/index.ts new file mode 100644 index 0000000..6b1c747 --- /dev/null +++ b/apps/server/src/chat/index.ts @@ -0,0 +1,82 @@ +import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { randomUUID } from "node:crypto"; +import type { FastifyPluginAsync } from "fastify"; +import type { ChatClientMessage, ChatConversation, ChatEvent } from "@shellbook/core"; +import type { ServerConfig } from "../config"; +import { notebookPath } from "./cli"; +import { startTurn, type TurnOptions } from "./process"; + +export function parseChatMessage(text: string): ChatClientMessage | undefined { + if (text.length > 70_000) return; + let m; try { m = JSON.parse(text); } catch { return; } + if (!m || typeof m !== "object") return; + if (m.type === "cancel") return { type: "cancel" }; + if (m.type !== "send" || typeof m.message !== "string" || !m.message.trim() || m.message.length > 32_000 + || typeof m.allowShell !== "boolean" || (m.notebookPath !== undefined && !notebookPath(m.notebookPath)) + || (m.conversationId !== undefined && (typeof m.conversationId !== "string" || !/^[a-f0-9-]{36}$/.test(m.conversationId)))) return; + return { type: "send", message: m.message, allowShell: m.allowShell, notebookPath: m.notebookPath, conversationId: m.conversationId }; +} + +export const chatPlugin: FastifyPluginAsync<{ config: ServerConfig; processOptions?: Pick }> = async (app, { config, processOptions }) => { + mkdirSync(config.dataDir, { recursive: true, mode: 0o700 }); + const file = join(config.dataDir, "chat-conversations.json"); + let conversations: ChatConversation[] = []; + try { + const raw = readFileSync(file); + if (raw.length > 512 * 1024) throw new Error("Conversation index exceeds limit"); + const saved = JSON.parse(raw.toString()); + if (!Array.isArray(saved) || saved.length > 100 || saved.some(c => !c || !/^[a-f0-9-]{36}$/.test(c.id) + || typeof c.title !== "string" || c.title.length > 120 || typeof c.createdAt !== "string" || typeof c.updatedAt !== "string" + || (c.sessionId !== undefined && !/^[a-zA-Z0-9-]{1,128}$/.test(c.sessionId)))) throw new Error("Invalid conversation index"); + conversations = saved; + } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw new Error("Cannot load chat conversation index"); } + const save = () => { + writeFileSync(file + ".tmp", JSON.stringify(conversations), { mode: 0o600 }); + renameSync(file + ".tmp", file); + }; + const turns = new Map>(); + app.addHook("onClose", async () => { for (const turn of turns.values()) turn.cancel(); await Promise.all([...turns.values()].map(t => t.done)); }); + app.get("/api/chat", { websocket: true }, socket => { + let active: ReturnType | undefined; + const send = (event: ChatEvent) => { + if (socket.readyState !== 1) return; + if (socket.bufferedAmount > 1024 * 1024) { active?.cancel(); socket.close(1013, "Chat client too slow"); return; } + socket.send(JSON.stringify(event), error => { if (error) active?.cancel(); }); + }; + send({ type: "history", conversations }); + socket.on("close", () => active?.cancel()); + socket.on("error", () => { active?.cancel(); socket.close(); }); + socket.on("message", (raw, binary) => { + const m = binary ? undefined : parseChatMessage(raw.toString()); + if (!m) { send({ type: "error", code: "invalid", message: "Invalid chat message." }); return; } + if (m.type === "cancel") { active?.cancel(); return; } + if (active || (m.conversationId && turns.has(m.conversationId))) { send({ type: "error", code: "busy", message: "A turn is already running in this conversation." }); return; } + // Bound total concurrent CLI processes, not only per-conversation use. + if (turns.size >= 4) { send({ type: "error", code: "busy", message: "Chat is busy. Try again shortly." }); return; } + let conversation = conversations.find(c => c.id === m.conversationId); + if (m.conversationId && !conversation) { send({ type: "error", code: "invalid", message: "Conversation no longer exists." }); return; } + try { + if (!conversation) { + if (conversations.length >= 100) { + const removable = conversations.findIndex(c => !turns.has(c.id)); + if (removable < 0) throw new Error("No free conversation slots"); + conversations.splice(removable, 1); + } + const now = new Date().toISOString(); + conversation = { id: randomUUID(), title: m.message.replace(/\s+/g, " ").slice(0, 120), createdAt: now, updatedAt: now }; + conversations.push(conversation); + } + conversation.updatedAt = new Date().toISOString(); save(); + const current = conversation; + send({ type: "conversation", conversation: current }); + active = startTurn({ ...processOptions, workspaceDir: config.workspaceDir, message: m.message, allowShell: m.allowShell, + notebookPath: m.notebookPath, sessionId: current.sessionId, emit: send, + onSession: id => { current.sessionId = id; try { save(); } catch { active?.cancel(); send({ type: "error", code: "cli", message: "Cannot save conversation." }); } }, + }); + turns.set(current.id, active); + void active.done.finally(() => { turns.delete(current.id); active = undefined; }); + } catch { send({ type: "error", code: "cli", message: "Cannot start or save conversation." }); } + }); + }); +}; diff --git a/apps/server/src/chat/process.ts b/apps/server/src/chat/process.ts new file mode 100644 index 0000000..3a6f685 --- /dev/null +++ b/apps/server/src/chat/process.ts @@ -0,0 +1,70 @@ +import { spawn } from "node:child_process"; +import { StringDecoder } from "node:string_decoder"; +import type { ChatEvent } from "@shellbook/core"; +import { buildClaudeArgs, needsLogin, parseClaudeLine } from "./cli"; + +export interface TurnOptions { + workspaceDir: string; message: string; sessionId?: string; notebookPath?: string; allowShell: boolean; + executable?: string; prefixArgs?: string[]; timeoutMs?: number; + emit(event: ChatEvent): void; onSession(id: string): void; +} +/** One process per turn. Resolves only on close, so cancelled turns retain their lock. */ +export function startTurn(options: TurnOptions): { cancel(): void; done: Promise } { + const child = spawn(options.executable ?? "claude", [...(options.prefixArgs ?? []), ...buildClaudeArgs(options)], { + cwd: options.workspaceDir, shell: false, stdio: ["pipe", "pipe", "pipe"], windowsHide: true, + detached: process.platform !== "win32", + }); + let terminal: ChatEvent | undefined; + let stopped = false, bytes = 0, pending = "", stderr = ""; + const decoder = new StringDecoder("utf8"); + let force: ReturnType | undefined; + const kill = (signal: NodeJS.Signals) => { + // On the Linux service, also stop any shell descendants in the turn's group. + try { + if (process.platform !== "win32" && child.pid) process.kill(-child.pid, signal); + else child.kill(signal); + } catch { /* The process may already have exited. */ } + }; + const stop = (event: ChatEvent) => { + if (stopped) return; + stopped = true; terminal = event; + kill("SIGTERM"); + force = setTimeout(() => kill("SIGKILL"), 1500); + force.unref(); + }; + const consume = (line: string) => { + if (!line.trim()) return; + for (const event of parseClaudeLine(line, options.workspaceDir)) { + if (event.type === "session") options.onSession(event.sessionId); + else if (event.type === "finished" || event.type === "error") terminal = event; + else options.emit(event); + } + }; + child.stdout.on("data", (chunk: Buffer) => { + if (stopped) return; + bytes += chunk.length; + if (bytes > 4 * 1024 * 1024) { stop({ type: "error", code: "limit", message: "Claude output limit exceeded." }); return; } + pending += decoder.write(chunk); + if (pending.length > 1024 * 1024) { stop({ type: "error", code: "limit", message: "Claude record limit exceeded." }); return; } + const lines = pending.split("\n"); pending = lines.pop()!; + try { for (const line of lines) consume(line); } + catch { stop({ type: "error", code: "cli", message: "Invalid response from Claude CLI." }); } + }); + child.stderr.on("data", (chunk: Buffer) => { stderr = (stderr + chunk.toString()).slice(-8192); }); + child.stdin.on("error", () => {}); + child.stdin.end(JSON.stringify({ type: "user", message: { role: "user", content: options.message } }) + "\n"); + const timeout = setTimeout(() => stop({ type: "error", code: "timeout", message: "Claude turn timed out." }), options.timeoutMs ?? 5 * 60_000); + const done = new Promise(resolve => { + child.on("error", (error: NodeJS.ErrnoException) => { + terminal = { type: "error", code: error.code === "ENOENT" ? "missing" : "cli", message: error.code === "ENOENT" ? "Claude CLI is missing from the server PATH. Install it, then open Terminal and run claude followed by /login." : "Unable to start Claude CLI." }; + }); + child.on("close", code => { + clearTimeout(timeout); clearTimeout(force); + if (!stopped) { try { consume(pending + decoder.end()); } catch { terminal = undefined; } } + if (!stopped && needsLogin(stderr)) terminal = { type: "error", code: "login", message: "Claude needs a login. Open Terminal, run claude, then /login." }; + if (!terminal || (!stopped && code !== 0 && terminal.type === "finished")) terminal = { type: "error", code: "cli", message: "Claude CLI exited without completing the turn." }; + options.emit(terminal); resolve(); + }); + }); + return { done, cancel: () => stop({ type: "finished", cancelled: true }) }; +} diff --git a/apps/server/test/chat.test.ts b/apps/server/test/chat.test.ts new file mode 100644 index 0000000..ae4b5db --- /dev/null +++ b/apps/server/test/chat.test.ts @@ -0,0 +1,104 @@ +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(); } + }); +}); diff --git a/apps/server/test/fixtures/chat.jsonl b/apps/server/test/fixtures/chat.jsonl new file mode 100644 index 0000000..1760331 --- /dev/null +++ b/apps/server/test/fixtures/chat.jsonl @@ -0,0 +1,4 @@ +{"type":"system","subtype":"init","session_id":"11111111-1111-4111-8111-111111111111"} +{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello notebook"}}} +{"type":"assistant","message":{"content":[{"type":"text","text":"Hello notebook"},{"type":"tool_use","id":"tool-1","name":"Edit","input":{"file_path":"notebooks/setup/nginx.md","old_string":"private contents","new_string":"other contents"}}]}} +{"type":"result","subtype":"success","is_error":false,"session_id":"11111111-1111-4111-8111-111111111111","total_cost_usd":0.002,"duration_ms":1234,"result":"Hello notebook"} diff --git a/apps/server/test/fixtures/fake-claude.cjs b/apps/server/test/fixtures/fake-claude.cjs new file mode 100644 index 0000000..8fda461 --- /dev/null +++ b/apps/server/test/fixtures/fake-claude.cjs @@ -0,0 +1,15 @@ +// Test-only executable. No external network or real CLI calls. +const fs = require('node:fs'); +let input = ''; +process.stdin.on('data', chunk => input += chunk); +process.stdin.on('end', () => { + const message = JSON.parse(input).message.content; + if (message === 'hang') { setInterval(() => {}, 1000); return; } + if (message === 'login') { console.log(JSON.stringify({ type: 'result', subtype: 'error_during_execution', is_error: true, result: 'Not logged in · Please run /login' })); process.exitCode = 1; return; } + if (message === 'stderr-login') { process.stderr.write('Authentication required'); process.exitCode = 1; return; } + if (message === 'bad') { console.log('not JSON'); return; } + if (message === 'huge') { process.stdout.write('x'.repeat(1024 * 1024 + 1)); return; } + if (message === 'failed') { process.exitCode = 2; return; } + const lines = fs.readFileSync(__dirname + '/chat.jsonl', 'utf8'); + process.stdout.write(lines); +}); diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index fede150..40c5dd7 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -34,6 +34,7 @@ import type { Api } from "./api"; import { emptySession, eventReducer, stepKey } from "./events"; import { ParamsForm } from "./ParamsForm"; import { StepCard } from "./StepCard"; +import { ChatPanel } from "./ChatPanel"; const TerminalSlot = lazy(() => import("./TerminalSlot").then((module) => ({ default: module.TerminalSlot })), ); @@ -61,6 +62,7 @@ export function App({ api }: { api: Api }) { const [values, setValues] = useState({}); const [edit, setEdit] = useState(false); const [terminal, setTerminal] = useState(false); + const [chat, setChat] = useState(false); const [terminalOpened, setTerminalOpened] = useState(false); const [conflict, setConflict] = useState(false); const [error, setError] = useState(""); @@ -338,7 +340,7 @@ export function App({ api }: { api: Api }) { ); return ( -
+