feat(web): add notebook chat panel (#8)
This commit is contained in:
@@ -7,6 +7,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;
|
||||
@@ -41,6 +42,7 @@ export async function buildApp(options: AppOptions = {}): Promise<FastifyInstanc
|
||||
await app.register(workspacePlugin, { config });
|
||||
await app.register(runsPlugin, { config, hub });
|
||||
await app.register(terminalPlugin, { ...options.terminal, workspaceDir: config.workspaceDir });
|
||||
await app.register(chatPlugin, { config });
|
||||
|
||||
if (options.watchNotebooks) {
|
||||
const watcher = createNotebookWatcher(config.workspaceDir, {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# Chat transport and CLI contract (#8)
|
||||
|
||||
`/api/chat` is a dedicated JSON WebSocket protected by the existing auth and
|
||||
same-origin hook. Run events remain on `/api/events`. The socket owns its turn:
|
||||
disconnect, server shutdown, Stop, a five-minute timeout, malformed CLI output,
|
||||
or resource overflow terminates the child (SIGTERM, then SIGKILL after 1.5s).
|
||||
One turn per conversation, one per socket, at most four processes globally.
|
||||
The lock lasts until process close. Output is capped at 4 MiB per turn, records
|
||||
at 1 MiB, stderr at 8 KiB and outgoing socket buffering at 1 MiB.
|
||||
|
||||
Client frames: `send` with `message` (1–32000 characters), optional
|
||||
`conversationId`, optional workspace-relative `notebookPath`, and required
|
||||
`allowShell` boolean; or `cancel`. Server frames: `history`, `conversation`,
|
||||
`delta`, `tool` (name and optional notebook path only), `finished` (optional
|
||||
cancelled/costUsd/durationMs), and `error` (code and safe message). See core's
|
||||
additive Chat section. Tool activity describes requested operations, not proof
|
||||
that an edit succeeded. The existing watcher reloads actual changed files.
|
||||
|
||||
The data directory stores only a private, atomically replaced index of up to
|
||||
100 conversations: ID, first-message title (120 characters), CLI session ID,
|
||||
creation and update timestamps. Old inactive entries are evicted first.
|
||||
Shell permission is per-turn and never persisted. Messages/tool contents are
|
||||
not stored by ShellBook; Claude retains its own session files for `--resume`.
|
||||
The browser caches messages only while this panel is mounted. Do not enter
|
||||
secrets in chat: conversation titles and the CLI's own transcripts persist.
|
||||
|
||||
Verified against the official CLI reference and headless guide on 2026-11-16:
|
||||
- https://code.claude.com/docs/en/cli-reference
|
||||
- https://code.claude.com/docs/en/headless
|
||||
|
||||
Exact base argv: `-p --output-format stream-json --input-format stream-json
|
||||
--verbose --include-partial-messages --restricted --strict-mcp-config
|
||||
--disallowedTools mcp__* --tools Read,Glob,Grep,Edit,Write,MultiEdit
|
||||
--allowedTools Read,Glob,Grep,Edit,Write,MultiEdit --permission-mode acceptEdits
|
||||
--append-system-prompt <ShellBook context>`. Add `,Bash` to both tool lists only
|
||||
when the toggle is enabled; append `--resume <session_id>` 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.
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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<TurnOptions, "executable" | "prefixArgs" | "timeoutMs"> }> = 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<string, ReturnType<typeof startTurn>>();
|
||||
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<typeof startTurn> | 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." }); }
|
||||
});
|
||||
});
|
||||
};
|
||||
@@ -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<void> } {
|
||||
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<typeof setTimeout> | 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<void>(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 }) };
|
||||
}
|
||||
@@ -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(); }
|
||||
});
|
||||
});
|
||||
Vendored
+4
@@ -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"}
|
||||
+15
@@ -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);
|
||||
});
|
||||
@@ -29,6 +29,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 })),
|
||||
);
|
||||
@@ -55,6 +56,7 @@ export function App({ api }: { api: Api }) {
|
||||
const [values, setValues] = useState<ParamValues>({});
|
||||
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("");
|
||||
@@ -319,7 +321,7 @@ export function App({ api }: { api: Api }) {
|
||||
</main>
|
||||
);
|
||||
return (
|
||||
<div className={`app ${terminal ? "with-terminal" : ""}`}>
|
||||
<div className={`app ${terminal || chat ? "with-terminal" : ""}`}>
|
||||
<aside className="sidebar">
|
||||
<h1>
|
||||
ShellBook<span>RUNBOOKS</span>
|
||||
@@ -348,6 +350,7 @@ export function App({ api }: { api: Api }) {
|
||||
</aside>
|
||||
<main>
|
||||
<div className="toolbar">
|
||||
<button aria-expanded={chat} onClick={() => { setChat(!chat); setTerminal(false); }}>Chat</button>
|
||||
<span>{doc?.notebook.title ?? "Loading workspace…"}</span>
|
||||
<button onClick={() => setEdit(!edit)}>
|
||||
{edit ? "Close editor" : "Edit Markdown"}
|
||||
@@ -356,6 +359,7 @@ export function App({ api }: { api: Api }) {
|
||||
aria-expanded={terminal}
|
||||
onClick={() => {
|
||||
setTerminalOpened(true);
|
||||
setChat(false);
|
||||
setTerminal(!terminal);
|
||||
}}
|
||||
>
|
||||
@@ -469,6 +473,9 @@ export function App({ api }: { api: Api }) {
|
||||
</>
|
||||
)}
|
||||
</main>
|
||||
{chat && <ChatPanel notebookPath={doc?.path} openNotebook={path => {
|
||||
if (!dirty || window.confirm("Discard unsaved edits?")) void load(path);
|
||||
}} openTerminal={() => { setChat(false); setTerminalOpened(true); setTerminal(true); }} />}
|
||||
{terminalOpened && (
|
||||
<Suspense fallback={<p>Loading terminal...</p>}>
|
||||
<TerminalSlot collapsed={!terminal} />
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import type { ChatClientMessage, ChatConversation, ChatEvent } from "@shellbook/core";
|
||||
import "./chat.css";
|
||||
|
||||
export interface ChatSocket {
|
||||
onopen: ((event: Event) => void) | null; onclose: ((event: CloseEvent) => void) | null; onerror: ((event: Event) => void) | null;
|
||||
onmessage: ((event: MessageEvent) => void) | null;
|
||||
send(text: string): void; close(): void;
|
||||
}
|
||||
const connectChat = (): ChatSocket => new WebSocket(`${location.protocol === "https:" ? "wss:" : "ws:"}//${location.host}/api/chat`);
|
||||
type Message = { role: "user" | "assistant" | "tool"; text: string; path?: string };
|
||||
|
||||
export function ChatPanel({ notebookPath, openNotebook, openTerminal, connect = connectChat }: {
|
||||
notebookPath?: string; openNotebook(path: string): void; openTerminal(): void; connect?: () => ChatSocket;
|
||||
}) {
|
||||
const [history, setHistory] = useState<ChatConversation[]>([]);
|
||||
const [selected, setSelected] = useState("");
|
||||
const [messages, setMessages] = useState<Message[]>([]);
|
||||
const cache = useRef(new Map<string, Message[]>());
|
||||
const selectedRef = useRef("");
|
||||
const [text, setText] = useState("");
|
||||
const [allowShell, setAllowShell] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [ready, setReady] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [login, setLogin] = useState(false);
|
||||
const [summary, setSummary] = useState("");
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
const socket = useRef<ChatSocket>();
|
||||
const end = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => { end.current?.scrollIntoView?.({ block: "nearest" }); }, [messages]);
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
let connection: ChatSocket;
|
||||
try { connection = connect(); socket.current = connection; }
|
||||
catch { setError("Cannot connect to chat."); return; }
|
||||
connection.onopen = () => { if (alive) { setReady(true); setError(""); } };
|
||||
connection.onclose = connection.onerror = () => {
|
||||
if (alive) { setReady(false); setBusy(false); setError("Chat disconnected. The current turn was stopped. Reconnect to continue."); }
|
||||
};
|
||||
connection.onmessage = ({ data }) => {
|
||||
if (!alive) return;
|
||||
let event: ChatEvent; try { event = JSON.parse(data); } catch { return; }
|
||||
if (event.type === "history") setHistory(event.conversations);
|
||||
if (event.type === "conversation") {
|
||||
selectedRef.current = event.conversation.id; setSelected(event.conversation.id);
|
||||
setHistory(previous => [...previous.filter(c => c.id !== event.conversation.id), event.conversation]);
|
||||
}
|
||||
if (event.type === "delta") setMessages(previous => {
|
||||
const last = previous.at(-1);
|
||||
return last?.role === "assistant" ? [...previous.slice(0, -1), { ...last, text: last.text + event.text }] : [...previous, { role: "assistant", text: event.text }];
|
||||
});
|
||||
if (event.type === "tool") setMessages(previous => [...previous, {
|
||||
role: "tool", text: `${["Edit", "Write", "MultiEdit"].includes(event.name) ? "Editing" : event.name} ${event.path ?? ""}`.trim(), path: event.path,
|
||||
}]);
|
||||
if (event.type === "error") { setBusy(false); setError(event.message); setLogin(event.code === "login" || event.code === "missing"); }
|
||||
if (event.type === "finished") {
|
||||
setBusy(false); setSummary(event.cancelled ? "Stopped" : `Finished${event.durationMs === undefined ? "" : ` in ${(event.durationMs / 1000).toFixed(1)}s`}${event.costUsd === undefined ? "" : ` · estimated $${event.costUsd.toFixed(4)}`}`);
|
||||
}
|
||||
};
|
||||
return () => { alive = false; connection.close(); };
|
||||
}, [connect, attempt]);
|
||||
useEffect(() => { if (selected) cache.current.set(selected, messages); }, [messages, selected]);
|
||||
function choose(id: string) {
|
||||
selectedRef.current = id; setSelected(id); setMessages(cache.current.get(id) ?? []);
|
||||
setError(""); setLogin(false); setSummary(""); setAllowShell(false);
|
||||
}
|
||||
function send(message: ChatClientMessage) { try { socket.current?.send(JSON.stringify(message)); } catch { setBusy(false); setError("Cannot send chat message. Reconnect to continue."); } }
|
||||
return <aside className="chat-panel" aria-label="Chat panel">
|
||||
<h2>Chat with Claude</h2>
|
||||
<div className="actions"><button disabled={busy} onClick={() => choose("")}>New conversation</button>
|
||||
{!ready && <button onClick={() => setAttempt(n => n + 1)}>Reconnect chat</button>}</div>
|
||||
<label>Conversation history<select aria-label="Conversation history" disabled={busy} value={selected} onChange={e => choose(e.target.value)}>
|
||||
<option value="">New conversation</option>{[...history].reverse().map(c => <option key={c.id} value={c.id}>{c.title}</option>)}
|
||||
</select></label>
|
||||
<div className="chat-messages" role="log" aria-label="Chat messages" aria-live="polite">
|
||||
{!messages.length && <p>{selected ? "Continue this conversation. Earlier messages are retained by the Claude CLI; this view shows messages from this browser session." : "Ask Claude to create or edit a notebook. Do not send secrets."}</p>}
|
||||
{messages.map((m, i) => <div key={i} className={`chat-message ${m.role}`}>
|
||||
{m.role === "tool" ? <small>{m.text} {m.path && <button onClick={() => openNotebook(m.path!)}>Open notebook</button>}</small> : <><strong>{m.role === "user" ? "You" : "Claude"}</strong><ReactMarkdown>{m.text}</ReactMarkdown></>}
|
||||
</div>)}<div ref={end} />
|
||||
</div>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{login && <button onClick={openTerminal}>Open Terminal — run claude, then /login</button>}
|
||||
<p role="status">{busy ? "Claude is working…" : summary}</p>
|
||||
{!messages.length && <div className="actions">{["Create a notebook that…", "Add a check that…"].map(prompt => <button key={prompt} onClick={() => setText(prompt)}>{prompt}</button>)}</div>}
|
||||
<form onSubmit={e => { e.preventDefault(); if (!ready || busy || !text.trim()) return;
|
||||
setMessages(previous => [...previous, { role: "user", text }]); setBusy(true); setError(""); setLogin(false); setSummary("");
|
||||
send({ type: "send", conversationId: selectedRef.current || undefined, message: text, notebookPath, allowShell }); setText("");
|
||||
}}>
|
||||
<label>Message<textarea value={text} onChange={e => setText(e.target.value)} maxLength={32000} required rows={3} /></label>
|
||||
<label className="chat-shell"><input type="checkbox" checked={allowShell} disabled={busy} onChange={e => setAllowShell(e.target.checked)} />Allow Claude to run shell commands on the ShellBook server</label>
|
||||
<small>Off by default. Enabling this allows commands as the service user, including network access. File tools otherwise stay in the workspace.</small>
|
||||
<div className="actions"><button disabled={!ready || busy || !text.trim()}>Send</button>{busy && <button type="button" onClick={() => send({ type: "cancel" })}>Stop</button>}</div>
|
||||
</form>
|
||||
</aside>;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
.chat-panel { position: sticky; top: 0; height: 100vh; min-width: 0; display: flex; flex-direction: column; gap: .6rem; padding: 1rem; border-left: 1px solid #64748b; box-sizing: border-box; }
|
||||
.chat-panel h2, .chat-panel p { margin: .25rem 0; }
|
||||
.chat-panel select, .chat-panel textarea { width: 100%; box-sizing: border-box; }
|
||||
.chat-panel label { display: block; }
|
||||
.chat-messages { flex: 1; min-height: 120px; overflow-y: auto; overflow-wrap: anywhere; }
|
||||
.chat-messages pre { overflow-x: auto; }
|
||||
.chat-message { padding: .6rem 0; border-bottom: 1px solid #64748b55; }
|
||||
.chat-message.user { opacity: .85; }
|
||||
.chat-shell { margin-top: .5rem; }
|
||||
.chat-panel form { flex-shrink: 0; }
|
||||
@media (max-width: 900px) { .chat-panel { position: static; grid-column: 1 / -1; height: min(800px, 100dvh); } }
|
||||
@media (max-width: 580px) { .with-terminal { display: block; } .chat-panel { padding: .7rem; } }
|
||||
@@ -0,0 +1,49 @@
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { ChatPanel, type ChatSocket } from "../ChatPanel";
|
||||
import type { ChatEvent } from "@shellbook/core";
|
||||
|
||||
function setup() {
|
||||
const socket: ChatSocket = { onopen: null, onclose: null, onerror: null, onmessage: null, send: vi.fn(), close: vi.fn() };
|
||||
const openNotebook = vi.fn(), openTerminal = vi.fn();
|
||||
const view = render(<ChatPanel notebookPath="notebooks/current.md" connect={() => socket} openNotebook={openNotebook} openTerminal={openTerminal} />);
|
||||
act(() => socket.onopen?.(new Event("open")));
|
||||
const emit = (event: ChatEvent) => act(() => socket.onmessage?.({ data: JSON.stringify(event) } as MessageEvent));
|
||||
return { socket, emit, openNotebook, openTerminal, ...view };
|
||||
}
|
||||
it("sends notebook context, defaults shell off, streams Markdown, opens edited notebooks and stops", () => {
|
||||
const { socket, emit, openNotebook } = setup();
|
||||
fireEvent.change(screen.getByLabelText("Message"), { target: { value: "Create nginx" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send" }));
|
||||
expect(socket.send).toHaveBeenCalledWith(JSON.stringify({ type: "send", message: "Create nginx", notebookPath: "notebooks/current.md", allowShell: false }));
|
||||
emit({ type: "delta", text: "Hello **" }); emit({ type: "delta", text: "world**" });
|
||||
expect(screen.getByText("world").tagName).toBe("STRONG");
|
||||
emit({ type: "tool", name: "Edit", path: "notebooks/nginx.md" });
|
||||
fireEvent.click(screen.getByText("Open notebook")); expect(openNotebook).toHaveBeenCalledWith("notebooks/nginx.md");
|
||||
fireEvent.click(screen.getByText("Stop")); expect(socket.send).toHaveBeenLastCalledWith('{"type":"cancel"}');
|
||||
emit({ type: "finished", durationMs: 1000, costUsd: .01 }); expect(screen.getByRole("status")).toHaveTextContent("Finished in 1.0s");
|
||||
});
|
||||
it("offers terminal login recovery and closes the socket on unmount", () => {
|
||||
const { emit, openTerminal, unmount, socket } = setup();
|
||||
emit({ type: "error", code: "login", message: "Please log in" });
|
||||
fireEvent.click(screen.getByRole("button", { name: /Open Terminal/ })); expect(openTerminal).toHaveBeenCalledOnce();
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("Please log in");
|
||||
unmount(); expect(socket.close).toHaveBeenCalledOnce();
|
||||
});
|
||||
it("resumes history, enables shell explicitly and resets it for new conversations", () => {
|
||||
const { emit, socket } = setup();
|
||||
emit({ type: "history", conversations: [{ id: "saved", title: "Earlier notebook", createdAt: "now", updatedAt: "now" }] });
|
||||
fireEvent.change(screen.getByLabelText("Conversation history"), { target: { value: "saved" } });
|
||||
fireEvent.click(screen.getByLabelText(/Allow Claude/));
|
||||
fireEvent.click(screen.getByText("Add a check that…"));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send" }));
|
||||
expect(JSON.parse((socket.send as ReturnType<typeof vi.fn>).mock.calls[0]![0])).toMatchObject({ conversationId: "saved", allowShell: true });
|
||||
expect(screen.getByText("New conversation", { selector: "button" })).toBeDisabled();
|
||||
emit({ type: "finished" }); fireEvent.click(screen.getByText("New conversation", { selector: "button" }));
|
||||
expect(screen.getByLabelText(/Allow Claude/)).not.toBeChecked();
|
||||
});
|
||||
it("handles a disconnect and disables sending", () => {
|
||||
const { socket } = setup(); act(() => socket.onclose?.(new CloseEvent("close")));
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("disconnected");
|
||||
expect(screen.getByRole("button", { name: "Reconnect chat" })).toBeInTheDocument();
|
||||
});
|
||||
Reference in New Issue
Block a user