easel-canvas 0.1.0 → 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,28 +1,181 @@
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 { readBody, sendJson } from "./index.mjs";
10
- import { readTokens } from "./tokens.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";
23
+ import { NO_TOKENS_NOTE, readTokens } from "./tokens.mjs";
11
24
 
12
- /** Agent launch command. Tests override it with DESIGN_CANVAS_AGENT_CMD='{"claude":["node","fake.mjs"]}' */
13
- function agentCommand(agent, { prompt, resume, root, images }) {
14
- const override = process.env.DESIGN_CANVAS_AGENT_CMD ? JSON.parse(process.env.DESIGN_CANVAS_AGENT_CMD)[agent] : null;
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";
40
+ const fakeAgents = () => (process.env.DESIGN_CANVAS_AGENT_CMD ? JSON.parse(process.env.DESIGN_CANVAS_AGENT_CMD) : {});
41
+
42
+ /** Model names passed to --model / -m: aliases or full ids only (they reach a shell on Windows) */
43
+ export const validModel = (m) => (typeof m === "string" && /^[\w.:/[\]-]{1,100}$/.test(m.trim()) ? m.trim() : "");
44
+
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 }) {
56
+ const override = fakeAgents()[agent];
15
57
  if (override) return { cmd: override[0], args: [...override.slice(1), prompt] };
16
58
  if (agent === "codex") {
17
- const common = ["--json", "--skip-git-repo-check", "-s", "workspace-write", ...images.flatMap((i) => ["-i", i])];
59
+ const common = ["--json", "--skip-git-repo-check", "-s", "workspace-write", ...(model ? ["-m", model] : []), ...images.flatMap((i) => ["-i", i])];
18
60
  return resume ? { cmd: "codex", args: ["exec", "resume", resume, ...common, prompt] } : { cmd: "codex", args: ["exec", ...common, "-C", root, prompt] };
19
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] : [])] };
20
66
  return {
21
67
  cmd: "claude",
22
- args: ["-p", prompt, "--output-format", "stream-json", "--verbose", "--include-partial-messages", "--permission-mode", "acceptEdits", "--allowedTools", "mcp__easel", "mcp__design-canvas", ...(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
+ ],
23
84
  };
24
85
  }
25
86
 
