easel-canvas 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/server/chat.mjs CHANGED
@@ -1,33 +1,86 @@
1
1
  // AI-generated with Claude Code, 2026-10-09, reviewed by Hyun Park
2
2
  // In-canvas chat: spawns claude -p / codex exec and turns their output (JSONL) into uniform events streamed over WS.
3
3
  // Attaches the selection, visible boards, comments, references and errors as context; for "N variants" it first creates copies side by side.
4
+ // Each run copies the tracked files to .easel/runs/<id>/ first (POST /api/chat/revert), and everything it changes becomes one undo step
5
+ // that "Undo this run" takes back. Claude Code's permission prompts come back through bin/mcp.mjs --permission as cards in the chat.
4
6
  import { spawn } from "node:child_process";
7
+ import { existsSync } from "node:fs";
5
8
  import fs from "node:fs/promises";
9
+ import os from "node:os";
6
10
  import path from "node:path";
7
11
 
12
+ import { TOOL_ROOT } from "./args.mjs";
8
13
  import { createBoards } from "./boards.mjs";
9
- import { rootOf } from "./fsutil.mjs";
10
- import { readBody, sendJson } from "./index.mjs";
14
+ import { copyRun, revertRun } from "./copies.mjs";
15
+ import { addCustom, customArgv, readCustom, removeCustom } from "./custom.mjs";
16
+ import { boardFile, routeWrite } from "./forks.mjs";
17
+ import { rootOf, toPosix } from "./fsutil.mjs";
18
+ import { requestScope } from "./history.mjs";
19
+ import { originAllowed, readBody, sendJson } from "./index.mjs";
20
+ import { createPermissions, describePermission, permissionRule, toolAnswer } from "./permissions.mjs";
21
+ import { freeRow } from "./place.mjs";
22
+ import { applyRunChanges, dropMissingAutoPlaced, mergeSteps, readRunFile, runBoards, runCopyInfo, undoChanges, withBase } from "./runs.mjs";
11
23
  import { NO_TOKENS_NOTE, readTokens } from "./tokens.mjs";
12
24
 
13
- export const AGENT_LABEL = { claude: "Claude Code", codex: "Codex" };
14
- const LOGIN_CMD = { claude: "claude auth login", codex: "codex login" };
25
+ export const AGENTS = ["claude", "codex", "cursor", "gemini"];
26
+ export const AGENT_LABEL = { claude: "Claude Code", codex: "Codex", cursor: "Cursor Agent", gemini: "Gemini CLI" };
27
+ /** Program each agent runs as, and the arguments of its sign-in check */
28
+ export const AGENT_CLI = { claude: "claude", codex: "codex", cursor: "cursor-agent", gemini: "gemini" };
29
+ const STATUS_ARGS = { claude: ["auth", "status"], codex: ["login", "status"], cursor: ["status"] };
30
+ const LOGIN_CMD = { claude: "claude auth login", codex: "codex login", cursor: "cursor-agent login", gemini: "gemini" };
31
+ /** Vendor install pages for "How to install" */
32
+ export const INSTALL_URL = {
33
+ claude: "https://docs.anthropic.com/en/docs/claude-code/setup",
34
+ codex: "https://github.com/openai/codex#quickstart",
35
+ cursor: "https://cursor.com/cli",
36
+ gemini: "https://github.com/google-gemini/gemini-cli#-installation",
37
+ };
38
+ /** MCP server name for the run's permission prompts: distinct from a project-configured "easel" server */
39
+ export const PERMISSION_SERVER = "easel-chat";
15
40
  const fakeAgents = () => (process.env.DESIGN_CANVAS_AGENT_CMD ? JSON.parse(process.env.DESIGN_CANVAS_AGENT_CMD) : {});
16
41
 
17
42
  /** Model names passed to --model / -m: aliases or full ids only (they reach a shell on Windows) */
18
43
  export const validModel = (m) => (typeof m === "string" && /^[\w.:/[\]-]{1,100}$/.test(m.trim()) ? m.trim() : "");
19
44
 
