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/index.mjs CHANGED
@@ -7,11 +7,17 @@ import path from "node:path";
7
7
  import chokidar from "chokidar";
8
8
  import { WebSocketServer } from "ws";
9
9
 
10
+ import { cleanAgent } from "./agents.mjs";
10
11
  import { TOOL_ROOT } from "./args.mjs";
11
12
  import { createBoardStore } from "./board.mjs";
12
- import { createHistory } from "./history.mjs";
13
+ import { isTrackedRel } from "./copies.mjs";
14
+ import { rootOf, toPosix } from "./fsutil.mjs";
15
+ import { createHistory, requestScope } from "./history.mjs";
16
+ import { createOccupancy } from "./occupancy.mjs";
17
+ import { writeEntry } from "./registry.mjs";
18
+ import { checkUpdate } from "./update.mjs";
13
19
 
14
- const MIME = {
20
+ export const MIME = {
15
21
  ".html": "text/html; charset=utf-8",
16
22
  ".css": "text/css; charset=utf-8",
17
23
  ".js": "text/javascript; charset=utf-8",
@@ -45,6 +51,38 @@ export async function readBody(req, limit = 4 * 1024 * 1024) {
45
51
  return raw ? JSON.parse(raw) : {};
46
52
  }
47
53
 
54
+ /** Host names a browser uses for this local server; anything else is a DNS-rebinding page */
55
+ const LOCAL_HOST = /^(localhost|127\.0\.0\.1|\[::1\]|[a-z0-9.-]+\.localhost)(:\d+)?$/i;
56
+
57
+ /**
58
+ * State-changing requests and the WebSocket: refused when they come from another web page in the user's browser.
59
+ * No Origin header (CLI, MCP server, curl) or the page's own origin is allowed; the Host must be a local name.
60
+ */
61
+ export function originAllowed(headers) {
62
+ const host = String(headers.host ?? "");
63
+ if (!LOCAL_HOST.test(host)) return false;
64
+ const o = headers.origin;
65
+ if (o == null) return true;
66
+ try {
67
+ const u = new URL(o);
68
+ return (u.protocol === "http:" || u.protocol === "https:") && u.host.toLowerCase() === host.toLowerCase();
69
+ } catch {
70
+ return false; // "null" (sandboxed frames, file://) and anything unparsable
71
+ }
72
+ }
73
+
74
+ /** Who sent a request: agent and in-app run (MCP, chat runs), browser id and person's name (the app; the name is URI-encoded so any script fits a header) */
75
+ export function scopeOf(headers) {
76
+ const h = (k) => cleanAgent(headers[k]) || undefined;
77
+ let person = headers["x-easel-author"];
78
+ try {
79
+ person = person == null ? undefined : decodeURIComponent(String(person));
80
+ } catch {
81
+ /* not encoded: kept as sent */
82
+ }
83
+ return { agent: h("x-easel-agent"), run: h("x-easel-run"), client: h("x-easel-client"), person: cleanAgent(person) || undefined };
84
+ }
85
+
48
86
  /** Allow only paths inside dir (blocks ../ escapes) */
49
87
  export function safeJoin(root, rel) {
50
88
  const p = path.resolve(root, "." + path.posix.normalize("/" + rel));
@@ -86,10 +124,11 @@ async function serveFile(res, file) {
86
124
  }
87
125
  }
88
126
 
89
- /** Rebuild if files under app/ are newer than dist/index.html */
127
+ /** Rebuild if files under app/ are newer than dist/index.html, or the export viewer (dist/viewer) is missing */
90
128
  async function appIsStale(distDir) {
91
129
  const built = await fs.stat(path.join(distDir, "index.html")).catch(() => null);
92
130
  if (!built) return true;
131
+ if (existsSync(path.join(TOOL_ROOT, "app")) && !existsSync(path.join(distDir, "viewer", "viewer.js"))) return true;
93
132
  let newest = 0;
94
133
  const walk = async (d) => {
95
134
  for (const e of await fs.readdir(d, { withFileTypes: true })) {
@@ -105,10 +144,69 @@ async function appIsStale(distDir) {
105
144
  return newest > built.mtimeMs;
106
145
  }
107
146
 
108
- export async function createServer({ dir, port, dev = true, extraRoutes = [] }) {
147
+ /** Listens on 127.0.0.1:port; with autoPort a busy port moves on to the next ones (up to +20). Resolves to the port used */
148
+ export async function listen(server, port, autoPort = false) {
149
+ for (let p = port; ; p++) {
150
+ try {
151
+ await new Promise((resolve, reject) => {
152
+ const fail = (e) => {
153
+ server.off("listening", ok);
154
+ reject(e);
155
+ };
156
+ const ok = () => {
157
+ server.off("error", fail);
158
+ resolve();
159
+ };
160
+ server.once("error", fail);
161
+ server.once("listening", ok);
162
+ server.listen(p, "127.0.0.1");
163
+ });
164
+ return p;
165
+ } catch (e) {
166
+ if (e.code !== "EADDRINUSE") throw e;
167
+ if (!autoPort) throw Object.assign(new Error(`Port ${p} is already in use. Pick another with --port <n>, or leave --port out to use the next free one.`), { code: "EADDRINUSE" });
168
+ if (p >= port + 20) throw Object.assign(new Error(`Ports ${port}–${p} are all in use. Pick one with --port <n>.`), { code: "EADDRINUSE" });
169
+ }
170
+ }
171
+ }
172
+
173
+ /** Tracked for undo of outside changes: every .html under screens/ (any depth) and board.json */
174
+ function trackedFiles(store) {
175
+ const rel = (p) => toPosix(path.relative(store.screensDir, p));
176
+ return {
177
+ list: async () => [...(await store.listScreenFiles()).map((f) => path.join(store.screensDir, f)), store.boardPath],
178
+ isTracked: (p) => p === store.boardPath || (p.endsWith(".html") && !rel(p).startsWith("..") && !rel(p).split("/").some((s) => s.startsWith("."))),
179
+ name: (p) => (p === store.boardPath ? "board.json" : rel(p)),
180
+ };
181
+ }
182
+
183
+ /** Who wrote a board, from a history step: an agent (MCP or an in-app run) starts or keeps holding it; a change found on disk with no
184
+ * author keeps an agent that claimed the board busy; a board file that is gone has nobody on it */
185
+ function noteWriters(occupancy, screensDir, step, changes) {
186
+ for (const c of changes) {
187
+ const rel = toPosix(path.relative(screensDir, c.path));
188
+ if (!c.path.endsWith(".html") || rel.startsWith("..")) continue;
189
+ if (c.after == null) occupancy.forget(rel);
190
+ else if (step.by) occupancy.agentWrite(rel, step.by, { run: step.run, client: step.client, before: c.before });
191
+ else if (step.outside) occupancy.touch(rel);
192
+ }
193
+ }
194
+
195
+ /**
196
+ * register: write the running-canvas entry (~/.easel/servers/<port>.json, or under EASEL_HOME) for MCP discovery.
197
+ * autoPort: when the port is busy, try the next ones instead of failing (for a port the user did not choose).
198
+ * updateCheck: ask the npm registry once a day whether a newer Easel exists (the CLI only; see update.mjs).
199
+ */
200
+ export async function createServer({ dir, port, dev = true, extraRoutes = [], autoPort = false, register = false, updateCheck = false }) {
109
201
  if (!existsSync(dir)) throw new Error(`Design folder not found: ${dir}`);
110
- const store = createBoardStore(dir);
111
- const ctx = { dir, store, history: createHistory(), broadcast: () => {} };
202
+ let history;
203
+ const store = createBoardStore(dir, { onWrite: (p, text) => history.note(p, text) });
204
+ // Who is on which board: in memory, sent to every browser when it changes
205
+ const occupancy = createOccupancy({ onChange: (boards) => ctx.broadcast({ type: "occupancy", boards }) });
206
+ history = createHistory({ ...trackedFiles(store), onStep: (step, changes) => noteWriters(occupancy, store.screensDir, step, changes) });
207
+ // boot: when this server started; the chat shows "Easel restarted" when it changes (the undo history did not survive)
208
+ const ctx = { dir, store, history, occupancy, broadcast: () => {}, boot: new Date().toISOString() };
209
+ await history.seed();
112
210
 
113
211
  // App UI: on startup, build once if the app source is newer than dist, then serve dist statically.
114
212
  // (The Vite dev server is not used: even with HMR off it injects a websocket client that causes console errors)
@@ -116,18 +214,25 @@ export async function createServer({ dir, port, dev = true, extraRoutes = [] })
116
214
  if (dev && (await appIsStale(distDir))) {
117
215
  const { build } = await import("vite");
118
216
  await build({ root: path.join(TOOL_ROOT, "app"), configFile: path.join(TOOL_ROOT, "vite.config.mjs"), logLevel: "warn" });
217
+ // Second entry: the view-only viewer that Share › Export copies next to the screens (the first build empties dist/)
218
+ await build({ root: path.join(TOOL_ROOT, "app"), configFile: path.join(TOOL_ROOT, "vite.config.mjs"), logLevel: "warn", mode: "viewer" });
119
219
  }
120
220
  if (!existsSync(path.join(distDir, "index.html"))) throw new Error("No app build found (running with npm start creates it)");
121
221
 
122
- const LOCKED = /^\/api\/(board|boards\/|history\/|edit|undo|redo|place|notes|pages|comments)/;
222
+ const LOCKED = /^\/api\/(board|boards\/|history\/|edit|undo|redo|place|notes|pages|comments|chat\/(revert|undo-run|redo-run))/;
223
+ // Screens folder as the agent sees it: relative to the project root
224
+ const screensRel = toPosix(path.relative(rootOf(dir), store.screensDir)) || "screens";
225
+ // Started now, answered by /api/update: never in the way of start-up, resolves to null when there is nothing to say
226
+ const update = updateCheck ? checkUpdate({ current: JSON.parse(await fs.readFile(path.join(TOOL_ROOT, "package.json"), "utf8")).version }) : Promise.resolve(null);
123
227
  const routes = [
124
- ["GET", "/api/health", async (req, res) => sendJson(res, 200, { ok: true, dir })],
228
+ ["GET", "/api/update", async (req, res) => sendJson(res, 200, { update: await update })],
229
+ ["GET", "/api/health", async (req, res) => sendJson(res, 200, { ok: true, dir, root: rootOf(dir), screens: screensRel, pid: process.pid })],
125
230
  [
126
231
  "GET",
127
232
  "/api/board",
128
233
  async (req, res) => {
129
234
  const { board, files, missing } = await store.syncBoard();
130
- sendJson(res, 200, { board, files, missing, dir });
235
+ sendJson(res, 200, { board, files, missing, dir, screens: screensRel });
131
236
  },
132
237
  ],
133
238
  [
@@ -161,8 +266,10 @@ export async function createServer({ dir, port, dev = true, extraRoutes = [] })
161
266
  res.writeHead(404);
162
267
  return res.end("not found");
163
268
  }
269
+ if (req.method !== "GET" && req.method !== "HEAD" && url.pathname.startsWith("/api/") && !originAllowed(req.headers)) return sendJson(res, 403, { error: "Cross-origin request refused" });
164
270
  for (const [m, p, h] of routes) {
165
- if (req.method === m && url.pathname === p) return await h(req, res, url);
271
+ // Who sent a write (MCP clients send their agent name, in-app runs their run id): read by history.push
272
+ if (req.method === m && url.pathname === p) return await requestScope.run(scopeOf(req.headers), () => h(req, res, url));
166
273
  }
167
274
  if (url.pathname.startsWith("/api/")) return sendJson(res, 404, { error: "Unknown API" });
168
275
  if (url.pathname.startsWith("/_app/")) {
@@ -191,7 +298,28 @@ export async function createServer({ dir, port, dev = true, extraRoutes = [] })
191
298
  }
192
299
  });
193
300
 
194
- const wss = new WebSocketServer({ server, path: "/ws" });
301
+ const wss = new WebSocketServer({ server, path: "/ws", verifyClient: ({ req }) => originAllowed(req.headers) });
302
+ wss.on("error", () => {}); // ws re-emits the http server's errors; a busy port is handled by listen()
303
+ let conns = 0;
304
+ wss.on("connection", (c) => {
305
+ const conn = `w${++conns}`;
306
+ c.send(JSON.stringify({ type: "hello", boot: ctx.boot }));
307
+ c.send(JSON.stringify({ type: "occupancy", boards: occupancy.snapshot() }));
308
+ // The app says which board this tab is editing (an element selected on it, or none); a closed tab leaves it
309
+ c.on("message", (data) => {
310
+ let m;
311
+ try {
312
+ m = JSON.parse(String(data));
313
+ } catch {
314
+ return;
315
+ }
316
+ if (m?.type !== "editing") return;
317
+ const file = m.file == null ? null : isTrackedRel(`screens/${m.file}`) ? m.file : undefined;
318
+ if (file === undefined) return;
319
+ occupancy.personEdit(conn, file, { client: cleanAgent(m.client) || undefined, person: cleanAgent(m.person) || undefined });
320
+ });
321
+ c.on("close", () => occupancy.personEdit(conn, null));
322
+ });
195
323
  ctx.broadcast = (msg) => {
196
324
  const data = JSON.stringify(msg);
197
325
  for (const c of wss.clients) if (c.readyState === 1) c.send(data);
@@ -203,16 +331,25 @@ export async function createServer({ dir, port, dev = true, extraRoutes = [] })
203
331
  appWatcher.on("all", () => ctx.broadcast({ type: "app-changed" }));
204
332
  }
205
333
 
206
- await new Promise((resolve, reject) => {
207
- server.once("error", reject);
208
- server.listen(port, "127.0.0.1", resolve);
209
- });
334
+ let used;
335
+ try {
336
+ used = await listen(server, port, autoPort);
337
+ } catch (e) {
338
+ await appWatcher?.close();
339
+ throw e;
340
+ }
341
+ const unregister = register ? writeEntry({ port: used, dir, root: rootOf(dir) }) : () => {};
210
342
 
211
343
  return {
212
344
  ctx,
213
345
  server,
214
- url: `http://localhost:${port}`,
346
+ port: used,
347
+ url: `http://localhost:${used}`,
348
+ update,
349
+ unregister,
215
350
  async close() {
351
+ unregister();
352
+ occupancy.close();
216
353
  await appWatcher?.close();
217
354
  for (const c of wss.clients) c.terminate();
218
355
  wss.close();
@@ -0,0 +1,183 @@
1
+ // AI-generated with Claude Code, 2026-11-12, reviewed by Hyun Park
2
+ // Who is on which board right now, kept in memory only (nothing is written to the project). An agent holds a board from its first
3
+ // write: an in-app chat run until the run ends, an MCP client until QUIET_MS pass without another write or until it disconnects;
4
+ // then it shows as done for DONE_MS. A person holds a board while a browser has an element selected on it (closing the tab releases it).
5
+
6
+ /** An MCP client that has not written for this long is no longer editing */
7
+ export const QUIET_MS = 45000;
8
+ /** How long "Claude Code · done 13:52" stays above a board */
9
+ export const DONE_MS = 30 * 60 * 1000;
10
+
11
+ /**
12
+ * onChange(snapshot) runs after every change someone can see (a writer starts or finishes, a person enters or leaves); a write
13
+ * that only keeps a holder busy does not call it
14
+ */
15
+ export function createOccupancy({ quietMs = QUIET_MS, doneMs = DONE_MS, onChange = () => {} } = {}) {
16
+ /** file → { base, holders: Map<key, holder> } — holder: { key, kind, by | person, client, runs, clients, conns, since, quietUntil, doneAt, timer } */
17
+ const files = new Map();
18
+ const conns = new Map(); // WebSocket id → { file, key }
19
+ const changed = () => onChange(snapshot());
20
+ const timer = (fn, ms) => {
21
+ const t = setTimeout(fn, ms);
22
+ t.unref?.();
23
+ return t;
24
+ };
25
+
26
+ const rec = (file) => {
27
+ let r = files.get(file);
28
+ if (!r) files.set(file, (r = { base: null, holders: new Map() }));
29
+ return r;
30
+ };
31
+ const active = (h) => h.kind === "person" || (!h.doneAt && (h.runs.size > 0 || h.quietUntil > Date.now()));
32
+ const agentsOn = (file) => [...(files.get(file)?.holders.values() ?? [])].filter((h) => h.kind === "agent" && active(h));
33
+ const drop = (file, key) => {
34
+ const r = files.get(file);
35
+ const h = r?.holders.get(key);
36
+ if (!h) return;
37
+ clearTimeout(h.timer);
38
+ r.holders.delete(key);
39
+ if (!r.holders.size) files.delete(file);
40
+ };
41
+
42
+ /** Marks h done (or schedules the check for when its quiet time is over) */
43
+ function settle(file, h) {
44
+ clearTimeout(h.timer);
45
+ if (h.runs.size || h.doneAt) return;
46
+ const left = h.quietUntil - Date.now();
47
+ if (left > 0) return void (h.timer = timer(() => settle(file, h), left + 5));
48
+ h.doneAt = Date.now();
49
+ h.timer = timer(() => {
50
+ drop(file, h.key);
51
+ changed();
52
+ }, doneMs);
53
+ changed();
54
+ }
55
+
56
+ /**
57
+ * An agent wrote (or is about to write) a board. run: the in-app run it belongs to (held until runEnded); client: the MCP client
58
+ * (held until it goes quiet or disconnects); before: the board's content before this write (kept as the fork base when it starts
59
+ * the board's first hold)
60
+ */
61
+ function agentWrite(file, by, { run, client, before } = {}) {
62
+ const r = rec(file);
63
+ if (!agentsOn(file).length) r.base = before ?? r.base;
64
+ const key = `a:${by}`;
65
+ let h = r.holders.get(key);
66
+ const fresh = !h || !active(h);
67
+ if (!h) r.holders.set(key, (h = { key, kind: "agent", by, runs: new Set(), clients: new Set(), since: Date.now(), quietUntil: 0, doneAt: null, timer: null }));
68
+ if (fresh) {
69
+ clearTimeout(h.timer); // the timer that would drop the done label
70
+ h.since = Date.now();
71
+ h.doneAt = null;
72
+ }
73
+ if (run) h.runs.add(run);
74
+ else {
75
+ if (client) h.clients.add(client);
76
+ h.quietUntil = Date.now() + quietMs;
77
+ clearTimeout(h.timer);
78
+ h.timer = timer(() => settle(file, h), quietMs + 5);
79
+ }
80
+ if (fresh) changed();
81
+ return h;
82
+ }
83
+
84
+ /** A write nobody claimed landed on a board an agent holds (its own file tools after claim_board): that agent stays busy */
85
+ function touch(file) {
86
+ for (const h of agentsOn(file))
87
+ if (!h.runs.size) {
88
+ h.quietUntil = Date.now() + quietMs;
89
+ clearTimeout(h.timer);
90
+ h.timer = timer(() => settle(file, h), quietMs + 5);
91
+ }
92
+ }
93
+
94
+ function runEnded(run) {
95
+ for (const [file, r] of [...files])
96
+ for (const h of [...r.holders.values()])
97
+ if (h.runs.delete(run) && !h.runs.size) settle(file, h); // done now, unless the same agent also wrote over MCP within its quiet time
98
+ }
99
+
100
+ /** An MCP client disconnected: boards it alone kept busy are done now */
101
+ function clientGone(client) {
102
+ for (const [file, r] of [...files])
103
+ for (const h of [...r.holders.values()])
104
+ if (h.clients.delete(client) && !h.clients.size && !h.runs.size && !h.doneAt) {
105
+ h.quietUntil = 0;
106
+ settle(file, h);
107
+ }
108
+ }
109
+
110
+ /** A browser (WebSocket conn) selected an element on file, or let go (file null); who: { client, person } */
111
+ function personEdit(conn, file, who = {}) {
112
+ const cur = conns.get(conn);
113
+ if (cur?.file === file) return;
114
+ let any = false;
115
+ if (cur) {
116
+ const h = files.get(cur.file)?.holders.get(cur.key);
117
+ h?.conns.delete(conn);
118
+ if (h && !h.conns.size) drop(cur.file, cur.key);
119
+ conns.delete(conn);
120
+ any = true;
121
+ }
122
+ if (file) {
123
+ const key = `p:${who.client || conn}`;
124
+ const r = rec(file);
125
+ let h = r.holders.get(key);
126
+ if (!h) r.holders.set(key, (h = { key, kind: "person", person: who.person || undefined, client: who.client || undefined, conns: new Set(), since: Date.now() }));
127
+ h.conns.add(conn);
128
+ conns.set(conn, { file, key });
129
+ any = true;
130
+ }
131
+ if (any) changed();
132
+ }
133
+
134
+ /** The board's file is gone (trashed, deleted): nobody is on it any more */
135
+ function forget(file) {
136
+ const r = files.get(file);
137
+ if (!r) return;
138
+ for (const h of r.holders.values()) clearTimeout(h.timer);
139
+ for (const [c, v] of [...conns]) if (v.file === file) conns.delete(c);
140
+ files.delete(file);
141
+ changed();
142
+ }
143
+
144
+ /** What browsers draw: per board, its holders (editing or done), oldest first */
145
+ function snapshot() {
146
+ const out = {};
147
+ for (const [file, r] of files) {
148
+ const list = [...r.holders.values()]
149
+ .sort((a, b) => a.since - b.since)
150
+ .map((h) => ({
151
+ key: h.key,
152
+ kind: h.kind,
153
+ ...(h.by ? { by: h.by } : {}),
154
+ ...(h.person ? { person: h.person } : {}),
155
+ ...(h.client ? { client: h.client } : {}),
156
+ state: active(h) ? "editing" : "done",
157
+ since: h.since,
158
+ ...(h.doneAt && !active(h) ? { doneAt: h.doneAt } : {}),
159
+ }));
160
+ if (list.length) out[file] = list;
161
+ }
162
+ return out;
163
+ }
164
+
165
+ return {
166
+ agentWrite,
167
+ touch,
168
+ runEnded,
169
+ clientGone,
170
+ personEdit,
171
+ forget,
172
+ snapshot,
173
+ /** Agents editing file now (people never count: they are never forked) */
174
+ agentsOn: (file) => agentsOn(file).map((h) => ({ by: h.by, since: h.since })),
175
+ /** The board as it was when its current writer started, if known */
176
+ base: (file) => (agentsOn(file).length ? (files.get(file)?.base ?? null) : null),
177
+ close() {
178
+ for (const r of files.values()) for (const h of r.holders.values()) clearTimeout(h.timer);
179
+ files.clear();
180
+ conns.clear();
181
+ },
182
+ };
183
+ }
@@ -0,0 +1,141 @@
1
+ // AI-generated with Claude Code, 2026-11-11, reviewed by Hyun Park
2
+ // Permission requests from an in-app Claude Code run (--permission-prompt-tool): what the card shows, the "Always allow" rule,
3
+ // and the pending requests per run that the MCP permission tool waits on. Always-allow rules live in memory only (never in the project).
4
+ import { realpathSync } from "node:fs";
5
+ import path from "node:path";
6
+
7
+ import { toPosix } from "./fsutil.mjs";
8
+
9
+ /** Shell operators and substitutions: a command with any of these never gets an "Always allow" rule */
10
+ export const SHELL_OPERATORS = /[;&|<>`\n\r]|\$\(/;
11
+
12
+ const FILE_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
13
+
14
+ /** Resolved path (/var → /private/var), also for a file that does not exist yet: its nearest existing parent */
15
+ const real = (p) => {
16
+ try {
17
+ return realpathSync(p);
18
+ } catch {
19
+ const up = path.dirname(p);
20
+ return up === p ? p : path.join(real(up), path.basename(p));
21
+ }
22
+ };
23
+ const inside = (p, dir) => {
24
+ const rel = path.relative(dir, p);
25
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
26
+ };
27
+ /** Path as shown on the card: relative to the project when inside it (agents report resolved paths), else as requested */
28
+ const shownPath = (asked, abs, root) => (inside(abs, root) ? toPosix(path.relative(root, abs)) || "." : asked);
29
+
30
+ /** Programs that run whatever follows them, and flags that take code to run: two words of these would cover any command */
31
+ const WRAPPERS = new Set(["sh", "bash", "zsh", "fish", "dash", "ksh", "env", "xargs", "sudo", "doas", "eval", "exec", "command", "nohup", "time", "nice", "timeout", "watch", "ssh"]);
32
+ const CODE_FLAG = /^-{1,2}(c|e|p|eval|exec|command)$/;
33
+
34
+ /**
35
+ * "Always allow" rule for a request: the tool name, or "Bash <first two words>"; null when none may be offered.
36
+ * Never for file tools: the run already edits inside the project without asking (acceptEdits), so a request for one is a file
37
+ * outside it or a protected one, and a rule by tool name would open every such path.
38
+ */
39
+ export function permissionRule(tool, input) {
40
+ const name = String(tool ?? "");
41
+ if (!name || FILE_TOOLS.has(name)) return null;
42
+ if (name !== "Bash") return { rule: name, label: name };
43
+ const cmd = String(input?.command ?? "").trim();
44
+ if (!cmd || SHELL_OPERATORS.test(cmd)) return null;
45
+ const [first, second] = cmd.split(/\s+/);
46
+ if (WRAPPERS.has(first.split("/").pop()) || (second && CODE_FLAG.test(second))) return null;
47
+ const words = [first, second].filter(Boolean).join(" ");
48
+ return { rule: `Bash ${words}`, label: words };
49
+ }
50
+
51
+ /** Whether a request falls under a remembered rule (Bash rules match the first two words of an operator-free command) */
52
+ export const ruleMatches = (rules, tool, input) => {
53
+ const r = permissionRule(tool, input);
54
+ return !!r && rules.has(r.rule);
55
+ };
56
+
57
+ /**
58
+ * What the card shows, taken from the request as is: what (command | edit | fetch | tool), subject (the exact command,
59
+ * file path, URL, or the input as JSON), the working folder, and whether a file path is outside the design folder
60
+ */
61
+ export function describePermission(tool, input, { root, dir }) {
62
+ const name = String(tool ?? "");
63
+ const inp = input && typeof input === "object" ? input : {};
64
+ const where = root;
65
+ if (name === "Bash") return { what: "command", tool: name, subject: String(inp.command ?? ""), where };
66
+ if (FILE_TOOLS.has(name) && (inp.file_path || inp.notebook_path)) {
67
+ const asked = path.resolve(root, String(inp.file_path ?? inp.notebook_path));
68
+ const abs = real(asked);
69
+ return { what: "edit", tool: name, subject: shownPath(asked, abs, real(root)), where, outside: !inside(abs, real(dir)) };
70
+ }
71
+ if (name === "WebFetch" && inp.url) return { what: "fetch", tool: name, subject: String(inp.url), where };
72
+ return { what: "tool", tool: name, subject: JSON.stringify(inp, null, 1), where };
73
+ }
74
+
75
+ /**
76
+ * Pending requests: request(run, tool, input) → { id, decided? }; wait(id, ms) resolves to the decision or null on timeout;
77
+ * answer(id, decision) settles it. Decisions are allow-once | always | deny. Rules are remembered for this server process only.
78
+ */
79
+ export function createPermissions() {
80
+ const rules = new Set();
81
+ const pending = new Map(); // id → { id, run, tool, input, decision, waiters: [] }
82
+ let n = 0;
83
+
84
+ const settle = (p, decision) => {
85
+ if (p.decision) return false;
86
+ p.decision = decision;
87
+ for (const w of p.waiters.splice(0)) w(decision);
88
+ setTimeout(() => pending.delete(p.id), 60000).unref?.(); // a late poll still gets the answer
89
+ return true;
90
+ };
91
+
92
+ return {
93
+ rules,
94
+ pending,
95
+ /** New request; when a remembered rule covers it the decision is already "always" */
96
+ request(run, tool, input) {
97
+ const id = `p${Date.now().toString(36)}${(n++).toString(36)}`;
98
+ const p = { id, run, tool, input, decision: null, waiters: [] };
99
+ pending.set(id, p);
100
+ if (ruleMatches(rules, tool, input)) settle(p, "always");
101
+ return p;
102
+ },
103
+ /** Resolves to the decision, or null when none came within ms (the MCP tool asks again) */
104
+ wait(id, ms = 25000) {
105
+ const p = pending.get(id);
106
+ if (!p) return Promise.resolve("deny");
107
+ if (p.decision) return Promise.resolve(p.decision);
108
+ return new Promise((resolve) => {
109
+ const t = setTimeout(() => {
110
+ p.waiters.splice(p.waiters.indexOf(done), 1);
111
+ resolve(null);
112
+ }, ms);
113
+ const done = (d) => {
114
+ clearTimeout(t);
115
+ resolve(d);
116
+ };
117
+ p.waiters.push(done);
118
+ });
119
+ },
120
+ /** Settles an open request; "always" also remembers its rule. false when unknown or already answered */
121
+ answer(id, decision) {
122
+ const p = pending.get(id);
123
+ if (!p || !["once", "always", "deny"].includes(decision)) return null;
124
+ if (decision === "always") {
125
+ const r = permissionRule(p.tool, p.input);
126
+ if (!r) return null;
127
+ rules.add(r.rule);
128
+ }
129
+ return settle(p, decision) ? p : null;
130
+ },
131
+ /** Denies every open request (of one run, or all): cancel, run end, server close */
132
+ denyAll(run) {
133
+ const out = [];
134
+ for (const p of pending.values()) if (!p.decision && (!run || p.run === run) && settle(p, "deny")) out.push(p);
135
+ return out;
136
+ },
137
+ };
138
+ }
139
+
140
+ /** The answer Claude Code expects back from the permission prompt tool */
141
+ export const toolAnswer = (decision, input) => (decision === "once" || decision === "always" ? { behavior: "allow", updatedInput: input ?? {} } : { behavior: "deny", message: "The user denied this in Easel" });
@@ -0,0 +1,87 @@
1
+ // AI-generated with Claude Code, 2026-11-12, reviewed by Hyun Park
2
+ // Where the server puts a new board (auto-placed screens, duplicates, forks, the chat's variants): the first free spot that covers
3
+ // neither another board nor a note on the same page. Note sizes are estimated from their text, as the canvas draws them.
4
+
5
+ export const GAP_X = 80;
6
+ export const GAP_Y = 120;
7
+ /** Clearance kept around boards and notes (board labels and tags sit above a board) */
8
+ const CLEAR = 80;
9
+
10
+ /** Rough width of one character at a font size: wide scripts (CJK, Hangul) take a full em */
11
+ const charW = (ch, size) => ((ch.codePointAt(0) ?? 0) >= 0x2e80 ? size : size * 0.6);
12
+ const textW = (line, size) => [...line].reduce((w, ch) => w + charW(ch, size), 0);
13
+
14
+ /** A note's box on the canvas (sticky: 20px side padding and 1.45 line height at 22px; title: max-content up to maxW at 1.1 line height) */
15
+ export function noteRect(n) {
16
+ const text = String(n.text ?? "");
17
+ if (n.kind === "title") {
18
+ const size = n.size ?? 72;
19
+ const maxW = n.maxW ?? 4000;
20
+ const lines = text.split("\n");
21
+ const w = Math.min(maxW, Math.max(size, ...lines.map((l) => textW(l, size))));
22
+ const rows = lines.reduce((k, l) => k + Math.max(1, Math.ceil(textW(l, size) / maxW)), 0);
23
+ return { x: n.x, y: n.y, w, h: n.maxH || rows * size * 1.1 };
24
+ }
25
+ const size = n.size ?? 22;
26
+ const w = n.w ?? 320;
27
+ const inner = Math.max(40, w - 40);
28
+ const rows = text.split("\n").reduce((k, l) => k + Math.max(1, Math.ceil(textW(l, size) / inner)), 0);
29
+ return { x: n.x, y: n.y, w, h: n.h || rows * size * 1.45 + 32 };
30
+ }
31
+
32
+ /** Boards and notes on a page (items without page are on the first page) as boxes, leaving out the files in ignore */
33
+ export function obstacles(board, page, ignore = []) {
34
+ const first = board.pages?.[0]?.id;
35
+ const on = (it) => !board.pages?.length || (it.page ?? first) === (page ?? first);
36
+ const boxes = Object.entries(board.boards ?? {})
37
+ .filter(([f, b]) => !ignore.includes(f) && on(b))
38
+ .map(([, b]) => ({ x: b.x, y: b.y, w: b.w, h: b.h }));
39
+ for (const n of Object.values(board.notes ?? {})) if (on(n)) boxes.push(noteRect(n));
40
+ return boxes;
41
+ }
42
+
43
+ const hits = (r, o) => r.x < o.x + o.w + CLEAR && r.x + r.w + CLEAR > o.x && r.y < o.y + o.h + CLEAR && r.y + r.h + CLEAR > o.y;
44
+
45
+ /**
46
+ * The first spot for rect (x, y, w, h) that is clear of the page's boards and notes, moving right past whatever is in the way
47
+ * (dir "right": a fork, a duplicate, the next auto-placed screen) or down (dir "down": a row of variants, a new row)
48
+ */
49
+ export function freeSpot(board, rect, { dir = "right", page, ignore = [] } = {}) {
50
+ const obs = obstacles(board, page, ignore);
51
+ const r = { x: Math.round(rect.x), y: Math.round(rect.y), w: rect.w, h: rect.h };
52
+ for (let k = 0; k < 1000; k++) {
53
+ const hit = obs.filter((o) => hits(r, o));
54
+ if (!hit.length) return r;
55
+ if (dir === "down") r.y = Math.round(Math.max(...hit.map((o) => o.y + o.h)) + GAP_Y);
56
+ else r.x = Math.round(Math.max(...hit.map((o) => o.x + o.w)) + GAP_X);
57
+ }
58
+ return r;
59
+ }
60
+
61
+ /** Spot for a copy that belongs next to board o (a fork): right of it when that is free, otherwise the nearer of further right and below */
62
+ export function besideSpot(board, o) {
63
+ const x = o.x + o.w + GAP_X;
64
+ const right = freeSpot(board, { x, y: o.y, w: o.w, h: o.h }, { dir: "right", page: o.page });
65
+ if (right.x === Math.round(x)) return right;
66
+ const down = freeSpot(board, { x: o.x, y: o.y + o.h + GAP_Y, w: o.w, h: o.h }, { dir: "down", page: o.page });
67
+ return down.y - o.y < right.x - o.x ? down : right;
68
+ }
69
+
70
+ /** Spot for a new screen: right of the last auto-placed board, otherwise a new row below everything; either way clear of boards and notes */
71
+ export function placeNew(board, size, page) {
72
+ const all = Object.values(board.boards);
73
+ const auto = all.filter((b) => b.autoPlaced);
74
+ if (auto.length) {
75
+ const last = auto.reduce((a, b) => (b.x > a.x ? b : a));
76
+ return freeSpot(board, { x: last.x + last.w + GAP_X, y: last.y, ...size }, { dir: "right", page });
77
+ }
78
+ const bottom = all.reduce((m, b) => Math.max(m, b.y + b.h), 0);
79
+ const left = all.reduce((m, b) => Math.min(m, b.x), 0);
80
+ return freeSpot(board, { x: left, y: bottom + GAP_Y, ...size }, { dir: "down", page });
81
+ }
82
+
83
+ /** A row of n copies of board b (variants): the first free row below it */
84
+ export function freeRow(board, b, n) {
85
+ const r = freeSpot(board, { x: b.x, y: b.y + b.h + GAP_Y, w: n * b.w + (n - 1) * GAP_X, h: b.h }, { dir: "down", page: b.page });
86
+ return Array.from({ length: n }, (_, i) => ({ x: r.x + (b.w + GAP_X) * i, y: r.y }));
87
+ }