87
+ /** Runs a short command; null when it cannot start or takes longer than ms */
88
+ function runQuick(cmd, args, ms = 5000) {
89
+ return new Promise((resolve) => {
90
+ const win = process.platform === "win32";
91
+ let out = "";
92
+ let p;
93
+ try {
94
+ p = spawn(cmd, win ? args.map(winQuote) : args, { shell: win, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
95
+ } catch {
96
+ return resolve(null);
97
+ }
98
+ const done = (v) => {
99
+ clearTimeout(t);
100
+ resolve(v);
101
+ };
102
+ const t = setTimeout(() => {
103
+ p.kill();
104
+ done(null);
105
+ }, ms);
106
+ p.stdout.on("data", (d) => (out += d));
107
+ p.stderr.on("data", (d) => (out += d));
108
+ p.on("error", () => done(null));
109
+ p.on("close", (code) => done({ code, out }));
110
+ });
111
+ }
112
+
113
+ /** Output of `claude auth status` / `codex login status` / `cursor-agent status` → ready | signin | unknown */
114
+ export function readiness(agent, r) {
115
+ if (!r) return "unknown";
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";
118
+ try {
119
+ const j = JSON.parse(r.out.slice(r.out.indexOf("{"), r.out.lastIndexOf("}") + 1));
120
+ return j.loggedIn === true ? "ready" : j.loggedIn === false ? "signin" : "unknown";
121
+ } catch {
122
+ return "unknown";
123
+ }
124
+ }
125
+
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)));
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
+
134
+ /** Whether an agent can run now: missing (not on PATH), signin, ready, unknown (status check failed or timed out) */
135
+ export async function agentStatus(agent) {
136
+ if (fakeAgents()[agent]) return "ready";
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]));
140
+ }
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
+
148
+ /** Known causes of a failed run → { cause, text }: one plain sentence with the next step. The raw output goes under Details */
149
+ export function classifyFailure({ agent, cmd = agent, text = "", code = null, signal = null, enoent = false, model = "", label = AGENT_LABEL[agent] ?? agent }) {
150
+ const t = String(text ?? "");
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.` };
152
+ if (/usage limit|usage_limit_reached|rate limit/i.test(t)) {
153
+ const at = /try again at\s+(.+?)(?:\.(?=\s|"|$)|"|\n|$)/i.exec(t)?.[1]?.trim();
154
+ return { cause: "limit", text: `${label} hit its usage limit. Try again ${at ? `after ${at}` : "later"}, or switch agent.` };
155
+ }
156
+ if (/model/i.test(t) && /not supported|not found|unknown|invalid|does not exist|not available/i.test(t)) {
157
+ const name = model || /model\W{0,3}["'`]([^"'`\s]+)["'`]/i.exec(t)?.[1] || "";
158
+ return { cause: "model", text: `${name ? `Model "${name}"` : "This model"} is not available to this account. Pick another model, or the CLI default.` };
159
+ }
160
+ if (/not logged in|please run \/login|authenticat|\blog ?in\b/i.test(t)) return { cause: "signin", text: `${label} is not signed in. Run \`${LOGIN_CMD[agent] ?? `${cmd} login`}\`, then Retry.` };
161
+ if ((code != null && code !== 0) || signal) return { cause: "crash", text: `${label} stopped unexpectedly (exit ${code ?? signal}). Retry; if it repeats, copy Details into an issue.` };
162
+ return { cause: "other", text: t.trim().split("\n")[0] || "Failed" };
163
+ }
164
+
165
+ /** Tools that only read (anything else may have changed files) */
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
+ }
178
+
26
179
  const short = (v, n = 120) => {
27
180
  const s = typeof v === "string" ? v : JSON.stringify(v ?? "");
28
181
  return s.length > n ? s.slice(0, n) + "…" : s;
@@ -37,6 +190,33 @@ export function parseLine(agent, line, st) {
37
190
  return line.trim() ? [{ kind: "log", text: line.trim() }] : [];
38
191
  }
39
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
+ }
40
220
  if (agent === "codex") {
41
221
  if (o.type === "thread.started") out.push({ kind: "session", id: o.thread_id });
42
222
  else if (o.type === "item.started" || o.type === "item.completed") {
@@ -58,7 +238,7 @@ export function parseLine(agent, line, st) {
58
238
  } else if (o.type === "stream_event" && o.event?.type === "message_start") out.push({ kind: "break" });
59
239
  else if (o.type === "assistant") {
60
240
  for (const c of o.message?.content ?? []) {
61
- 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) });
62
242
  else if (c.type === "text" && !st.streamed) out.push({ kind: "text", text: c.text });
63
243
  }