20
- /** Agent launch command. Tests override it with DESIGN_CANVAS_AGENT_CMD='{"claude":["node","fake.mjs"]}' */
21
- export function agentCommand(agent, { prompt, resume, root, images = [], model = "" }) {
45
+ /** Inline --mcp-config for a Claude Code run: this package's MCP server with only the permission tool, bound to this canvas and run */
46
+ export function permissionMcpConfig({ port, runId }) {
47
+ const env = { DESIGN_CANVAS_PORT: String(port), EASEL_RUN_ID: runId };
48
+ return JSON.stringify({ mcpServers: { [PERMISSION_SERVER]: { type: "stdio", command: process.execPath, args: [path.join(TOOL_ROOT, "bin/mcp.mjs"), "--permission", "--port", String(port)], env } } });
49
+ }
50
+
51
+ /**
52
+ * Agent launch command. Tests override it with DESIGN_CANVAS_AGENT_CMD='{"claude":["node","fake.mjs"]}'.
53
+ * permission: { port, runId } routes Claude Code's permission prompts to the chat (anything else is refused in headless mode)
54
+ */
55
+ export function agentCommand(agent, { prompt, resume, root, images = [], model = "", permission = null }) {
22
56
  const override = fakeAgents()[agent];
23
57
  if (override) return { cmd: override[0], args: [...override.slice(1), prompt] };
24
58
  if (agent === "codex") {
25
59
  const common = ["--json", "--skip-git-repo-check", "-s", "workspace-write", ...(model ? ["-m", model] : []), ...images.flatMap((i) => ["-i", i])];
26
60
  return resume ? { cmd: "codex", args: ["exec", "resume", resume, ...common, prompt] } : { cmd: "codex", args: ["exec", ...common, "-C", root, prompt] };
27
61
  }
62
+ // Headless print mode needs --trust (no workspace prompt) and --force (otherwise edits are only proposed)
63
+ if (agent === "cursor")
64
+ return { cmd: AGENT_CLI.cursor, args: ["-p", "--output-format", "stream-json", "--stream-partial-output", "--trust", "--force", "--approve-mcps", ...(model ? ["--model", model] : []), ...(resume ? ["--resume", resume] : []), prompt] };
65
+ if (agent === "gemini") return { cmd: AGENT_CLI.gemini, args: ["-p", prompt, "--output-format", "stream-json", "--approval-mode", "auto_edit", ...(model ? ["-m", model] : []), ...(resume ? ["--resume", resume] : [])] };
28
66
  return {
29
67
  cmd: "claude",
30
- args: ["-p", prompt, "--output-format", "stream-json", "--verbose", "--include-partial-messages", "--permission-mode", "acceptEdits", "--allowedTools", "mcp__easel", "mcp__design-canvas", ...(model ? ["--model", model] : []), ...(resume ? ["--resume", resume] : [])],
68
+ args: [
69
+ "-p",
70
+ prompt,
71
+ "--output-format",
72
+ "stream-json",
73
+ "--verbose",
74
+ "--include-partial-messages",
75
+ "--permission-mode",
76
+ "acceptEdits",
77
+ "--allowedTools",
78
+ "mcp__easel",
79
+ "mcp__design-canvas",
80
+ ...(permission ? ["--mcp-config", permissionMcpConfig(permission), "--permission-prompt-tool", `mcp__${PERMISSION_SERVER}__permission`] : []),
81
+ ...(model ? ["--model", model] : []),
82
+ ...(resume ? ["--resume", resume] : []),
83
+ ],
31
84
  };
32
85
  }
33
86
 
@@ -57,10 +110,11 @@ function runQuick(cmd, args, ms = 5000) {
57
110
  });
58
111
  }
59
112
 
