easel-canvas 0.1.1 → 0.2.1

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