easel-canvas 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "easel-canvas",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Easel: an HTML design canvas for AI agents. Shows screens/*.html as boards and edits the source directly, with Claude Code / Codex via MCP",
5
5
  "license": "MIT",
6
6
  "author": "Hyun Park",
package/server/chat.mjs CHANGED
@@ -329,6 +329,8 @@ export function chatRoutes({ getSelection } = {}) {
329
329
  return {
330
330
  state,
331
331
  close: () => denyOpen(),
332
+ /** An Easel chat run is going (the one-click update waits for it) */
333
+ busy: () => [...runs.values()].some((r) => r.status === "running"),
332
334
  routes: [
333
335
  [
334
336
  "POST",
package/server/index.mjs CHANGED
@@ -17,7 +17,9 @@ import { contentHash } from "./livePatch.mjs";
17
17
  import { createOccupancy } from "./occupancy.mjs";
18
18
  import { createStamps } from "./stamps.mjs";
19
19
  import { isAlive, readEntries, real, writeEntry } from "./registry.mjs";
20
- import { checkUpdate } from "./update.mjs";
20
+ import { install } from "./selfupdate.mjs";
21
+ import { readFileSync } from "node:fs";
22
+ import { createUpdater } from "./update.mjs";
21
23
 
22
24
  export const MIME = {
23
25
  ".html": "text/html; charset=utf-8",
@@ -201,6 +203,9 @@ function noteWriters(occupancy, screensDir, step, changes) {
201
203
  * autoPort: when the port is busy, try the next ones instead of failing (for a port the user did not choose).
202
204
  * updateCheck: ask the npm registry once a day whether a newer Easel exists (the CLI only; see update.mjs).
203
205
  */
206
+ /** The version of the code this process runs, read when it loaded: after a failed hand-over the files on disk may be newer */
207
+ const RUNNING_VERSION = JSON.parse(readFileSync(path.join(TOOL_ROOT, "package.json"), "utf8")).version;
208
+
204
209
  export async function createServer({ dir, port, dev = true, extraRoutes = [], autoPort = false, register = false, updateCheck = false }) {
205
210
  if (!existsSync(dir)) throw new Error(`Design folder not found: ${dir}`);
206
211
  let history;
@@ -227,10 +232,44 @@ export async function createServer({ dir, port, dev = true, extraRoutes = [], au
227
232
  const LOCKED = /^\/api\/(board|boards\/|history\/|edit|undo|redo|place|notes|pages|comments|chat\/(revert|undo-run|redo-run))/;
228
233
  // Screens folder as the agent sees it: relative to the project root
229
234
  const screensRel = toPosix(path.relative(rootOf(dir), store.screensDir)) || "screens";
230
- // Started now, answered by /api/update: never in the way of start-up, resolves to null when there is nothing to say
231
- const update = updateCheck ? checkUpdate({ current: JSON.parse(await fs.readFile(path.join(TOOL_ROOT, "package.json"), "utf8")).version }) : Promise.resolve(null);
235
+ // New-version notice (update.mjs): asked now, when a page loads (an answer older than an hour is asked again) and every few hours;
236
+ // the terminal says it once per new version. ctx.updateState: the one-click update's phase (installing, restarting, failed), kept
237
+ // across a failed hand-over by bin/server.mjs; ctx.busy and ctx.handover are set by routes.mjs and bin/server.mjs
238
+ const current = RUNNING_VERSION;
239
+ const updater = updateCheck
240
+ ? createUpdater({ current, onNews: (u) => console.log(`Easel ${u.latest} is out (you have ${u.current}). ${u.self ? "Update from the project menu, or run" : "Update:"} ${u.command}${u.self ? "" : ", then restart"}.`) })
241
+ : null;
242
+ const update = updater ? updater.get() : Promise.resolve(null);
243
+ ctx.updateState ??= null;
244
+ const setUpdateState = (s) => {
245
+ ctx.updateState = s;
246
+ ctx.broadcast({ type: "update-state" });
247
+ };
232
248
  const routes = [
233
- ["GET", "/api/update", async (req, res) => sendJson(res, 200, { update: await update })],
249
+ ["GET", "/api/update", async (req, res) => sendJson(res, 200, { update: updater ? await updater.get() : null, current, state: ctx.updateState, busy: !!ctx.busy?.() })],
250
+ // One click: only the app page itself may ask (an Origin header of this canvas, JSON body); one at a time; never during an Easel AI
251
+ // run; install, check the version on disk, then hand over under the store's lock so no write is cut in half
252
+ [
253
+ "POST",
254
+ "/api/update",
255
+ async (req, res) => {
256
+ if (!req.headers.origin || !originAllowed(req.headers) || !/^application\/json\b/.test(req.headers["content-type"] ?? "")) return sendJson(res, 403, { error: "Only the canvas page can update it" });
257
+ await readBody(req);
258
+ const u = updater ? await updater.get() : null;
259
+ if (!u) return sendJson(res, 409, { error: "Up to date", why: "uptodate" });
260
+ if (!u.self) return sendJson(res, 409, { error: "Easel cannot update itself here", why: u.why, command: u.command });
261
+ if (!ctx.handover) return sendJson(res, 409, { error: "Easel cannot restart itself here", why: "other", command: u.command });
262
+ if (ctx.busy?.()) return sendJson(res, 409, { error: "An AI run is going", why: "busy" });
263
+ if (ctx.updateState && ctx.updateState.phase !== "failed") return sendJson(res, 409, { error: "Already updating", why: "updating" });
264
+ setUpdateState({ phase: "installing", to: u.latest });
265
+ sendJson(res, 202, { ok: true, to: u.latest });
266
+ const r = await install({ version: u.latest });
267
+ if (!r.ok) return setUpdateState({ phase: "failed", to: u.latest, why: r.why, detail: r.detail, command: u.command });
268
+ setUpdateState({ phase: "restarting", to: u.latest });
269
+ const handed = await store.exclusive(() => ctx.handover(r.root)).catch(() => false);
270
+ if (!handed) setUpdateState({ phase: "failed", to: u.latest, why: "restart", command: u.command });
271
+ },
272
+ ],
234
273
  ["GET", "/api/health", async (req, res) => sendJson(res, 200, { ok: true, dir, root: rootOf(dir), screens: screensRel, pid: process.pid })],
235
274
  // Other Easel canvases running on this machine (the registry easel-canvas status reads), for the project menu: only those that
236
275
  // answer for their own folder, never this one. Title from each one's board.json; nothing else of theirs is read
@@ -377,6 +416,7 @@ export async function createServer({ dir, port, dev = true, extraRoutes = [], au
377
416
  unregister,
378
417
  async close() {
379
418
  unregister();
419
+ updater?.close();
380
420
  occupancy.close();
381
421
  await appWatcher?.close();
382
422
  for (const c of wss.clients) c.terminate();
@@ -310,6 +310,8 @@ const brief = (c, by) => ({
310
310
  ...(c.request.attach?.kind ? { kind: c.request.attach.kind } : {}),
311
311
  ...(c.request.by ? { by: c.request.by } : {}),
312
312
  ...(c.request.left ? { left: c.request.left } : {}),
313
+ // When an agent first listed it while waiting (the Claude Code wake hook announces a request again only while this is unset)
314
+ ...(c.request.seenAt ? { seenAt: c.request.seenAt } : {}),
313
315
  });
314
316
 
315
317
  /** In-memory: each taken request's board contents when it was taken, so finishing can tell which boards changed */
package/server/routes.mjs CHANGED
@@ -459,6 +459,7 @@ export const extraRoutes = [
459
459
 
460
460
  /** Things to attach after the server starts (file watching etc.) */
461
461
  export async function attach(app) {
462
+ app.ctx.busy = chat.busy; // the one-click update waits while an Easel AI run is going
462
463
  const stop = watchDesign(app.ctx);
463
464
  const close = app.close;
464
465
  app.close = async () => {
@@ -0,0 +1,98 @@
1
+ // AI-generated with Claude Code, 2026-12-03, reviewed by Hyun Park
2
+ // One-click update, where Easel can replace itself (an npx cache or a global install; see update.mjs installKind): npm installs
3
+ // easel-canvas@<x.y.z> into the prefix this copy runs from, the version on disk is checked, and only then is the canvas handed over to
4
+ // the new files (bin/server.mjs: the old server closes its port, starts the new one on the same port and folder, and goes back to
5
+ // listening if the new one does not answer). Nothing from the registry reaches a shell: the version must be x.y.z and npm is spawned
6
+ // with an argument array. EASEL_UPDATE_INSTALLER (a JSON argument array, as DESIGN_CANVAS_AGENT_CMD) stands in for npm in tests.
7
+ import { spawn } from "node:child_process";
8
+ import { existsSync, readFileSync } from "node:fs";
9
+ import path from "node:path";
10
+
11
+ import { TOOL_ROOT } from "./args.mjs";
12
+ import { installKind, validVersion } from "./update.mjs";
13
+
14
+ /** How to run npm without a shell: node + npm-cli.js beside this node when it is there (also on Windows, where npm is a .cmd), else npm */
15
+ export function npmCommand({ execPath = process.execPath, exists = existsSync, platform = process.platform } = {}) {
16
+ const dir = path.dirname(execPath);
17
+ for (const cli of [path.join(dir, "node_modules/npm/bin/npm-cli.js"), path.join(dir, "../lib/node_modules/npm/bin/npm-cli.js")]) if (exists(cli)) return [execPath, cli];
18
+ return platform === "win32" ? null : ["npm"];
19
+ }
20
+
21
+ /** npm's arguments for this install kind: into npx's cache dir as its own package, or -g into the global prefix this copy lives under */
22
+ export function installArgs(kind, prefix, version) {
23
+ if (!validVersion(version)) throw new Error(`Not a release version: ${String(version).slice(0, 40)}`);
24
+ if (!prefix || !path.isAbsolute(prefix)) throw new Error("No install folder");
25
+ const common = ["--no-audit", "--no-fund", "--loglevel=error"];
26
+ if (kind === "npx") return ["install", `easel-canvas@${version}`, "--prefix", prefix, ...common];
27
+ if (kind === "global") return ["install", "-g", `easel-canvas@${version}`, "--prefix", prefix, ...common];
28
+ throw new Error(`Easel cannot update itself here (${kind})`);
29
+ }
30
+
31
+ /** Why an install failed, in a word the page turns into plain words (strings.update.why): permission, network or failed */
32
+ export function classifyInstallFailure(text = "", code = null) {
33
+ if (/EACCES|EPERM|permission denied|operation not permitted/i.test(text)) return "permission";
34
+ if (/ENOTFOUND|EAI_AGAIN|ETIMEDOUT|ECONNRESET|ECONNREFUSED|network|fetch failed|ENETUNREACH/i.test(text)) return "network";
35
+ if (code === "ENOENT") return "nonpm";
36
+ return "failed";
37
+ }
38
+
39
+ /** The version in <root>/package.json, or null */
40
+ export function versionOnDisk(root) {
41
+ try {
42
+ const v = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")).version;
43
+ return validVersion(v) ? v : null;
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Installs easel-canvas@version where the copy at root came from. Resolves to { ok: true, root } (the folder to start the new server
51
+ * from, its package.json at that version) or { ok: false, why, detail }; never throws. Times out after `timeout` (npm hanging on a
52
+ * registry that does not answer).
53
+ */
54
+ export async function install({ version, root = TOOL_ROOT, env = process.env, spawnImpl = spawn, timeout = 180_000, npm = npmCommand() } = {}) {
55
+ try {
56
+ const { kind, prefix } = installKind(root);
57
+ const args = installArgs(kind, prefix, version);
58
+ let cmd;
59
+ if (env.EASEL_UPDATE_INSTALLER) {
60
+ const fake = JSON.parse(env.EASEL_UPDATE_INSTALLER);
61
+ if (!Array.isArray(fake) || !fake.every((a) => typeof a === "string")) throw new Error("EASEL_UPDATE_INSTALLER is not an argument array");
62
+ cmd = [...fake, ...args];
63
+ } else {
64
+ if (!npm) return { ok: false, why: "nonpm", detail: "npm was not found beside node" };
65
+ cmd = [...npm, ...args];
66
+ }
67
+ const out = await new Promise((resolve) => {
68
+ let text = "";
69
+ const p = spawnImpl(cmd[0], cmd.slice(1), { stdio: ["ignore", "pipe", "pipe"], env: { ...env, npm_config_update_notifier: "false" }, windowsHide: true });
70
+ const t = setTimeout(() => (p.kill("SIGTERM"), (text += "\nTimed out (network)")), timeout);
71
+ p.stdout?.on("data", (d) => (text += d));
72
+ p.stderr?.on("data", (d) => (text += d));
73
+ p.on("error", (e) => (clearTimeout(t), resolve({ code: e.code ?? "error", text: text + String(e.message) })));
74
+ p.on("close", (code) => (clearTimeout(t), resolve({ code, text })));
75
+ });
76
+ if (out.code !== 0) return { ok: false, why: classifyInstallFailure(out.text, out.code), detail: out.text.trim().split("\n").slice(-3).join("\n").slice(0, 400) };
77
+ const got = versionOnDisk(root);
78
+ if (got !== version) return { ok: false, why: "failed", detail: `After the install ${root} holds ${got ?? "no version"}, not ${version}` };
79
+ if (!existsSync(path.join(root, "bin", "server.mjs"))) return { ok: false, why: "failed", detail: "The new copy has no bin/server.mjs" };
80
+ return { ok: true, root };
81
+ } catch (e) {
82
+ return { ok: false, why: "failed", detail: String(e?.message ?? e) };
83
+ }
84
+ }
85
+
86
+ /** Polls http://127.0.0.1:port/api/health until a server with another pid answers, or the time is up; false if `alive()` says the new process died */
87
+ export async function waitForNew({ port, pid, ms = 30_000, alive = () => true, fetchImpl = fetch }) {
88
+ const end = Date.now() + ms;
89
+ while (Date.now() < end) {
90
+ if (!alive()) return false;
91
+ try {
92
+ const r = await fetchImpl(`http://127.0.0.1:${port}/api/health`, { signal: AbortSignal.timeout(1000) });
93
+ if (r.ok && (await r.json()).pid !== pid) return true;
94
+ } catch {}
95
+ await new Promise((r) => setTimeout(r, 250));
96
+ }
97
+ return false;
98
+ }
package/server/up.mjs CHANGED
@@ -80,6 +80,6 @@ export async function up({ dir, dirGiven = false, port = null, init = false, ope
80
80
 
81
81
  /** One line for people (and agents reading the output) */
82
82
  export function describe(r, dir) {
83
- if (!r) return `No Easel canvas is running for ${dir}. Start one with: npx easel-canvas up`;
83
+ if (!r) return `No Easel canvas is running for ${dir}. Start one with: npx easel-canvas@latest up`;
84
84
  return `${r.started ? "Started Easel" : "Easel is already running"}: ${r.url} (design folder ${r.dir}, pid ${r.pid})${r.log ? `\nLog: ${r.log}` : ""}`;
85
85
  }
package/server/update.mjs CHANGED
@@ -1,17 +1,25 @@
1
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";
2
+ // New-version notice: npx keeps the copy it cached, so nothing tells people a newer Easel exists. The canvas asks the npm registry
3
+ // for easel-canvas's latest version (only that: one GET, nothing about the project) when the page loads and every few hours while it
4
+ // runs, keeping the answer an hour, and when it is newer says how this install updates: in one click where Easel can replace itself
5
+ // (npx's cache, a global install; see selfupdate.mjs), else the command to run. Silent whenever it cannot ask:
6
+ // EASEL_NO_UPDATE_CHECK=1, CI, a source checkout (git clone or submodule: updated with git), offline, a slow or broken registry.
7
+ import { accessSync, constants, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
7
8
  import path from "node:path";
8
9
 
9
10
  import { TOOL_ROOT } from "./args.mjs";
10
11
  import { easelHome } from "./registry.mjs";
11
12
 
12
- const DAY = 24 * 60 * 60 * 1000;
13
+ export const HOUR = 60 * 60 * 1000;
14
+ /** How long an answer from the registry is kept (in memory and in <EASEL_HOME>/update.json) */
15
+ export const CACHE_MS = HOUR;
16
+ /** How often a running canvas asks again on its own (a page load asks too, when the answer is older than CACHE_MS) */
17
+ export const EVERY_MS = 3 * HOUR;
13
18
  const REGISTRY = "https://registry.npmjs.org/easel-canvas/latest";
14
19
 
20
+ /** A plain release version, x.y.z: the only thing ever passed on to npm (never a tag, a range or a URL) */
21
+ export const validVersion = (v) => typeof v === "string" && /^\d{1,4}\.\d{1,4}\.\d{1,6}$/.test(v);
22
+
15
23
  /** a > b for x.y.z versions; a pre-release (0.3.0-beta.1) is older than its release and never offered */
16
24
  export function isNewer(a, b) {
17
25
  const parse = (v) => String(v).replace(/^v/, "").split("-")[0].split(".").map((n) => parseInt(n, 10) || 0);
@@ -21,21 +29,48 @@ export function isNewer(a, b) {
21
29
  return /-/.test(String(b)); // 0.3.0 is newer than 0.3.0-beta.1
22
30
  }
23
31
 
32
+ /**
33
+ * Where the running copy comes from, and so how it updates:
34
+ * npx (npx's cache, <prefix>/_npx/<hash>/node_modules/easel-canvas): installs into that prefix in place, so plain `npx easel-canvas` starts
35
+ * the new one too; global (<prefix>/lib/node_modules, or <prefix>\node_modules on Windows): `npm i -g` into that prefix; project (a
36
+ * project's node_modules: its lockfile is the owner's call) and source (a checkout: git) only say the command; other: as npx.
37
+ */
38
+ export function installKind(root = TOOL_ROOT) {
39
+ const p = root.split(path.sep).join("/").replace(/\/+$/, "");
40
+ if (existsSync(path.join(root, "app")) || existsSync(path.join(root, ".git"))) return { kind: "source", prefix: null };
41
+ const m = p.match(/^(.*\/_npx\/[^/]+)\/node_modules\/easel-canvas$/);
42
+ if (m) return { kind: "npx", prefix: m[1].split("/").join(path.sep) };
43
+ const g = p.match(/^(.*)\/lib\/node_modules\/easel-canvas$/) ?? p.match(/^(.*\/npm)\/node_modules\/easel-canvas$/i);
44
+ if (g) return { kind: "global", prefix: g[1].split("/").join(path.sep) };
45
+ if (/\/node_modules\/easel-canvas$/.test(p)) return { kind: "project", prefix: null };
46
+ return { kind: "other", prefix: null };
47
+ }
48
+
24
49
  /** The command that updates the copy running from root: npx's cache, a project's node_modules, or a global install */
25
50
  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";
51
+ const { kind } = installKind(root);
52
+ return kind === "global" ? "npm i -g easel-canvas@latest" : kind === "project" ? "npm i -D easel-canvas@latest" : kind === "source" ? "git pull" : "npx easel-canvas@latest";
53
+ }
54
+
55
+ /** Whether Easel can replace this copy itself, and if not, why (shown under the row in plain words; see strings.update.why) */
56
+ export function selfUpdatable(root = TOOL_ROOT) {
57
+ const { kind } = installKind(root);
58
+ if (kind === "npx") return { self: true };
59
+ if (kind === "global") {
60
+ try {
61
+ accessSync(path.dirname(root), constants.W_OK); // …/lib/node_modules: npm writes there
62
+ return { self: true };
63
+ } catch {
64
+ return { self: false, why: "permission" };
65
+ }
31
66
  }
32
- return "npx easel-canvas@latest";
67
+ return { self: false, why: kind === "project" ? "project" : kind === "source" ? "source" : "other" };
33
68
  }
34
69
 
35
70
  /**
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).
71
+ * Resolves to { current, latest, command, kind, self, why? } when the registry has a newer version, else null; never throws.
72
+ * The answer is kept CACHE_MS in <EASEL_HOME>/update.json. EASEL_UPDATE_URL points the check elsewhere (tests, trying it out from a
73
+ * source checkout).
39
74
  */
40
75
  export async function checkUpdate({ current, env = process.env, root = TOOL_ROOT, home = easelHome(env), now = Date.now(), fetchImpl = fetch } = {}) {
41
76
  try {
@@ -46,18 +81,45 @@ export async function checkUpdate({ current, env = process.env, root = TOOL_ROOT
46
81
  let latest = null;
47
82
  try {
48
83
  const c = JSON.parse(readFileSync(file, "utf8"));
49
- if (c.url === url && now - c.checkedAt < DAY) latest = c.latest;
84
+ if (c.url === url && now - c.checkedAt < CACHE_MS && now >= c.checkedAt) latest = c.latest;
50
85
  } catch {}
51
86
  if (!latest) {
52
87
  const r = await fetchImpl(url, { signal: AbortSignal.timeout(2000), headers: { accept: "application/json" } });
53
88
  if (!r.ok) return null;
54
89
  latest = (await r.json())?.version;
55
- if (typeof latest !== "string") return null;
90
+ if (!validVersion(latest)) return null;
56
91
  mkdirSync(home, { recursive: true });
57
92
  writeFileSync(file, JSON.stringify({ url, checkedAt: now, latest }));
58
93
  }
59
- return isNewer(latest, current) ? { current, latest, command: updateCommand(root) } : null;
94
+ if (!validVersion(latest) || !isNewer(latest, current)) return null;
95
+ const { kind } = installKind(root);
96
+ return { current, latest, command: updateCommand(root), kind, ...selfUpdatable(root) };
60
97
  } catch {
61
98
  return null;
62
99
  }
63
100
  }
101
+
102
+ /**
103
+ * The server's view of the notice: get() answers from memory while the last check is younger than CACHE_MS, else asks again (one at a
104
+ * time); a timer asks every EVERY_MS while the canvas runs (unref'd: it never keeps the process alive). onNews(u) is told the first time
105
+ * each newer version is seen (the terminal line).
106
+ */
107
+ export function createUpdater({ current, env = process.env, root = TOOL_ROOT, home, now = () => Date.now(), fetchImpl = fetch, onNews = () => {}, every = EVERY_MS } = {}) {
108
+ let last = null; // { at, value }
109
+ let pending = null;
110
+ let told = null;
111
+ const get = () => {
112
+ if (last && now() - last.at < CACHE_MS && now() >= last.at) return Promise.resolve(last.value);
113
+ pending ??= checkUpdate({ current, env, root, home: home ?? easelHome(env), now: now(), fetchImpl })
114
+ .then((value) => {
115
+ last = { at: now(), value };
116
+ if (value && told !== value.latest) (told = value.latest), onNews(value);
117
+ return value;
118
+ })
119
+ .finally(() => (pending = null));
120
+ return pending;
121
+ };
122
+ const timer = setInterval(() => void get(), every);
123
+ timer.unref?.();
124
+ return { get, close: () => clearInterval(timer) };
125
+ }