60
- /** Output of `claude auth status` / `codex login status` → ready | signin | unknown */
113
+ /** Output of `claude auth status` / `codex login status` / `cursor-agent status` → ready | signin | unknown */
61
114
  export function readiness(agent, r) {
62
115
  if (!r) return "unknown";
63
116
  if (agent === "codex") return r.code === 0 && /Logged in/.test(r.out) ? "ready" : "signin";
117
+ if (agent === "cursor") return /not logged in|not authenticated/i.test(r.out) ? "signin" : r.code === 0 && /logged in/i.test(r.out) ? "ready" : "unknown";
64
118
  try {
65
119
  const j = JSON.parse(r.out.slice(r.out.indexOf("{"), r.out.lastIndexOf("}") + 1));
66
120
  return j.loggedIn === true ? "ready" : j.loggedIn === false ? "signin" : "unknown";
@@ -71,16 +125,28 @@ export function readiness(agent, r) {
71
125
 
72
126
  const which = (c) => new Promise((r) => spawn(process.platform === "win32" ? "where" : "which", [c], { windowsHide: true }).on("close", (code) => r(code === 0)).on("error", () => r(false)));
73
127
 
128
+ /** Gemini CLI has no status command: an API key in the environment or saved Google sign-in counts as ready, anything else is unknown */
129
+ export function geminiReadiness(env = process.env, home = os.homedir()) {
130
+ if (env.GEMINI_API_KEY || env.GOOGLE_API_KEY || env.GOOGLE_GENAI_USE_VERTEXAI) return "ready";
131
+ return existsSync(path.join(home, ".gemini", "oauth_creds.json")) ? "ready" : "unknown";
132
+ }
133
+
74
134
  /** Whether an agent can run now: missing (not on PATH), signin, ready, unknown (status check failed or timed out) */
75
135
  export async function agentStatus(agent) {
76
136
  if (fakeAgents()[agent]) return "ready";
77
- if (!(await which(agent))) return "missing";
78
- return readiness(agent, await runQuick(agent, agent === "codex" ? ["login", "status"] : ["auth", "status"]));
137
+ if (!(await which(AGENT_CLI[agent]))) return "missing";
138
+ if (agent === "gemini") return geminiReadiness();
139
+ return readiness(agent, await runQuick(AGENT_CLI[agent], STATUS_ARGS[agent]));
79
140
  }
80
141
 
142
+ /** A custom command is ready when its program is on PATH (or an existing path) */
143
+ const customStatus = async (command) => {
144
+ const cmd = customArgv(command, "").cmd;
145
+ return (/[\\/]/.test(cmd) ? existsSync(cmd) : await which(cmd)) ? "ready" : "missing";
146
+ };
147
+
81
148
  /** Known causes of a failed run → { cause, text }: one plain sentence with the next step. The raw output goes under Details */
82
- export function classifyFailure({ agent, cmd = agent, text = "", code = null, signal = null, enoent = false, model = "" }) {
83
- const label = AGENT_LABEL[agent] ?? agent;
149
+ export function classifyFailure({ agent, cmd = agent, text = "", code = null, signal = null, enoent = false, model = "", label = AGENT_LABEL[agent] ?? agent }) {
84
150
  const t = String(text ?? "");
85
151
  if (enoent || /command not found|is not recognized as an internal or external command/i.test(t)) return { cause: "missing", text: `${cmd} command not found. Install it, then Check again.` };
86
152
  if (/usage limit|usage_limit_reached|rate limit/i.test(t)) {
@@ -97,7 +163,18 @@ export function classifyFailure({ agent, cmd = agent, text = "", code = null, si
97
163
  }
98
164
 
99
165
  /** Tools that only read (anything else may have changed files) */
100
- const READ_ONLY = /^(Read|Glob|Grep|LS|WebFetch|WebSearch|TodoWrite|Task|ToolSearch)$|(^|__)(list_|read_|get_|check_|screenshot)/;
166
+ const READ_ONLY = /^(Read|Glob|Grep|LS|WebFetch|WebSearch|TodoWrite|Task|ToolSearch|glob|search_file_content|google_web_search|web_fetch)$|(^|__)(list_|read_|get_|check_|screenshot)/;
167
+
168
+ /** Cursor tool_call payload ({ readToolCall: { args } }, { function: { name, arguments } }) → a tool event */
169
+ function cursorTool(tc) {
170
+ const [key, v] = Object.entries(tc ?? {}).find(([k]) => k.endsWith("ToolCall") || k === "function") ?? [];
171
+ if (!key) return { kind: "tool", name: "Tool" };
172
+ if (key === "function") return { kind: "tool", name: v?.name ?? "Tool", detail: short(v?.arguments) };
173
+ const base = key.replace(/ToolCall$/, "");
174
+ const name = base === "ls" ? "LS" : base.charAt(0).toUpperCase() + base.slice(1);
175
+ const a = v?.args ?? {};
176
+ return { kind: "tool", name: base === "mcp" ? (a.toolName ?? a.name ?? "MCP") : name, detail: short(a.path ?? a.command ?? a.globPattern ?? a.pattern ?? a.args ?? a) };
177
+ }
101
178
 
102
179
  const short = (v, n = 120) => {
103
180
  const s = typeof v === "string" ? v : JSON.stringify(v ?? "");
@@ -113,6 +190,33 @@ export function parseLine(agent, line, st) {
113
190
  return line.trim() ? [{ kind: "log", text: line.trim() }] : [];
114
191
  }
115
192
  const out = [];
193
+ if (agent === "cursor") {
194
+ // With --stream-partial-output text comes as assistant deltas (timestamp_ms), then once more as the whole message: that copy is skipped
195
+ if (o.type === "system" && o.subtype === "init") out.push({ kind: "session", id: o.session_id });
196
+ else if (o.type === "assistant") {
197
+ const text = (o.message?.content ?? []).filter((c) => c.type === "text").map((c) => c.text).join("");
198
+ if (o.timestamp_ms != null) {
199
+ st.seg = true;
200
+ if (text) out.push({ kind: "delta", text });
201
+ } else if (st.seg) st.seg = false;
202
+ else if (text) out.push({ kind: "text", text });
203
+ } else if (o.type === "tool_call" && o.subtype === "started") {
204
+ st.seg = false;
205
+ out.push(cursorTool(o.tool_call));
206
+ } else if (o.type === "result") out.push(o.is_error ? { kind: "error", text: o.result ?? o.subtype ?? "Failed" } : { kind: "done" });
207
+ else if (o.type === "error") out.push({ kind: "error", text: o.message ?? o.error?.message ?? "Failed" });
208
+ return out;
209
+ }
210
+ if (agent === "gemini") {
211
+ if (o.type === "init") out.push({ kind: "session", id: o.session_id });
212
+ else if (o.type === "message" && o.role === "assistant" && o.content) out.push(o.delta ? { kind: "delta", text: o.content } : { kind: "text", text: o.content });
213
+ else if (o.type === "tool_use") {
214
+ const a = o.parameters ?? {};
215
+ out.push({ kind: "tool", name: o.tool_name ?? "Tool", detail: short(a.file_path ?? a.absolute_path ?? a.path ?? a.command ?? a.pattern ?? a) });
216
+ } else if (o.type === "error") out.push(o.severity === "warning" ? { kind: "log", text: o.message } : { kind: "error", text: o.message ?? "Failed" });
217
+ else if (o.type === "result") out.push(o.status === "error" ? { kind: "error", text: o.error?.message ?? "Failed" } : { kind: "done" });
218
+ return out;
219
+ }
116
220
  if (agent === "codex") {
117
221
  if (o.type === "thread.started") out.push({ kind: "session", id: o.thread_id });
118
222
  else if (o.type === "item.started" || o.type === "item.completed") {
@@ -134,7 +238,7 @@ export function parseLine(agent, line, st) {
134
238
  } else if (o.type === "stream_event" && o.event?.type === "message_start") out.push({ kind: "break" });
135
239
  else if (o.type === "assistant") {
136
240
  for (const c of o.message?.content ?? []) {
137
- if (c.type === "tool_use") out.push({ kind: "tool", name: c.name, detail: short(c.input?.file_path ?? c.input?.path ?? c.input) });
241
+ if (c.type === "tool_use") out.push({ kind: "tool", name: c.name, detail: short(c.input?.file_path ?? c.input?.path ?? c.input?.command ?? c.input) });
138
242
  else if (c.type === "text" && !st.streamed) out.push({ kind: "text", text: c.text });
139
243
  }
140
244
  } else if (o.type === "result") out.push(o.is_error ? { kind: "error", text: o.result ?? o.subtype } : { kind: "done", cost: o.total_cost_usd });
@@ -177,6 +281,11 @@ export async function buildPrompt(ctx, body, state) {
177
281
  }
178
282
  const errs = Object.entries(state.errors).filter(([f]) => boards.includes(f));
179
283
  for (const [f, list] of errs) lines.push(`- ${f} error: ${list[0].message}${list[0].line ? ` (line ${list[0].line})` : ""}`);
284
+ for (const f of body.forks ?? []) {
285
+ const at = (x) => `${rel0 ? rel0 + "/" : ""}screens/${x}`;
286
+ const why = f.created === false ? `${at(f.of)} already has a fork of yours from an earlier run: ${at(f.file)}` : `${f.while} is editing ${at(f.of)} right now, so a fork was made for you: ${at(f.file)}`;
287
+ lines.push(`- ${why}. Make your changes in ${f.file}, not in ${f.of}.`);
288
+ }
180
289
  if (body.variants?.files?.length) {
181
290
  lines.push(`- Make ${body.variants.files.length} distinct variants of "${body.variants.base}". Copies have already been created side by side: ${body.variants.files.map((f) => `${rel0 ? rel0 + "/" : ""}screens/${f}`).join(", ")}. Take each file in a different direction, and use place_board to retitle each one like "Variant 1: summary". Do not modify the original.`);
182
291
  }
@@ -193,68 +302,99 @@ export async function buildPrompt(ctx, body, state) {
193
302
  return lines.join("\n");
194
303
  }
195
304
 
196
- /** y of the first row below the original where n variants do not overlap other boards */
197
- function freeRowY(board, b, n) {
198
- const w = (b.w + 80) * n;
199
- let y = b.y + b.h + 160;
200
- for (let k = 0; k < 200; k++) {
201
- const hit = Object.values(board.boards).filter((o) => o.x < b.x + w && o.x + o.w > b.x && o.y < y + b.h + 160 && o.y + o.h > y - 80);
202
- if (!hit.length) return y;
203
- y = Math.max(...hit.map((o) => o.y + o.h)) + 160;
204
- }
205
- return y;
206
- }
207
-
208
305
  const readJson = (p, d) => fs.readFile(p, "utf8").then(JSON.parse, () => d);
209
306
 
307
+ /** A request that changes per-user settings or answers for the user: only the app page itself (same-origin, with an Origin header) */
308
+ const fromBrowser = (req) => !!req.headers.origin && originAllowed(req.headers);
309
+
210
310
  export function chatRoutes({ getSelection } = {}) {
211
- const runs = new Map(); // id → { proc, agent, events, status }
311
+ const runs = new Map(); // id → { proc, agent, events, status, emit, changes, boards, label, undone }
212
312
  const state = { selection: null, context: null, errors: {} };
313
+ const perms = createPermissions();
314
+ /** Settles open permission requests as denied (run cancelled or ended, server closing) and says so in the chat */
315
+ const denyOpen = (runId) => {
316
+ for (const p of perms.denyAll(runId)) runs.get(p.run)?.emit?.({ kind: "permission-answered", id: p.id, decision: "deny" });
317
+ };
213
318
 
214
319
  return {
215
320
  state,
321
+ close: () => denyOpen(),
216
322
  routes: [
217
323
  [
218
324
  "POST",
219
325
  "/api/chat",
220
326
  async (req, res, url, ctx) => {
221
327
  const body = await readBody(req);
222
- const agent = body.agent === "codex" ? "codex" : "claude";
328
+ const custom = String(body.agent ?? "").startsWith("custom:") ? (await readCustom()).find((c) => `custom:${c.id}` === body.agent) : null;
329
+ if (String(body.agent ?? "").startsWith("custom:") && !custom) return sendJson(res, 400, { error: "That custom command is gone; pick another agent" });
330
+ const agent = custom ? body.agent : AGENTS.includes(body.agent) ? body.agent : "claude";
223
331
  if (!String(body.text ?? "").trim()) return sendJson(res, 400, { error: "Please enter a message" });
224
332
  state.selection = getSelection?.() ?? null;
225
- // N variants: create copies of the original side by side to the right
333
+ let id = `r${Date.now().toString(36)}`;
334
+ while (runs.has(id)) id = `r${(parseInt(id.slice(1), 36) + 1).toString(36)}`;
335
+ const label = custom?.name ?? AGENT_LABEL[agent];
336
+ // Pre-run copy on disk (before variant copies too): revertable even after a restart, no git needed
337
+ await ctx.store.exclusive(() => copyRun(ctx, id, { agent, label, request: String(body.text).slice(0, 200) })).catch((e) => console.error("run copy failed", e));
338
+ const request = String(body.text).trim().replace(/\s+/g, " ");
339
+ const historyLabel = `${label}: ${request.length > 40 ? request.slice(0, 40) + "…" : request}`;
340
+ // From here every change (variant copies included) joins the run's one undo step
341
+ ctx.history.beginRun({ id, label: historyLabel, by: label });
342
+ // N variants: create copies of the original side by side, in a row below it
226
343
  const n = Math.min(4, Math.max(0, Number(body.variants) || 0));
227
344
  if (n > 1) {
228
345
  const base = body.attach?.boards?.[0] ?? state.selection?.file;
229
- if (!base) return sendJson(res, 400, { error: "Select one board to make variants of" });
346
+ if (!base) {
347
+ ctx.history.endRun(id);
348
+ ctx.occupancy?.runEnded(id);
349
+ return sendJson(res, 400, { error: "Select one board to make variants of" });
350
+ }
230
351
  const html = await fs.readFile(path.join(ctx.store.screensDir, base), "utf8");
231
352
  const { board } = await ctx.store.syncBoard();
232
353
  const b = board.boards[base] ?? { x: 0, y: 0, w: 390, h: 844 };
233
354
  const stem = base.replace(/\.html$/, "");
234
- const files = await ctx.store.exclusive(() =>
235
- createBoards(
236
- ctx,
237
- Array.from({ length: n }, (_, i) => ({ file: `${stem}-v${i + 1}.html`, html, x: b.x + (b.w + 80) * i, y: freeRowY(board, b, n), w: b.w, h: b.h, title: `${b.title ?? stem} variant ${i + 1}`, page: b.page })),
238
- `Create ${n} variants ${base}`,
355
+ // In the first free row below the original (never on top of notes or boards); each one remembers where it came from
356
+ const spots = freeRow(board, b, n);
357
+ const origin = { kind: "variant", of: base, at: new Date().toISOString() };
358
+ const files = await requestScope.run({ ...requestScope.getStore(), run: id }, () =>
359
+ ctx.store.exclusive(() =>
360
+ createBoards(
361
+ ctx,
362
+ Array.from({ length: n }, (_, i) => ({ file: `${stem}-v${i + 1}.html`, html, ...spots[i], w: b.w, h: b.h, title: `${b.title ?? stem} variant ${i + 1}`, page: b.page, origin })),
363
+ `Create ${n} variants ${base}`,
364
+ ),
239
365
  ),
240
366
  );
241
367
  body.variants = { base, files };
242
368
  body.attach = { ...body.attach, boards: [base, ...files] };
243
- } else body.variants = undefined;
369
+ } else {
370
+ body.variants = undefined;
371
+ // A target board another agent is editing right now: this run works on a fork of it (one writer per board)
372
+ const targets = [...new Set([...(body.attach?.boards ?? []), ...(state.selection?.file ? [state.selection.file] : [])])].filter(boardFile);
373
+ const forks = [];
374
+ for (const f of targets) {
375
+ const r = await requestScope.run({ ...requestScope.getStore(), agent: label, run: id }, () => ctx.store.exclusive(() => routeWrite(ctx, f)));
376
+ if (r.forked) forks.push({ of: f, file: r.file, while: r.while ?? "another agent", created: r.created });
377
+ }
378
+ body.forks = forks;
379
+ if (forks.length) body.attach = { ...body.attach, boards: (body.attach?.boards ?? []).map((f) => forks.find((x) => x.of === f)?.file ?? f) };
380
+ }
244
381
  const prompt = await buildPrompt(ctx, body, state);
245
382
  const images = (body.attach?.refs ?? []).filter((r) => r.kind === "image").map((r) => path.join(ctx.dir, r.value));
246
- const model = validModel(body.model);
247
- const { cmd, args } = agentCommand(agent, { prompt, resume: body.resume, root: rootOf(ctx.dir), images, model });
248
- const id = `r${Date.now().toString(36)}`;
383
+ const model = custom ? "" : validModel(body.model);
384
+ const { cmd, args } = custom ? customArgv(custom.command, prompt) : agentCommand(agent, { prompt, resume: body.resume, root: rootOf(ctx.dir), images, model, permission: { port: req.socket.localPort, runId: id } });
249
385
  let proc;
250
386
  try {
251
- // Windows: claude/codex are .cmd wrappers so a shell is needed, and there is no process-group kill so detached is not used
387
+ // Windows: claude/codex are .cmd wrappers so a shell is needed, and there is no process-group kill so detached is not used.
388
+ // A custom command never goes through a shell: its arguments are passed as they are
252
389
  const win = process.platform === "win32";
253
- proc = spawn(cmd, win ? args.map(winQuote) : args, { cwd: rootOf(ctx.dir), stdio: ["ignore", "pipe", "pipe"], detached: !win, shell: win, windowsHide: true, env: { ...process.env, DESIGN_CANVAS_PORT: String(req.socket.localPort) } });
390
+ const shell = win && !custom;
391
+ proc = spawn(cmd, shell ? args.map(winQuote) : args, { cwd: rootOf(ctx.dir), stdio: ["ignore", "pipe", "pipe"], detached: !win, shell, windowsHide: true, env: { ...process.env, DESIGN_CANVAS_PORT: String(req.socket.localPort), EASEL_RUN_ID: id } });
254
392
  } catch (e) {
393
+ ctx.history.endRun(id);
394
+ ctx.occupancy?.runEnded(id);
255
395
  return sendJson(res, 500, { error: `Could not run ${cmd}: ${e.message}` });
256
396
  }
257
- const run = { proc, agent, events: [], status: "running", prompt };
397
+ const run = { proc, agent, events: [], status: "running", prompt, label: historyLabel, custom: !!custom };
258
398
  runs.set(id, run);
259
399
  // Show tool paths relative to the project (agents report absolute, sometimes symlink-resolved, paths)
260
400
  const roots = [rootOf(ctx.dir), await fs.realpath(rootOf(ctx.dir)).catch(() => null)].filter(Boolean).map((r) => r + path.sep).sort((a, b) => b.length - a.length); // longest first: /private/var/… before /var/…
@@ -263,42 +403,63 @@ export function chatRoutes({ getSelection } = {}) {
263
403
  const emit = (ev) => {
264
404
  if (typeof ev.detail === "string") for (const r of roots) ev.detail = ev.detail.split(r).join("");
265
405
  if (ev.kind === "tool" && !READ_ONLY.test(ev.name)) run.changed = true;
266
- if ((ev.kind === "error" && !ev.cause) || ev.kind === "log") seen.push(ev.text);
406
+ if ((ev.kind === "error" && !ev.cause) || ev.kind === "log" || ev.kind === "plain") seen.push(ev.text);
267
407
  run.events.push(ev);
268
408
  ctx.broadcast({ type: "chat", id, ev });
269
409
  };
410
+ run.emit = emit;
270
411
  const fail = ({ code = null, signal = null, enoent = false, message = "" }) => {
271
412
  const all = [...seen, err, message].join("\n").trim();
272
- const c = classifyFailure({ agent, cmd, text: all, code, signal, enoent, model });
273
- const shown = `$ ${cmd} ${args.filter((a) => a !== prompt).join(" ")}`.trim();
413
+ const c = classifyFailure({ agent, cmd, text: all, code, signal, enoent, model, label });
414
+ const shown = `$ ${cmd} ${args.filter((a) => a !== prompt && !a.includes(prompt)).join(" ")}`.trim();
274
415
  const raw = [shown, ...all.split("\n").slice(-20), code != null || signal ? `Exit code ${code ?? signal}` : ""].filter(Boolean).join("\n");
275
416
  emit({ kind: "error", text: c.text, cause: c.cause, raw, changed: !!run.changed });
276
417
  };
418
+ // At the end: diff the tracked files now (watcher events may still be pending), so the run's undo step is complete before `end`
419
+ const finish = async () => {
420
+ denyOpen(id);
421
+ const steps = await ctx.store
422
+ .exclusive(async () => {
423
+ await ctx.history.observe().catch((e) => console.error("run diff failed", e));
424
+ ctx.history.endRun(id);
425
+ ctx.occupancy?.runEnded(id);
426
+ return ctx.history.runSteps(id);
427
+ })
428
+ .catch(() => []);
429
+ if (steps.length) ctx.broadcast({ type: "history-changed" });
430
+ run.changes = mergeSteps(steps);
431
+ run.boards = runBoards(run.changes, ctx.store.screensDir);
432
+ const rel = (p) => toPosix(path.relative(ctx.store.screensDir, p));
433
+ const changed = [...new Set(steps.flatMap((s) => s.changes.map((c) => c.path)).filter((p) => p.endsWith(".html") && !rel(p).startsWith("..")).map(rel))];
434
+ return { changed, step: steps.length > 0, boards: run.boards };
435
+ };
277
436
  emit({ kind: "start", agent, prompt, variants: body.variants?.files });
278
437
  const st = {};
279
438
  let buf = "";
439
+ // A custom command's output is shown as plain text, line by line
440
+ const parse = (line) => (custom ? [{ kind: "plain", text: line.replace(/\r$/, "") }] : parseLine(agent, line, st));
280
441
  proc.stdout.on("data", (d) => {
281
442
  buf += d;
282
443
  let i;
283
444
  while ((i = buf.indexOf("\n")) >= 0) {
284
445
  const line = buf.slice(0, i);
285
446
  buf = buf.slice(i + 1);
286
- for (const ev of parseLine(agent, line, st)) emit(ev);
447
+ for (const ev of parse(line)) emit(ev);
287
448
  }
288
449
  });
289
450
  let err = "";
290
451
  proc.stderr.on("data", (d) => (err += d).length > 4000 && (err = err.slice(-4000)));
291
- proc.on("error", (e) => {
452
+ proc.on("error", async (e) => {
292
453
  run.status = "error";
293
454
  fail({ enoent: e.code === "ENOENT", message: e.message });
294
- emit({ kind: "end", status: "error" });
455
+ emit({ kind: "end", status: "error", ...(await finish()) });
295
456
  });
296
- proc.on("close", (code, signal) => {
457
+ proc.on("close", async (code, signal) => {
297
458
  if (run.status === "error") return;
298
- if (buf.trim()) for (const ev of parseLine(agent, buf, st)) emit(ev);
459
+ if (buf.trim()) for (const ev of parse(buf)) emit(ev);
299
460
  run.status = run.cancelled ? "cancelled" : code === 0 ? "done" : "error";
300
461
  if (run.status === "error") fail({ code, signal });
301
- emit({ kind: "end", status: run.status });
462
+ emit({ kind: "end", status: run.status, ...(await finish()) });
302
463
  });
303
464
  sendJson(res, 200, { id, variants: body.variants?.files ?? [] });
304
465
  },
@@ -311,6 +472,7 @@ export function chatRoutes({ getSelection } = {}) {
311
472
  const run = runs.get(id);
312
473
  if (!run || run.status !== "running") return sendJson(res, 404, { error: "Not running" });
313
474
  run.cancelled = true;
475
+ denyOpen(id);
314
476
  try {
315
477
  if (process.platform === "win32") spawn("taskkill", ["/pid", String(run.proc.pid), "/T", "/F"], { windowsHide: true });
316
478
  else process.kill(-run.proc.pid, "SIGTERM"); // the whole process group
@@ -321,13 +483,161 @@ export function chatRoutes({ getSelection } = {}) {
321
483
  },
322
484
  ],
323
485
  ["GET", "/api/chat", async (req, res, url) => sendJson(res, 200, { events: runs.get(url.searchParams.get("id"))?.events ?? [] })],
324
- // Readiness per agent, checked on every call (the app asks when the AI tab opens and on Check again)
486
+ // Claude Code asks (through bin/mcp.mjs --permission, header X-Easel-Run): a card in the chat, or an answer right away when
487
+ // a remembered "Always allow" rule covers it. The MCP tool then polls GET until the user answers
488
+ [
489
+ "POST",
490
+ "/api/chat/permission",
491
+ async (req, res, url, ctx) => {
492
+ const b = await readBody(req);
493
+ const runId = requestScope.getStore()?.run;
494
+ const run = runs.get(runId);
495
+ if (!run || run.status !== "running" || run.agent !== "claude") return sendJson(res, 200, { behavior: "deny", message: "No Easel run is waiting for this request" });
496
+ const tool = String(b.tool_name ?? "");
497
+ const input = b.input && typeof b.input === "object" ? b.input : {};
498
+ const p = perms.request(runId, tool, input);
499
+ const rule = permissionRule(tool, input);
500
+ run.emit({ kind: "permission", id: p.id, ...describePermission(tool, input, { root: rootOf(ctx.dir), dir: ctx.dir }), rule: rule?.label ?? null, ...(p.decision ? { decision: p.decision } : {}) });
501
+ sendJson(res, 200, p.decision ? toolAnswer(p.decision, input) : { id: p.id, pending: true });
502
+ },
503
+ ],
504
+ [
505
+ "GET",
506
+ "/api/chat/permission",
507
+ async (req, res, url) => {
508
+ const id = url.searchParams.get("id") ?? "";
509
+ const d = await perms.wait(id, Math.min(25000, Number(url.searchParams.get("ms")) || 25000));
510
+ sendJson(res, 200, d ? toolAnswer(d, perms.pending.get(id)?.input) : { id, pending: true });
511
+ },
512
+ ],
513
+ [
514
+ "POST",
515
+ "/api/chat/permission/answer",
516
+ async (req, res) => {
517
+ if (!fromBrowser(req)) return sendJson(res, 403, { error: "Only the Easel page can answer a permission request" });
518
+ const { id, decision } = await readBody(req);
519
+ const p = perms.answer(id, decision);
520
+ if (!p) return sendJson(res, 409, { error: "This request is no longer waiting" });
521
+ runs.get(p.run)?.emit?.({ kind: "permission-answered", id: p.id, decision });
522
+ sendJson(res, 200, { ok: true });
523
+ },
524
+ ],
525
+ // Puts the tracked files back as they were before a run, as one undo step. Works from the disk copy, so also after a restart
526
+ [
527
+ "POST",
528
+ "/api/chat/revert",
529
+ async (req, res, url, ctx) => {
530
+ const { id } = await readBody(req);
531
+ if (runs.get(id)?.status === "running") return sendJson(res, 409, { error: "The run is still going; cancel it first" });
532
+ const r = await revertRun(ctx, id);
533
+ if (!r) return sendJson(res, 404, { error: "No copy of that run is left (only the newest 10 are kept)" });
534
+ ctx.broadcast({ type: "board-changed", source: "server:revert" });
535
+ ctx.broadcast({ type: "history-changed" });
536
+ const rel = (p) => toPosix(path.relative(ctx.store.screensDir, p));
537
+ sendJson(res, 200, { ok: true, label: `Revert ${r.meta.label ?? "AI"} run`, changed: r.changes.map((c) => c.path).filter((p) => p.endsWith(".html")).map(rel) });
538
+ },
539
+ ],
540
+ // Undo this run: a plain undo when its step is the newest, else only its own files (409 with the boards changed since,
541
+ // unless mode is "rest" or "all"). Either way one history step, so Cmd+Z brings it back
542
+ [
543
+ "POST",
544
+ "/api/chat/undo-run",
545
+ async (req, res, url, ctx) => {
546
+ const { id, mode } = await readBody(req);
547
+ const run = runs.get(id);
548
+ if (!run || !run.changes) return sendJson(res, 404, { error: "This run's changes are no longer in the undo history" });
549
+ if (run.status === "running") return sendJson(res, 409, { error: "The run is still going; cancel it first" });
550
+ if (run.undone) return sendJson(res, 409, { error: "This run is already undone" });
551
+ await ctx.history.observe();
552
+ const steps = ctx.history.runSteps(id);
553
+ const top = ctx.history.peek().undo;
554
+ const onTop = top && ((steps.length === 1 && top === steps[0]) || top.redoOf === id) ? 1 : 0;
555
+ const r = await undoChanges(ctx, { onTop, changes: run.changes, mode, label: `Undo ${run.label}`, mark: { undoOf: id } });
556
+ if (r.conflicts) return sendJson(res, 409, { conflicts: r.conflicts, error: "Some boards changed since this run" });
557
+ run.undone = true;
558
+ await ctx.store.syncBoardNow();
559
+ ctx.broadcast({ type: "board-changed", source: "server:undo-run" });
560
+ ctx.broadcast({ type: "history-changed" });
561
+ run.emit({ kind: "run-undo", undone: true });
562
+ sendJson(res, 200, { ok: true, boards: run.boards.length });
563
+ },
564
+ ],
565
+ [
566
+ "POST",
567
+ "/api/chat/redo-run",
568
+ async (req, res, url, ctx) => {
569
+ const { id, mode } = await readBody(req);
570
+ const run = runs.get(id);
571
+ if (!run?.undone || !run.changes) return sendJson(res, 409, { error: "This run is not undone" });
572
+ await ctx.history.observe();
573
+ const pk = ctx.history.peek();
574
+ if (pk.redo?.run === id) await ctx.history.redo();
575
+ else if (pk.undo?.undoOf === id) {
576
+ await ctx.history.undo();
577
+ await dropMissingAutoPlaced(ctx);
578
+ } else {
579
+ const r = await applyRunChanges(ctx, run.changes, "redo", { mode: ["rest", "all"].includes(mode) ? mode : undefined, label: `Redo ${run.label}`, mark: { redoOf: id } });
580
+ if (r.conflicts) return sendJson(res, 409, { conflicts: r.conflicts, error: "Some boards changed since the undo" });
581
+ }
582
+ run.undone = false;
583
+ await ctx.store.syncBoardNow(); // screens the run created are back: place them now (the watcher may see only a change)
584
+ ctx.broadcast({ type: "board-changed", source: "server:redo-run" });
585
+ ctx.broadcast({ type: "history-changed" });
586
+ run.emit({ kind: "run-undo", undone: false });
587
+ sendJson(res, 200, { ok: true, boards: run.boards.length });
588
+ },
589
+ ],
590
+ // What the chat can still do for earlier runs: undo (this server's history) or restore the pre-run copy (saved time; null when pruned)
591
+ [
592
+ "GET",
593
+ "/api/chat/runs",
594
+ async (req, res, url, ctx) => {
595
+ const ids = (url.searchParams.get("ids") ?? "").split(",").filter((x) => /^r[0-9a-z]+$/.test(x)).slice(0, 200);
596
+ const out = {};
597
+ for (const id of ids) {
598
+ const run = runs.get(id);
599
+ out[id] = { live: !!run?.changes, undone: !!run?.undone, status: run?.status ?? null, copy: await runCopyInfo(ctx.dir, id) };
600
+ }
601
+ sendJson(res, 200, { boot: ctx.boot, runs: out });
602
+ },
603
+ ],
604
+ // Read-only: a screen as it was before a run (Compare's "before"), with a <base> so its assets resolve like the live screen
605
+ [
606
+ "GET",
607
+ "/api/chat/run-file",
608
+ async (req, res, url, ctx) => {
609
+ const f = url.searchParams.get("f") ?? "";
610
+ const html = await readRunFile(ctx.dir, url.searchParams.get("id"), f);
611
+ if (html == null) return sendJson(res, 404, { error: "No copy of that screen for this run" });
612
+ const out = withBase(html, f.slice("screens/".length));
613
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Content-Length": Buffer.byteLength(out), "Cache-Control": "no-store" });
614
+ res.end(out);
615
+ },
616
+ ],
617
+ // Readiness per agent plus the user's custom commands, checked on every call (the app asks when the AI tab opens and on Check again)
325
618
  [
326
619
  "GET",
327
620
  "/api/agents",
328
621
  async (req, res) => {
329
- const agents = await Promise.all(["claude", "codex"].map(async (id) => ({ id, label: AGENT_LABEL[id], status: await agentStatus(id) })));
330
- sendJson(res, 200, { agents: agents.map((a) => ({ ...a, ok: a.status !== "missing" })) });
622
+ const agents = await Promise.all(AGENTS.map(async (id) => ({ id, label: AGENT_LABEL[id], status: await agentStatus(id), install: INSTALL_URL[id] })));
623
+ const custom = await Promise.all((await readCustom()).map(async (c) => ({ id: `custom:${c.id}`, label: c.name, command: c.command, custom: true, status: await customStatus(c.command) })));
624
+ sendJson(res, 200, { agents: [...agents, ...custom].map((a) => ({ ...a, ok: a.status !== "missing" })), checkedAt: new Date().toISOString() });
625
+ },
626
+ ],
627
+ // Custom commands are stored per user (EASEL_HOME), only from the app page
628
+ [
629
+ "POST",
630
+ "/api/agents/custom",
631
+ async (req, res) => {
632
+ if (!fromBrowser(req)) return sendJson(res, 403, { error: "Custom commands can only be added from the Easel page" });
633
+ const b = await readBody(req);
634
+ if (b.action === "delete") {
635
+ await removeCustom(String(b.id ?? "").replace(/^custom:/, ""));
636
+ return sendJson(res, 200, { ok: true });
637
+ }
638
+ const r = await addCustom(b);
639
+ if (r.error) return sendJson(res, 400, { error: r.error });
640
+ sendJson(res, 200, { agent: { id: `custom:${r.agent.id}`, label: r.agent.name, command: r.agent.command, custom: true, status: await customStatus(r.agent.command), ok: true } });
331
641
  },
332
642
  ],
333
643
  // Upload references: stored in docs/design/.refs/ (kept out of the repo by .gitignore)