easel-canvas 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,110 @@
1
+ // AI-generated with Claude Code, 2026-11-10, reviewed by Hyun Park
2
+ // Running canvases: each app server writes <EASEL_HOME or ~/.easel>/servers/<port>.json, and the MCP server
3
+ // picks the one for the project it was started in, so agent configs need no --port.
4
+ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+
8
+ import { DEFAULT_PORT } from "./args.mjs";
9
+
10
+ export const easelHome = (env = process.env) => env.EASEL_HOME || path.join(os.homedir(), ".easel");
11
+ const serversDir = (home) => path.join(home, "servers");
12
+ /** Resolved path (links like /var → /private/var), also for a folder that does not exist yet: its nearest existing parent */
13
+ const real = (p) => {
14
+ const abs = path.resolve(p);
15
+ try {
16
+ return realpathSync(abs);
17
+ } catch {
18
+ const up = path.dirname(abs);
19
+ return up === abs ? abs : path.join(real(up), path.basename(abs));
20
+ }
21
+ };
22
+
23
+ /** Records a listening canvas; returns the remover (removes only our own entry) */
24
+ export function writeEntry({ port, dir, root, pid = process.pid }, home = easelHome()) {
25
+ const d = serversDir(home);
26
+ mkdirSync(d, { recursive: true });
27
+ const file = path.join(d, `${port}.json`);
28
+ writeFileSync(file, JSON.stringify({ port, pid, dir, root, startedAt: new Date().toISOString() }, null, 2) + "\n");
29
+ return () => {
30
+ try {
31
+ if (JSON.parse(readFileSync(file, "utf8")).pid === pid) rmSync(file, { force: true });
32
+ } catch {
33
+ /* already gone */
34
+ }
35
+ };
36
+ }
37
+
38
+ export function readEntries(home = easelHome()) {
39
+ const d = serversDir(home);
40
+ if (!existsSync(d)) return [];
41
+ const out = [];
42
+ for (const n of readdirSync(d).filter((n) => /^\d+\.json$/.test(n))) {
43
+ try {
44
+ const e = JSON.parse(readFileSync(path.join(d, n), "utf8"));
45
+ if (Number.isInteger(e.port) && e.dir && e.root) out.push(e);
46
+ } catch {
47
+ /* half-written or broken: skip */
48
+ }
49
+ }
50
+ return out.sort((a, b) => a.port - b.port);
51
+ }
52
+
53
+ /** Whether a (resolved) folder is inside another one, or the same */
54
+ export const within = (child, parent) => {
55
+ const r = path.relative(parent, child);
56
+ return r === "" || (!r.startsWith("..") && !path.isAbsolute(r));
57
+ };
58
+
59
+ /**
60
+ * Pure choice among live canvases for an MCP server started in cwd (paths already resolved):
61
+ * the entry whose root contains cwd (longest root wins), else the only one below cwd (several below: ambiguous),
62
+ * else the only one at all, else ambiguous/none.
63
+ */
64
+ export function pickServer(entries, cwd) {
65
+ const around = entries.filter((e) => within(cwd, e.root)).sort((a, b) => b.root.length - a.root.length);
66
+ if (around.length) return { entry: around[0] };
67
+ const below = entries.filter((e) => within(e.root, cwd));
68
+ if (below.length) return below.length === 1 ? { entry: below[0] } : { ambiguous: below };
69
+ if (entries.length === 1) return { entry: entries[0] };
70
+ return entries.length ? { ambiguous: entries } : {};
71
+ }
72
+
73
+ const pidAlive = (pid) => {
74
+ try {
75
+ process.kill(pid, 0);
76
+ return true;
77
+ } catch (e) {
78
+ return e.code === "EPERM";
79
+ }
80
+ };
81
+
82
+ /** /api/health answers and serves the same design folder */
83
+ export async function isAlive(e, ms = 800) {
84
+ try {
85
+ const r = await fetch(`http://127.0.0.1:${e.port}/api/health`, { signal: AbortSignal.timeout(ms) });
86
+ if (!r.ok) return false;
87
+ const h = await r.json();
88
+ return real(h.dir) === real(e.dir);
89
+ } catch {
90
+ return false;
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Port for the MCP server: explicit (--port, or DESIGN_CANVAS_PORT from an in-app run) wins, else the registry, else the default.
96
+ * Throws when several canvases are live and cwd does not single one out.
97
+ */
98
+ export async function discoverPort({ port = null, cwd = process.cwd(), home = easelHome() } = {}) {
99
+ if (port) return port;
100
+ const live = [];
101
+ for (const e of readEntries(home)) {
102
+ if (await isAlive(e)) live.push({ ...e, root: real(e.root) });
103
+ else if (!pidAlive(e.pid)) rmSync(path.join(serversDir(home), `${e.port}.json`), { force: true }); // left behind by a crash
104
+ }
105
+ const pick = pickServer(live, real(cwd));
106
+ if (pick.entry) return pick.entry.port;
107
+ if (pick.ambiguous)
108
+ throw new Error(`Several Easel canvases are running and ${cwd} does not single one out:\n${pick.ambiguous.map((e) => ` ${e.root} (port ${e.port})`).join("\n")}\nPass --port <n> to easel-mcp to pick one.`);
109
+ return DEFAULT_PORT;
110
+ }
package/server/routes.mjs CHANGED
@@ -3,13 +3,16 @@
3
3
  import fs from "node:fs/promises";
4
4
  import path from "node:path";
5
5
 
6
- import { TOOL_ROOT } from "./args.mjs";
6
+ import { activityRoutes } from "./activity.mjs";
7
+ import { closeBrowser, newPage } from "./browser.mjs";
7
8
  import { boardRoutes } from "./boards.mjs";
8
9
  import { chatRoutes } from "./chat.mjs";
9
10
  import { tokenRoutes } from "./tokens.mjs";
10
11
  import { snapshotRoutes } from "./snapshot.mjs";
11
12
  import { applyEdit, EditError } from "./edit.mjs";
12
- import { writeAtomic } from "./fsutil.mjs";
13
+ import { exportRoutes } from "./export.mjs";
14
+ import { forkMessage, forkRoutes, routeWrite } from "./forks.mjs";
15
+ import { easelDir, rootOf, toPosix, writeAtomic } from "./fsutil.mjs";
13
16
  import { inspect, outline } from "./html.mjs";
14
17
  import { readBody, safeJoin, sendJson } from "./index.mjs";
15
18
  import { watchDesign } from "./watch.mjs";
@@ -47,51 +50,8 @@ async function writeComments(ctx, comments) {
47
50
  }
48
51
 
49
52
  /* ---------- Screenshots (when playwright is available) ---------- */
50
- let browserPromise = null;
51
- /** Close the Chromium used for screenshots/thumbnails when the server stops (otherwise it becomes an orphan process) */
52
- export async function closeBrowser() {
53
- const b = await browserPromise?.catch(() => null);
54
- browserPromise = null;
55
- await b?.close().catch(() => {});
56
- }
57
-
58
- async function getBrowser() {
59
- // A browser that exited behind our back (crash, killed, sleep) must not stay cached, or every thumbnail fails until a restart
60
- const pending = browserPromise;
61
- const cached = pending && (await pending.catch(() => null));
62
- if (cached && !cached.isConnected() && browserPromise === pending) browserPromise = null;
63
- if (!browserPromise) {
64
- const p = (browserPromise = (async () => {
65
- const { chromium } = await import("playwright").catch(() => {
66
- throw Object.assign(new Error("Screenshots are unavailable because playwright is not installed (npm run design:install)"), { status: 501 });
67
- });
68
- // Fall back to the installed Chrome if no downloaded Chromium exists
69
- const b = await chromium.launch().catch(() => chromium.launch({ channel: "chrome" }));
70
- b.on("disconnected", () => {
71
- if (browserPromise === p) browserPromise = null;
72
- });
73
- return b;
74
- })());
75
- p.catch(() => {
76
- if (browserPromise === p) browserPromise = null;
77
- });
78
- }
79
- return browserPromise;
80
- }
81
-
82
- /** New page on the shared browser; if the browser died since it was cached, launch a fresh one and try once more */
83
- export async function newPage(opts) {
84
- const browser = await getBrowser();
85
- try {
86
- return await browser.newPage(opts);
87
- } catch (e) {
88
- if (browser.isConnected()) throw e;
89
- return (await getBrowser()).newPage(opts); // getBrowser drops the dead one and launches again
90
- }
91
- }
92
-
93
- /** For tests: the browser currently cached for screenshots, if any */
94
- export const cachedBrowser = () => browserPromise?.catch(() => null) ?? Promise.resolve(null);
53
+ // The shared Chromium lives in browser.mjs (export uses it too); re-exported here for existing callers
54
+ export { cachedBrowser, closeBrowser, newPage } from "./browser.mjs";
95
55
 
96
56
  /** Thumbnail sizes (long side, device px) the client may ask for; anything else snaps to the next one up. Matches THUMB_SIZES in Canvas.tsx */
97
57
  const THUMB_PX = [600, 1200, 2400];
@@ -123,7 +83,7 @@ export async function screenshot(ctx, port, file, elPath) {
123
83
  const page = await newPage({ viewport: { width: board?.w ?? 390, height: board?.h ?? 844 }, deviceScaleFactor: 2 });
124
84
  try {
125
85
  await page.goto(`http://127.0.0.1:${port}/screens/${encodeURI(file)}`, { waitUntil: "networkidle" });
126
- const outDir = path.join(TOOL_ROOT, ".out");
86
+ const outDir = path.join(await easelDir(ctx.dir), "screenshots");
127
87
  await fs.mkdir(outDir, { recursive: true });
128
88
  const name = `${file.replace(/[\\/]/g, "_").replace(/\.html$/, "")}${elPath ? "--" + elPath.replace(/\//g, "-") : ""}.png`;
129
89
  const out = path.join(outDir, name);
@@ -151,19 +111,24 @@ export const extraRoutes = [
151
111
  "/api/edit",
152
112
  async (req, res, url, ctx) => {
153
113
  const b = await readBody(req);
154
- const { p, html } = await readScreen(ctx, b.file);
114
+ await readScreen(ctx, b.file);
115
+ // An agent editing a board another agent is on works on its fork (people always edit the board they are on)
116
+ const to = await routeWrite(ctx, b.file);
117
+ const { p, html } = await readScreen(ctx, to.file);
118
+ const fork = to.forked ? { file: to.file, forked: true, original: b.file, message: forkMessage(ctx, b.file, to) } : {};
155
119
  let next;
156
120
  try {
157
121
  next = applyEdit(html, b);
158
122
  } catch (e) {
159
- if (e instanceof EditError) return sendJson(res, e.status, { error: e.message });
123
+ // On a fork the agent may hold the original's HTML, so the error says which file it is on now
124
+ if (e instanceof EditError) return sendJson(res, e.status, { error: to.forked ? `${e.message}. ${fork.message}` : e.message, ...fork });
160
125
  throw e;
161
126
  }
162
- if (next === html) return sendJson(res, 200, { ok: true, changed: false });
127
+ if (next === html) return sendJson(res, 200, { ok: true, changed: false, ...fork });
163
128
  await writeScreen(ctx, p, next);
164
- ctx.history.push(`${b.file} ${b.op}`, [{ path: p, before: html, after: next }]);
129
+ ctx.history.push(`${to.file} ${b.op}`, [{ path: p, before: html, after: next }]);
165
130
  ctx.broadcast({ type: "history-changed" });
166
- sendJson(res, 200, { ok: true, changed: true });
131
+ sendJson(res, 200, { ok: true, changed: true, ...fork });
167
132
  },
168
133
  ],
169
134
  // Legacy route: forwards to the chronological history
@@ -177,6 +142,8 @@ export const extraRoutes = [
177
142
  },
178
143
  ]),
179
144
  ...boardRoutes(),
145
+ ...forkRoutes(),
146
+ ...activityRoutes(),
180
147
  ...chat.routes,
181
148
  ...tokenRoutes(),
182
149
  // Zoomed-out thumbnails: small images shown below 25% instead of empty frames. Stored per modification time in docs/design/.thumbs/ (gitignored)
@@ -221,6 +188,7 @@ export const extraRoutes = [
221
188
  },
222
189
  ],
223
190
  ...snapshotRoutes(),
191
+ ...exportRoutes(),
224
192
  // Assets: list and upload docs/design/assets/ (images, fonts). Screens reference them as ../assets/<name>
225
193
  [
226
194
  "GET",
@@ -382,7 +350,7 @@ export const extraRoutes = [
382
350
  await readScreen(ctx, b.file);
383
351
  const port = Number(req.socket.localPort);
384
352
  const out = await screenshot(ctx, port, b.file, b.path || "");
385
- sendJson(res, 200, { path: out });
353
+ sendJson(res, 200, { path: out, relPath: toPosix(path.relative(rootOf(ctx.dir), out)) });
386
354
  },
387
355
  ],
388
356
  [
@@ -413,6 +381,7 @@ export async function attach(app) {
413
381
  const stop = watchDesign(app.ctx);
414
382
  const close = app.close;
415
383
  app.close = async () => {
384
+ chat.close(); // open permission requests are denied, so a waiting agent does not hang
416
385
  await stop();
417
386
  await closeBrowser();
418
387
  await close();
@@ -0,0 +1,167 @@
1
+ // AI-generated with Claude Code, 2026-11-11, reviewed by Hyun Park
2
+ // Undo and redo of one whole in-app AI run (and of the steps behind a board tag), and read-only access to a run's pre-run copy (Compare, restore after a restart).
3
+ // A run on top of the history is a plain undo/redo; an older run takes back only its own files, and asks before overwriting later changes.
4
+ import fs from "node:fs/promises";
5
+ import path from "node:path";
6
+
7
+ import { formatBoard } from "./boardFormat.mjs";
8
+ import { isTrackedRel } from "./copies.mjs";
9
+ import { toPosix, writeAtomic } from "./fsutil.mjs";
10
+
11
+ const read = (p) => fs.readFile(p, "utf8").catch(() => null);
12
+ const same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
13
+ const parse = (t) => {
14
+ try {
15
+ return t ? JSON.parse(t) : {};
16
+ } catch {
17
+ return null;
18
+ }
19
+ };
20
+
21
+ /** A run's undo steps → one change per file, from its first before to its last after */
22
+ export function mergeSteps(steps) {
23
+ const m = new Map();
24
+ for (const s of steps)
25
+ for (const c of s.changes) {
26
+ const prev = m.get(c.path);
27
+ if (prev) prev.after = c.after;
28
+ else m.set(c.path, { path: c.path, before: c.before, after: c.after });
29
+ }
30
+ return [...m.values()].filter((c) => c.before !== c.after);
31
+ }
32
+
33
+ /** Boards a run touched, relative to screens/: changed, added (did not exist before) or removed */
34
+ export function runBoards(changes, screensDir) {
35
+ const out = [];
36
+ for (const c of changes) {
37
+ const rel = toPosix(path.relative(screensDir, c.path));
38
+ if (!c.path.endsWith(".html") || rel.startsWith("..")) continue;
39
+ out.push({ file: rel, kind: c.before == null ? "added" : c.after == null ? "removed" : "changed" });
40
+ }
41
+ return out;
42
+ }
43
+
44
+ /**
45
+ * board.json: applies the from → to difference of boards/notes entries (and pages/title) onto the current file, key by key,
46
+ * so moving another board since does not block the undo. conflicts: entries that changed since (board file names, note ids)
47
+ */
48
+ export function mergeBoardJson(curText, fromText, toText, force = false) {
49
+ const cur = parse(curText);
50
+ const from = parse(fromText);
51
+ const to = parse(toText);
52
+ if (!cur || !from || !to) return { text: force ? toText : curText, conflicts: force ? [] : ["board.json"] };
53
+ const conflicts = [];
54
+ for (const sec of ["boards", "notes"]) {
55
+ const c = { ...(cur[sec] ?? {}) };
56
+ for (const k of new Set([...Object.keys(from[sec] ?? {}), ...Object.keys(to[sec] ?? {})])) {
57
+ const a = from[sec]?.[k];
58
+ const b = to[sec]?.[k];
59
+ if (same(a, b) || same(c[k], b)) continue;
60
+ if (!same(c[k], a) && !force) {
61
+ conflicts.push(k);
62
+ continue;
63
+ }
64
+ if (b === undefined) delete c[k];
65
+ else c[k] = b;
66
+ }
67
+ cur[sec] = c;
68
+ }
69
+ for (const key of ["pages", "title"]) {
70
+ if (same(from[key], to[key]) || same(cur[key], to[key])) continue;
71
+ if (!same(cur[key], from[key]) && !force) conflicts.push(key);
72
+ else cur[key] = to[key];
73
+ }
74
+ const order = (Array.isArray(cur.order) ? cur.order : []).filter((f) => cur.boards?.[f]);
75
+ for (const f of Object.keys(cur.boards ?? {})) if (!order.includes(f)) order.push(f);
76
+ cur.order = order;
77
+ return { text: formatBoard(cur), conflicts };
78
+ }
79
+
80
+ /**
81
+ * Applies a run's changes backwards (undo) or forwards (redo) as one new history step. Files changed since are conflicts:
82
+ * without mode the call writes nothing and returns them; mode "rest" skips them, "all" overwrites them.
83
+ */
84
+ export async function applyRunChanges(ctx, changes, dir, { mode, label, mark }) {
85
+ const plan = [];
86
+ const conflicts = [];
87
+ for (const c of changes) {
88
+ const from = dir === "undo" ? c.after : c.before;
89
+ const to = dir === "undo" ? c.before : c.after;
90
+ const now = await read(c.path);
91
+ if (c.path === ctx.store.boardPath) {
92
+ const m = mergeBoardJson(now, from, to, mode === "all");
93
+ if (m.conflicts.length && mode !== "rest") conflicts.push(...m.conflicts.map((k) => ({ file: k, board: true })));
94
+ if (m.text !== now && (!m.conflicts.length || mode)) plan.push({ path: c.path, before: now, after: m.text });
95
+ continue;
96
+ }
97
+ if (now === to) continue;
98
+ if (now !== from) {
99
+ conflicts.push({ file: toPosix(path.relative(ctx.store.screensDir, c.path)) });
100
+ if (mode !== "all") continue;
101
+ }
102
+ plan.push({ path: c.path, before: now, after: to });
103
+ }
104
+ if (conflicts.length && !mode) return { conflicts };
105
+ for (const c of plan) {
106
+ if (c.after == null) await fs.rm(c.path, { force: true });
107
+ else {
108
+ await fs.mkdir(path.dirname(c.path), { recursive: true });
109
+ await writeAtomic(c.path, c.after);
110
+ }
111
+ }
112
+ ctx.history.push(label, plan, mark);
113
+ await dropMissingAutoPlaced(ctx);
114
+ return { changed: plan.length, skipped: mode === "rest" ? conflicts.map((c) => c.file) : [] };
115
+ }
116
+
117
+ /**
118
+ * Undo of a set of changes that may be older than the newest step (a chat run, the steps behind a board tag): onTop plain history
119
+ * undos when they are the newest steps, else only their own files as one new step, with the same conflict rule as applyRunChanges
120
+ */
121
+ export async function undoChanges(ctx, { onTop = 0, changes, mode, label, mark }) {
122
+ if (!onTop) return applyRunChanges(ctx, changes, "undo", { mode: ["rest", "all"].includes(mode) ? mode : undefined, label, mark });
123
+ for (let i = 0; i < onTop; i++) await ctx.history.undo();
124
+ await dropMissingAutoPlaced(ctx);
125
+ return { changed: onTop, skipped: [] };
126
+ }
127
+
128
+ /** Entries auto-placed for files that are gone again (an undone run's new screens): placement is not an undo step, so neither is this */
129
+ export async function dropMissingAutoPlaced(ctx) {
130
+ const board = await ctx.store.readBoard();
131
+ const files = new Set(await ctx.store.listScreenFiles());
132
+ const gone = Object.keys(board.boards).filter((f) => board.boards[f].autoPlaced && !files.has(f));
133
+ if (!gone.length) return;
134
+ for (const f of gone) delete board.boards[f];
135
+ board.order = board.order.filter((f) => !gone.includes(f));
136
+ await ctx.store.writeBoard(board);
137
+ }
138
+
139
+ /* ---------- The pre-run copy in .easel/runs/<id>/ ---------- */
140
+ const validId = (id) => /^r[0-9a-z]+$/.test(String(id ?? ""));
141
+ const copyDir = (dir, id) => path.join(dir, ".easel", "runs", id);
142
+
143
+ /** Saved time and label of a run's copy; null when it is gone (pruned) or the id is not a run id */
144
+ export async function runCopyInfo(dir, id) {
145
+ if (!validId(id)) return null;
146
+ const meta = parse(await read(path.join(copyDir(dir, id), "run.json")));
147
+ return meta && typeof meta.at === "string" ? { at: meta.at, label: typeof meta.label === "string" ? meta.label : "" } : null;
148
+ }
149
+
150
+ /**
151
+ * A screen as it was before run id: f is screens/<…>.html (validated like the revert, and listed in the copy's run.json).
152
+ * null when the id, the name or the copy is not valid
153
+ */
154
+ export async function readRunFile(dir, id, f) {
155
+ if (!validId(id) || !isTrackedRel(f) || !String(f).startsWith("screens/")) return null;
156
+ const src = copyDir(dir, id);
157
+ const meta = parse(await read(path.join(src, "run.json")));
158
+ if (!meta || !Array.isArray(meta.files) || !meta.files.includes(f)) return null;
159
+ return read(path.join(src, f));
160
+ }
161
+
162
+ /** <base> so a copy served from the API resolves ../assets and links like the live screen at /screens/<file> */
163
+ export function withBase(html, file) {
164
+ const tag = `<base href="/screens/${file.split("/").map(encodeURIComponent).join("/")}">`;
165
+ const m = /<head[^>]*>/i.exec(html) ?? /<html[^>]*>/i.exec(html) ?? /<!doctype[^>]*>/i.exec(html);
166
+ return m ? html.slice(0, m.index + m[0].length) + tag + html.slice(m.index + m[0].length) : tag + html;
167
+ }
@@ -1,10 +1,12 @@
1
1
  // AI-generated with Claude Code, 2026-10-09, reviewed by Hyun Park
2
2
  // git snapshots instead of versions: commits only the design folder (author from git config) and lists recent snapshots.
3
3
  // No restore (use git directly). Commits only the design folder path so other staged files are not mixed in.
4
+ // Outside a git repository a snapshot is a folder copy in <design dir>/.easel/snapshots/ (kind "copy").
4
5
  import { spawn } from "node:child_process";
5
6
  import fs from "node:fs/promises";
6
7
  import path from "node:path";
7
8
 
9
+ import { copySnapshot, listSnapshotCopies } from "./copies.mjs";
8
10
  import { readBody, sendJson } from "./index.mjs";
9
11
 
10
12
  export function git(cwd, args) {
@@ -39,19 +41,25 @@ export function snapshotRoutes() {
39
41
  "/api/snapshots",
40
42
  async (req, res, url, ctx) => {
41
43
  const root = await repoOf(ctx.dir);
42
- if (!root) return sendJson(res, 200, { git: false, snapshots: [], changed: 0 });
44
+ const copies = await listSnapshotCopies(ctx.dir);
45
+ if (!root) return sendJson(res, 200, { git: false, snapshots: copies.slice(0, 15), changed: 0 });
43
46
  const rel = path.relative(root, await fs.realpath(ctx.dir)) || "."; // resolve links like /var → /private/var before comparing
44
- const log = await git(root, ["log", "-n", "15", "--format=%h%x09%an%x09%ar%x09%s", "--", rel]);
47
+ const log = await git(root, ["log", "-n", "15", "--format=%h%x09%an%x09%ar%x09%s%x09%aI", "--", rel]);
45
48
  const st = await git(root, ["status", "--porcelain", "--", rel]);
46
49
  const branch = (await git(root, ["branch", "--show-current"])).out.trim();
47
50
  sendJson(res, 200, {
48
51
  git: true,
49
52
  branch,
50
53
  changed: st.out.split("\n").filter(Boolean).length,
51
- snapshots: log.out.split("\n").filter(Boolean).map((l) => {
52
- const [hash, author, when, subject] = l.split("\t");
53
- return { hash, author, when, subject };
54
- }),
54
+ snapshots: [
55
+ ...log.out.split("\n").filter(Boolean).map((l) => {
56
+ const [hash, author, when, subject, at] = l.split("\t");
57
+ return { hash, author, when, subject, at, kind: "git" };
58
+ }),
59
+ ...copies,
60
+ ]
61
+ .sort((a, b) => new Date(b.at) - new Date(a.at))
62
+ .slice(0, 15),
55
63
  });
56
64
  },
57
65
  ],
@@ -61,9 +69,13 @@ export function snapshotRoutes() {
61
69
  async (req, res, url, ctx) => {
62
70
  const b = await readBody(req);
63
71
  const root = await repoOf(ctx.dir);
64
- if (!root) return sendJson(res, 400, { error: "The design folder is not inside a git repository" });
65
- const rel = path.relative(root, await fs.realpath(ctx.dir)) || "."; // resolve links like /var → /private/var before comparing
66
72
  const msg = String(b.message ?? "").trim() || `design: snapshot ${new Date().toLocaleString("en-US")}`;
73
+ if (!root) {
74
+ const me = await git(ctx.dir, ["config", "user.name"]);
75
+ const { name } = await copySnapshot(ctx.dir, { message: msg, author: me.code === 0 ? me.out.trim() : process.env.USER ?? "" });
76
+ return sendJson(res, 200, { ok: true, kind: "copy", hash: name, path: `.easel/snapshots/${name}`, message: msg });
77
+ }
78
+ const rel = path.relative(root, await fs.realpath(ctx.dir)) || "."; // resolve links like /var → /private/var before comparing
67
79
  const add = await git(root, ["add", "--", rel]);
68
80
  if (add.code !== 0) return sendJson(res, 500, { error: add.err.trim() || "git add failed" });
69
81
  const diff = await git(root, ["diff", "--cached", "--quiet", "--", rel]);
@@ -72,7 +84,7 @@ export function snapshotRoutes() {
72
84
  const c = await git(root, ["commit", "-m", msg, "--", rel]);
73
85
  if (c.code !== 0) return sendJson(res, 500, { error: (c.err || c.out).trim().split("\n").slice(-3).join("\n") || "git commit failed" });
74
86
  const hash = (await git(root, ["rev-parse", "--short", "HEAD"])).out.trim();
75
- sendJson(res, 200, { ok: true, hash, message: msg });
87
+ sendJson(res, 200, { ok: true, kind: "git", hash, message: msg });
76
88
  },
77
89
  ],
78
90
  ];
package/server/tokens.mjs CHANGED
@@ -8,6 +8,9 @@ import { writeAtomic } from "./fsutil.mjs";
8
8
  import { elementChildren, findBody, parseHtml } from "./html.mjs";
9
9
  import { readBody, sendJson } from "./index.mjs";
10
10
 
11
+ /** System font stack only: no web font download, nothing language- or brand-specific (the starter templates use it too) */
12
+ export const SYSTEM_FONT = 'system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';
13
+
11
14
  export const DEFAULT_TOKENS = {
12
15
  version: 1,
13
16
  active: "Default",
@@ -27,7 +30,7 @@ export const DEFAULT_TOKENS = {
27
30
  fontWeights: [400, 600, 700],
28
31
  radii: [4, 8, 16, 999],
29
32
  spacing: [0, 4, 8, 12, 16, 20, 24, 32, 40],
30
- fontFamily: '"Pretendard Variable", Pretendard, -apple-system, "Apple SD Gothic Neo", "Noto Sans KR", sans-serif',
33
+ fontFamily: SYSTEM_FONT,
31
34
  minTarget: 48,
32
35
  };
33
36
 
@@ -0,0 +1,63 @@
1
+ // AI-generated with Claude Code, 2026-11-15, reviewed by Hyun Park
2
+ // New-version notice: npx keeps the copy it cached, so nothing tells people a newer Easel exists. Once a day the canvas asks
3
+ // the npm registry for easel-canvas's latest version (only that: one GET, nothing about the project) and, when it is newer,
4
+ // says which command updates this install. Silent whenever it cannot ask: EASEL_NO_UPDATE_CHECK=1, CI, a source checkout
5
+ // (git clone or submodule: updated with git), offline, a slow or broken registry.
6
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
7
+ import path from "node:path";
8
+
9
+ import { TOOL_ROOT } from "./args.mjs";
10
+ import { easelHome } from "./registry.mjs";
11
+
12
+ const DAY = 24 * 60 * 60 * 1000;
13
+ const REGISTRY = "https://registry.npmjs.org/easel-canvas/latest";
14
+
15
+ /** a > b for x.y.z versions; a pre-release (0.3.0-beta.1) is older than its release and never offered */
16
+ export function isNewer(a, b) {
17
+ const parse = (v) => String(v).replace(/^v/, "").split("-")[0].split(".").map((n) => parseInt(n, 10) || 0);
18
+ if (/-/.test(String(a))) return false;
19
+ const [x, y] = [parse(a), parse(b)];
20
+ for (let i = 0; i < 3; i++) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) > (y[i] ?? 0);
21
+ return /-/.test(String(b)); // 0.3.0 is newer than 0.3.0-beta.1
22
+ }
23
+
24
+ /** The command that updates the copy running from root: npx's cache, a project's node_modules, or a global install */
25
+ export function updateCommand(root = TOOL_ROOT) {
26
+ const p = root.split(path.sep).join("/");
27
+ if (p.includes("/_npx/")) return "npx easel-canvas@latest";
28
+ if (/\/node_modules\/easel-canvas\/?$/.test(p)) {
29
+ const global = /\/lib\/node_modules\/easel-canvas\/?$/.test(p) || /\/npm\/node_modules\/easel-canvas\/?$/i.test(p);
30
+ return global ? "npm i -g easel-canvas@latest" : "npm i -D easel-canvas@latest";
31
+ }
32
+ return "npx easel-canvas@latest";
33
+ }
34
+
35
+ /**
36
+ * Resolves to { current, latest, command } when the registry has a newer version, else null; never throws.
37
+ * The answer is kept a day in <EASEL_HOME>/update.json. EASEL_UPDATE_URL points the check elsewhere (tests, trying it out
38
+ * from a source checkout).
39
+ */
40
+ export async function checkUpdate({ current, env = process.env, root = TOOL_ROOT, home = easelHome(env), now = Date.now(), fetchImpl = fetch } = {}) {
41
+ try {
42
+ if (env.EASEL_NO_UPDATE_CHECK === "1" || env.CI) return null;
43
+ const url = env.EASEL_UPDATE_URL || REGISTRY;
44
+ if (!env.EASEL_UPDATE_URL && existsSync(path.join(root, "app"))) return null;
45
+ const file = path.join(home, "update.json");
46
+ let latest = null;
47
+ try {
48
+ const c = JSON.parse(readFileSync(file, "utf8"));
49
+ if (c.url === url && now - c.checkedAt < DAY) latest = c.latest;
50
+ } catch {}
51
+ if (!latest) {
52
+ const r = await fetchImpl(url, { signal: AbortSignal.timeout(2000), headers: { accept: "application/json" } });
53
+ if (!r.ok) return null;
54
+ latest = (await r.json())?.version;
55
+ if (typeof latest !== "string") return null;
56
+ mkdirSync(home, { recursive: true });
57
+ writeFileSync(file, JSON.stringify({ url, checkedAt: now, latest }));
58
+ }
59
+ return isNewer(latest, current) ? { current, latest, command: updateCommand(root) } : null;
60
+ } catch {
61
+ return null;
62
+ }
63
+ }
package/server/watch.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  // AI-generated with Claude Code, 2026-10-09, reviewed by Hyun Park
2
2
  // Design folder watcher: when HTML changes, notify so only that board is redrawn; new files are auto-placed in board.json. PLAN.md ch. 7 M2.
3
+ // Changes the app did not make (agents' own file tools, editors) are handed to the undo history, which records them as steps.
3
4
  import crypto from "node:crypto";
4
5
  import fs from "node:fs/promises";
5
6
  import path from "node:path";
@@ -9,7 +10,7 @@ import chokidar from "chokidar";
9
10
  import { createDeps } from "./deps.mjs";
10
11
  import { toPosix } from "./fsutil.mjs";
11
12
 
12
- export function watchDesign({ dir, store, broadcast }) {
13
+ export function watchDesign({ dir, store, broadcast, history }) {
13
14
  const screensDir = store.screensDir;
14
15
  const watcher = chokidar.watch([screensDir, store.boardPath], {
15
16
  ignoreInitial: true,
@@ -57,8 +58,17 @@ export function watchDesign({ dir, store, broadcast }) {
57
58
  broadcast({ type: "board-changed", source: "server:rename" });
58
59
  }
59
60
 
61
+ // Compared with the last known content inside exclusive, so an app write still in flight has been recorded first
62
+ const track = (p) =>
63
+ history &&
64
+ store
65
+ .exclusive(() => history.observe([p]))
66
+ .then((step) => step && broadcast({ type: "history-changed" }))
67
+ .catch((e) => console.error("tracking an outside change failed", e));
68
+
60
69
  watcher.on("all", async (event, abs) => {
61
70
  if (abs === store.boardPath) {
71
+ void track(store.boardPath);
62
72
  // Do not notify for content this server just wrote (avoids echoing our own saves)
63
73
  try {
64
74
  const now = await fs.readFile(abs, "utf8");
@@ -72,6 +82,7 @@ export function watchDesign({ dir, store, broadcast }) {
72
82
  if (!abs.endsWith(".html")) return;
73
83
  const file = toPosix(path.relative(screensDir, abs));
74
84
  const kind = event === "add" ? "add" : event === "unlink" ? "unlink" : "change";
85
+ void track(path.join(screensDir, file));
75
86
  if (kind === "unlink") {
76
87
  deps.remove(file);
77
88
  if (hashes.has(file)) removed.push({ file, hash: hashes.get(file), at: Date.now() });