64
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 });
@@ -68,9 +248,6 @@ export function parseLine(agent, line, st) {
68
248
  /** Windows shell argument: wrap in double quotes and double any inner double quotes */
69
249
  export const winQuote = (a) => (/^[\w./:=-]+$/.test(a) ? a : `"${String(a).replace(/"/g, '""')}"`);
70
250
 
71
- /** Repo root: two levels up for docs/design, otherwise (temp folders in tests) the folder itself */
72
- const rootOf = (dir) => (dir.endsWith(path.join("docs", "design")) ? path.resolve(dir, "../..") : dir);
73
-
74
251
  /** Context block */
75
252
  export async function buildPrompt(ctx, body, state) {
76
253
  const { board } = await ctx.store.syncBoard();
@@ -104,13 +281,18 @@ export async function buildPrompt(ctx, body, state) {
104
281
  }
105
282
  const errs = Object.entries(state.errors).filter(([f]) => boards.includes(f));
106
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
+ }
107
289
  if (body.variants?.files?.length) {
108
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.`);
109
291
  }
110
- // Design tokens from the design folder (tokens.json, or the built-in defaults)
292
+ // Design tokens from tokens.json. Without one the AI gets no default palette, only "keep to the file's styles"
111
293
  const tk = await readTokens(ctx.dir);
112
294
  const palette = Object.entries(tk.themes?.[tk.active] ?? {}).map(([n, v]) => `${n} ${v}`).join(", ");
113
- const tokenRule = `Use the design tokens (theme "${tk.active}"${tk.registered ? "" : ", defaults"}): colors ${palette}; font sizes ${tk.fontSizes.join("/")}px; radii ${tk.radii.join("/")}px; spacing in multiples of 4; font ${tk.fontFamily}. Check with check_tokens if available.`;
295
+ const tokenRule = tk.registered ? `Use the design tokens (theme "${tk.active}"): colors ${palette}; font sizes ${tk.fontSizes.join("/")}px; radii ${tk.radii.join("/")}px; spacing in multiples of 4; font ${tk.fontFamily}. Check with check_tokens if available.` : NO_TOKENS_NOTE;
114
296
  lines.push(
115
297
  `Rules: Only edit design files inside ${rel}/screens. Change only what is asked and leave everything else as is. New screens must include <meta name="board-size" content="390x844">; after creating one, use place_board to set its name and position. ${tokenRule}`,
116
298
  "",
@@ -120,100 +302,164 @@ export async function buildPrompt(ctx, body, state) {
120
302
  return lines.join("\n");
121
303
  }
122
304
 
123
- /** y of the first row below the original where n variants do not overlap other boards */
124
- function freeRowY(board, b, n) {
125
- const w = (b.w + 80) * n;
126
- let y = b.y + b.h + 160;
127
- for (let k = 0; k < 200; k++) {
128
- 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);
129
- if (!hit.length) return y;
130
- y = Math.max(...hit.map((o) => o.y + o.h)) + 160;
131
- }
132
- return y;
133
- }
134
-
135
305
  const readJson = (p, d) => fs.readFile(p, "utf8").then(JSON.parse, () => d);
136
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
+
137
310
  export function chatRoutes({ getSelection } = {}) {
138
- const runs = new Map(); // id → { proc, agent, events, status }
311
+ const runs = new Map(); // id → { proc, agent, events, status, emit, changes, boards, label, undone }
139
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
+ };
140
318
 
141
319
  return {
142
320
  state,
321
+ close: () => denyOpen(),
143
322
  routes: [
144
323
  [
145
324
  "POST",
146
325
  "/api/chat",
147
326
  async (req, res, url, ctx) => {
148
327
  const body = await readBody(req);
149
- 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";
150
331
  if (!String(body.text ?? "").trim()) return sendJson(res, 400, { error: "Please enter a message" });
151
332
  state.selection = getSelection?.() ?? null;
152
- // 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
153
343
  const n = Math.min(4, Math.max(0, Number(body.variants) || 0));
154
344
  if (n > 1) {
155
345
  const base = body.attach?.boards?.[0] ?? state.selection?.file;
156
- 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
+ }
157
351
  const html = await fs.readFile(path.join(ctx.store.screensDir, base), "utf8");
158
352
  const { board } = await ctx.store.syncBoard();
159
353
  const b = board.boards[base] ?? { x: 0, y: 0, w: 390, h: 844 };
160
354
  const stem = base.replace(/\.html$/, "");
161
- const files = await ctx.store.exclusive(() =>
162
- createBoards(
163
- ctx,
164
- 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 })),
165
- `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
+ ),
166
365
  ),
167
366
  );
168
367
  body.variants = { base, files };
169
368
  body.attach = { ...body.attach, boards: [base, ...files] };
170
- } 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
+ }
171
381
  const prompt = await buildPrompt(ctx, body, state);
172
382
  const images = (body.attach?.refs ?? []).filter((r) => r.kind === "image").map((r) => path.join(ctx.dir, r.value));
173
- const { cmd, args } = agentCommand(agent, { prompt, resume: body.resume, root: rootOf(ctx.dir), images });
174
- 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 } });
175
385
  let proc;
176
386
  try {
177
- // 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
178
389
  const win = process.platform === "win32";
179
- 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 } });
180
392
  } catch (e) {
393
+ ctx.history.endRun(id);
394
+ ctx.occupancy?.runEnded(id);
181
395
  return sendJson(res, 500, { error: `Could not run ${cmd}: ${e.message}` });
182
396
  }
183
- const run = { proc, agent, events: [], status: "running", prompt };
397
+ const run = { proc, agent, events: [], status: "running", prompt, label: historyLabel, custom: !!custom };
184
398
  runs.set(id, run);
185
399
  // Show tool paths relative to the project (agents report absolute, sometimes symlink-resolved, paths)
186
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/…
401
+ // What a failure is classified from, and shown under Details: error events, non-JSON output, stderr (never the prompt)
402
+ const seen = [];
187
403
  const emit = (ev) => {
188
404
  if (typeof ev.detail === "string") for (const r of roots) ev.detail = ev.detail.split(r).join("");
405
+ if (ev.kind === "tool" && !READ_ONLY.test(ev.name)) run.changed = true;
406
+ if ((ev.kind === "error" && !ev.cause) || ev.kind === "log" || ev.kind === "plain") seen.push(ev.text);
189
407
  run.events.push(ev);
190
408
  ctx.broadcast({ type: "chat", id, ev });
191
409
  };
410
+ run.emit = emit;
411
+ const fail = ({ code = null, signal = null, enoent = false, message = "" }) => {
412
+ const all = [...seen, err, message].join("\n").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();
415
+ const raw = [shown, ...all.split("\n").slice(-20), code != null || signal ? `Exit code ${code ?? signal}` : ""].filter(Boolean).join("\n");
416
+ emit({ kind: "error", text: c.text, cause: c.cause, raw, changed: !!run.changed });
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
+ };
192
436
  emit({ kind: "start", agent, prompt, variants: body.variants?.files });
193
437
  const st = {};
194
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));
195
441
  proc.stdout.on("data", (d) => {
196
442
  buf += d;
197
443
  let i;
198
444
  while ((i = buf.indexOf("\n")) >= 0) {
199
445
  const line = buf.slice(0, i);
200
446
  buf = buf.slice(i + 1);
201
- for (const ev of parseLine(agent, line, st)) emit(ev);
447
+ for (const ev of parse(line)) emit(ev);
202
448
  }
203
449
  });
204
450
  let err = "";
205
451
  proc.stderr.on("data", (d) => (err += d).length > 4000 && (err = err.slice(-4000)));
206
- proc.on("error", (e) => {
452
+ proc.on("error", async (e) => {
207
453
  run.status = "error";
208
- emit({ kind: "error", text: e.code === "ENOENT" ? `${cmd} command not found. Install it and sign in.` : e.message });
209
- emit({ kind: "end", status: "error" });
454
+ fail({ enoent: e.code === "ENOENT", message: e.message });
455
+ emit({ kind: "end", status: "error", ...(await finish()) });
210
456
  });
211
- proc.on("close", (code, signal) => {
457
+ proc.on("close", async (code, signal) => {
212
458
  if (run.status === "error") return;
213
- 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);
214
460
  run.status = run.cancelled ? "cancelled" : code === 0 ? "done" : "error";
215
- if (run.status === "error") emit({ kind: "error", text: err.trim().split("\n").slice(-3).join("\n") || `Exit code ${code ?? signal}` });
216
- emit({ kind: "end", status: run.status });
461
+ if (run.status === "error") fail({ code, signal });
462
+ emit({ kind: "end", status: run.status, ...(await finish()) });
217
463
  });
218
464
  sendJson(res, 200, { id, variants: body.variants?.files ?? [] });
219
465
  },
@@ -226,6 +472,7 @@ export function chatRoutes({ getSelection } = {}) {
226
472
  const run = runs.get(id);
227
473
  if (!run || run.status !== "running") return sendJson(res, 404, { error: "Not running" });
228
474
  run.cancelled = true;
475
+ denyOpen(id);
229
476
  try {
230
477
  if (process.platform === "win32") spawn("taskkill", ["/pid", String(run.proc.pid), "/T", "/F"], { windowsHide: true });
231
478
  else process.kill(-run.proc.pid, "SIGTERM"); // the whole process group
@@ -236,13 +483,161 @@ export function chatRoutes({ getSelection } = {}) {
236
483
  },
237
484
  ],
238
485
  ["GET", "/api/chat", async (req, res, url) => sendJson(res, 200, { events: runs.get(url.searchParams.get("id"))?.events ?? [] })],
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)
239
618
  [
240
619
  "GET",
241
620
  "/api/agents",
242
621
  async (req, res) => {
243
- 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)));
244
- const fake = process.env.DESIGN_CANVAS_AGENT_CMD ? Object.keys(JSON.parse(process.env.DESIGN_CANVAS_AGENT_CMD)) : [];
245
- sendJson(res, 200, { agents: [{ id: "claude", label: "Claude Code", ok: fake.includes("claude") || (await which("claude")) }, { id: "codex", label: "Codex", ok: fake.includes("codex") || (await which("codex")) }] });
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 } });
246
641
  },
247
642
  ],
248
643
  // Upload references: stored in docs/design/.refs/ (kept out of the repo by .gitignore)