easel-canvas 0.2.2 → 0.4.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/README.md +51 -9
- package/bin/mcp.mjs +109 -9
- package/bin/server.mjs +22 -1
- package/dist/assets/index-DuziykA0.css +1 -0
- package/dist/assets/index-o294phw7.js +74 -0
- package/dist/index.html +2 -2
- package/dist/viewer/viewer.css +1 -1
- package/dist/viewer/viewer.js +20 -14
- package/examples/demo/.thumbs/home.html.1791613627606.jpg +0 -0
- package/package.json +8 -2
- package/server/activity.mjs +17 -2
- package/server/args.mjs +5 -4
- package/server/boards.mjs +64 -8
- package/server/browser.mjs +262 -32
- package/server/edit.mjs +27 -0
- package/server/export.mjs +40 -27
- package/server/index.mjs +33 -5
- package/server/livePatch.mjs +109 -0
- package/server/occupancy.mjs +14 -3
- package/server/place.mjs +11 -0
- package/server/registry.mjs +1 -1
- package/server/requests.mjs +560 -0
- package/server/routes.mjs +123 -42
- package/server/stamps.mjs +134 -0
- package/server/up.mjs +85 -0
- package/server/watch.mjs +31 -9
- package/dist/assets/index-CjyXUlEx.css +0 -1
- package/dist/assets/index-DFCSLJXY.js +0 -66
package/server/export.mjs
CHANGED
|
@@ -9,9 +9,10 @@ import path from "node:path";
|
|
|
9
9
|
|
|
10
10
|
import { TOOL_ROOT } from "./args.mjs";
|
|
11
11
|
import { createBoardStore } from "./board.mjs";
|
|
12
|
-
import { browserStatus,
|
|
12
|
+
import { browserStatus, withPage as sharedWithPage } from "./browser.mjs";
|
|
13
13
|
import { projectName, rootOf, toPosix } from "./fsutil.mjs";
|
|
14
14
|
import { MIME, readBody, safeJoin, sendJson } from "./index.mjs";
|
|
15
|
+
import { plainComment } from "./requests.mjs";
|
|
15
16
|
import { git } from "./snapshot.mjs";
|
|
16
17
|
|
|
17
18
|
export const MANIFEST = ".easel-export.json";
|
|
@@ -404,24 +405,24 @@ async function serveDesign(dir) {
|
|
|
404
405
|
return { url: `http://127.0.0.1:${server.address().port}`, close: () => new Promise((r) => server.close(r)) };
|
|
405
406
|
}
|
|
406
407
|
|
|
407
|
-
async function renderBoards(dir, boards,
|
|
408
|
+
async function renderBoards(dir, boards, withPage) {
|
|
408
409
|
const srv = await serveDesign(dir);
|
|
409
410
|
const shots = [];
|
|
410
411
|
try {
|
|
411
412
|
for (const b of boards) {
|
|
412
|
-
let pg;
|
|
413
413
|
try {
|
|
414
|
-
|
|
414
|
+
const png = await withPage({ viewport: { width: b.w, height: b.h }, deviceScaleFactor: 2 }, async (pg) => {
|
|
415
|
+
await pg.goto(`${srv.url}/screens/${encodePath(b.file)}`, { waitUntil: "load", timeout: 20000 });
|
|
416
|
+
// The board's background (board.json bg) behind its page; only a plain colour is taken
|
|
417
|
+
if (b.bg && /^(#[0-9a-f]{3,8}|[a-z]+|rgba?\([\d\s.,%]+\))$/i.test(b.bg)) await pg.addStyleTag({ content: `html{background:${b.bg}}` });
|
|
418
|
+
await pg.waitForTimeout(150);
|
|
419
|
+
return pg.screenshot({ type: "png" });
|
|
420
|
+
});
|
|
421
|
+
shots.push({ ...b, png });
|
|
415
422
|
} catch (e) {
|
|
423
|
+
if (!e.opening) throw e;
|
|
416
424
|
throw fail(501, `PDF and PNG need a headless Chromium (${String(e.message ?? e).split("\n")[0]}). Run npx playwright install chromium.`);
|
|
417
425
|
}
|
|
418
|
-
try {
|
|
419
|
-
await pg.goto(`${srv.url}/screens/${encodePath(b.file)}`, { waitUntil: "load", timeout: 20000 });
|
|
420
|
-
await pg.waitForTimeout(150);
|
|
421
|
-
shots.push({ ...b, png: await pg.screenshot({ type: "png" }) });
|
|
422
|
-
} finally {
|
|
423
|
-
await pg.close();
|
|
424
|
-
}
|
|
425
426
|
}
|
|
426
427
|
} finally {
|
|
427
428
|
await srv.close();
|
|
@@ -429,17 +430,28 @@ async function renderBoards(dir, boards, newPage) {
|
|
|
429
430
|
return shots;
|
|
430
431
|
}
|
|
431
432
|
|
|
432
|
-
/**
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
}
|
|
433
|
+
/** Paper sizes in CSS px (96 per inch): Letter 8.5 × 11 in, A4 210 × 297 mm */
|
|
434
|
+
export const PAPER = { letter: { w: 816, h: 1056 }, a4: { w: 794, h: 1123 } };
|
|
435
|
+
|
|
436
|
+
/** The pages of one board: continuous (the default) is one page the board's own size; fixed is paper-size pages, the board scaled to
|
|
437
|
+
* the paper's width and carried over as many pages as it needs */
|
|
438
|
+
export function pagesOf(s) {
|
|
439
|
+
if (s.print !== "fixed") return [{ w: s.w, h: s.h, scale: 1, top: 0 }];
|
|
440
|
+
const paper = PAPER[s.paper] ?? PAPER.letter;
|
|
441
|
+
const scale = paper.w / s.w;
|
|
442
|
+
const n = Math.max(1, Math.ceil((s.h * scale) / paper.h - 0.001));
|
|
443
|
+
return Array.from({ length: n }, (_, k) => ({ w: paper.w, h: paper.h, scale, top: -k * paper.h }));
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/** One page per board (or per paper sheet of a fixed board), each its own size (CSS named pages) */
|
|
447
|
+
async function pdfOf(shots, withPage) {
|
|
448
|
+
const pages = shots.flatMap((s) => pagesOf(s).map((pg) => ({ ...pg, s })));
|
|
449
|
+
const css = pages.map((p, i) => `@page b${i}{size:${p.w}px ${p.h}px;margin:0}.b${i}{page:b${i};width:${p.w}px;height:${p.h}px;position:relative}.b${i} img{position:absolute;left:0;top:${p.top}px;width:${Math.round(p.s.w * p.scale)}px;height:${Math.round(p.s.h * p.scale)}px}`).join("");
|
|
450
|
+
const body = pages.map((p, i) => `<div class="b${i}"><img src="data:image/png;base64,${p.s.png.toString("base64")}" alt=""></div>`).join("");
|
|
451
|
+
return withPage(undefined, async (pg) => {
|
|
452
|
+
await pg.setContent(`<!doctype html><html><head><style>html,body{margin:0}div{break-after:page;overflow:hidden}div:last-child{break-after:auto}img{display:block}${css}</style></head><body>${body}</body></html>`, { waitUntil: "load" });
|
|
453
|
+
return pg.pdf({ preferCSSPageSize: true, printBackground: true });
|
|
454
|
+
});
|
|
443
455
|
}
|
|
444
456
|
|
|
445
457
|
/* ---------- Export ---------- */
|
|
@@ -449,7 +461,7 @@ async function pdfOf(shots, newPage) {
|
|
|
449
461
|
* scope: page (id or name) or boards ([file]); neither = everything. dryRun: build in memory and return the size only.
|
|
450
462
|
* Returns { kind, out, outRel, main, mainRel, files, bytes, skipped, deploy }.
|
|
451
463
|
*/
|
|
452
|
-
export async function exportDesign({ dir, out, store, format = "web", singleFile = false, page: pageId, boards: boardList, dryRun = false, now = new Date(),
|
|
464
|
+
export async function exportDesign({ dir, out, store, format = "web", singleFile = false, page: pageId, boards: boardList, dryRun = false, now = new Date(), withPage = sharedWithPage }) {
|
|
453
465
|
dir = path.resolve(dir);
|
|
454
466
|
if (!existsSync(path.join(dir, "screens"))) throw fail(400, `No screens/ folder in ${dir}`);
|
|
455
467
|
out = path.resolve(out ?? defaultOut(dir));
|
|
@@ -466,11 +478,11 @@ export async function exportDesign({ dir, out, store, format = "web", singleFile
|
|
|
466
478
|
let main;
|
|
467
479
|
|
|
468
480
|
if (kind === "pdf" || kind === "png") {
|
|
469
|
-
const status =
|
|
481
|
+
const status = withPage === sharedWithPage ? await browserStatus() : { ok: true };
|
|
470
482
|
if (!status.ok) throw fail(501, `PDF and PNG are unavailable here. ${status.reason}`);
|
|
471
|
-
const shots = await renderBoards(dir, scope.boards.map((f) => ({ file: f, w: board.boards[f].w, h: board.boards[f].h })),
|
|
483
|
+
const shots = await renderBoards(dir, scope.boards.map((f) => ({ file: f, w: board.boards[f].w, h: board.boards[f].h, print: board.boards[f].print, paper: board.boards[f].paper, bg: board.boards[f].bg })), withPage);
|
|
472
484
|
if (kind === "png") for (const s of shots) entries.push({ rel: `png/${s.file.replace(/\.html$/, "").replace(/\//g, "-")}@2x.png`, data: s.png });
|
|
473
|
-
else entries.push({ rel: `${slug(dir)}-canvas.pdf`, data: await pdfOf(shots,
|
|
485
|
+
else entries.push({ rel: `${slug(dir)}-canvas.pdf`, data: await pdfOf(shots, withPage) });
|
|
474
486
|
main = kind === "pdf" ? entries[0].rel : "png/";
|
|
475
487
|
} else {
|
|
476
488
|
const outInDir = out.startsWith(dir + path.sep) ? toPosix(path.relative(dir, out)) : null;
|
|
@@ -478,7 +490,8 @@ export async function exportDesign({ dir, out, store, format = "web", singleFile
|
|
|
478
490
|
const col = await collect(dir, scope.boards, exclude);
|
|
479
491
|
skipped = col.skipped;
|
|
480
492
|
const viewer = await viewerBuild();
|
|
481
|
-
|
|
493
|
+
// For AI requests travel as ordinary comments: a view-only copy has no request status or controls
|
|
494
|
+
const comments = (await readComments(dir)).filter((c) => scope.boards.includes(c.file)).map(plainComment);
|
|
482
495
|
const pick = (obj, ids) => Object.fromEntries(ids.map((id) => [id, obj[id]]));
|
|
483
496
|
const shapes = pick(board.shapes ?? {}, scope.shapes);
|
|
484
497
|
const data = {
|
package/server/index.mjs
CHANGED
|
@@ -13,8 +13,10 @@ import { createBoardStore } from "./board.mjs";
|
|
|
13
13
|
import { isTrackedRel } from "./copies.mjs";
|
|
14
14
|
import { rootOf, toPosix } from "./fsutil.mjs";
|
|
15
15
|
import { createHistory, requestScope } from "./history.mjs";
|
|
16
|
+
import { contentHash } from "./livePatch.mjs";
|
|
16
17
|
import { createOccupancy } from "./occupancy.mjs";
|
|
17
|
-
import {
|
|
18
|
+
import { createStamps } from "./stamps.mjs";
|
|
19
|
+
import { isAlive, readEntries, real, writeEntry } from "./registry.mjs";
|
|
18
20
|
import { checkUpdate } from "./update.mjs";
|
|
19
21
|
|
|
20
22
|
export const MIME = {
|
|
@@ -91,8 +93,10 @@ export function safeJoin(root, rel) {
|
|
|
91
93
|
}
|
|
92
94
|
|
|
93
95
|
// When serving screen HTML, inject an error-collecting script into <head> (the file is untouched). The parent window (canvas) gathers them into the errored boards list
|
|
94
|
-
const
|
|
95
|
-
|
|
96
|
+
const PROBE_TAG = `<script data-dc-probe data-dc-src="@SRC@">(function(){var f=decodeURIComponent(location.pathname.replace(/^\\/screens\\//,""));function send(m){try{if(parent!==window)parent.postMessage(Object.assign({type:"dc-error",file:f},m),"*")}catch(e){}}send({start:true});addEventListener("error",function(e){var t=e.target;if(t&&t!==window&&(t.src||t.href)){send({kind:"resource",message:"Failed to load: "+(t.getAttribute("src")||t.getAttribute("href"))})}else{send({kind:"script",message:String(e.message||e),line:e.lineno,col:e.colno})}},true);addEventListener("unhandledrejection",function(e){send({kind:"script",message:"Promise: "+String(e.reason&&e.reason.message||e.reason)})});addEventListener("load",function(){send({loaded:true})});function tw(){var el=document.getElementById("board-tweaks");if(!el)return;try{var d=JSON.parse(el.textContent);for(var k in d){var t=d[k];if(!t||typeof t!=="object")continue;var v=t.type==="boolean"?(t.value?"1":"0"):String(t.value)+(t.type==="number"&&t.unit?t.unit:"");if(t.var)document.documentElement.style.setProperty(t.var,v);document.documentElement.setAttribute("data-tweak-"+k,t.type==="boolean"?(t.value?"on":"off"):String(t.value))}}catch(e){send({kind:"script",message:"board-tweaks JSON error: "+e.message})}}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",tw);else tw()})()</script>`;
|
|
97
|
+
/** src: the content hash of the file as served (data-dc-src), so the app knows which version of the file a board shows */
|
|
98
|
+
export function injectProbe(html, src = contentHash(html)) {
|
|
99
|
+
const PROBE = PROBE_TAG.replace("@SRC@", src);
|
|
96
100
|
const m = /<meta[^>]*charset[^>]*>/i.exec(html) ?? /<head[^>]*>/i.exec(html) ?? /<html[^>]*>/i.exec(html) ?? /<!doctype[^>]*>/i.exec(html);
|
|
97
101
|
return m ? html.slice(0, m.index + m[0].length) + PROBE + html.slice(m.index + m[0].length) : PROBE + html;
|
|
98
102
|
}
|
|
@@ -205,7 +209,8 @@ export async function createServer({ dir, port, dev = true, extraRoutes = [], au
|
|
|
205
209
|
const occupancy = createOccupancy({ onChange: (boards) => ctx.broadcast({ type: "occupancy", boards }) });
|
|
206
210
|
history = createHistory({ ...trackedFiles(store), onStep: (step, changes) => noteWriters(occupancy, store.screensDir, step, changes) });
|
|
207
211
|
// boot: when this server started; the chat shows "Easel restarted" when it changes (the undo history did not survive)
|
|
208
|
-
|
|
212
|
+
// stamps: each board's render stamp (server/stamps.mjs), the version of its zoomed-out thumbnail
|
|
213
|
+
const ctx = { dir, store, history, occupancy, stamps: createStamps(dir), broadcast: () => {}, boot: new Date().toISOString() };
|
|
209
214
|
await history.seed();
|
|
210
215
|
|
|
211
216
|
// App UI: on startup, build once if the app source is newer than dist, then serve dist statically.
|
|
@@ -227,12 +232,35 @@ export async function createServer({ dir, port, dev = true, extraRoutes = [], au
|
|
|
227
232
|
const routes = [
|
|
228
233
|
["GET", "/api/update", async (req, res) => sendJson(res, 200, { update: await update })],
|
|
229
234
|
["GET", "/api/health", async (req, res) => sendJson(res, 200, { ok: true, dir, root: rootOf(dir), screens: screensRel, pid: process.pid })],
|
|
235
|
+
// Other Easel canvases running on this machine (the registry easel-canvas status reads), for the project menu: only those that
|
|
236
|
+
// answer for their own folder, never this one. Title from each one's board.json; nothing else of theirs is read
|
|
237
|
+
[
|
|
238
|
+
"GET",
|
|
239
|
+
"/api/projects",
|
|
240
|
+
async (req, res) => {
|
|
241
|
+
const me = real(dir);
|
|
242
|
+
const entries = readEntries().filter((e) => real(e.dir) !== me);
|
|
243
|
+
const live = (await Promise.all(entries.map(async (e) => ((await isAlive(e, 600)) ? e : null)))).filter(Boolean);
|
|
244
|
+
const projects = await Promise.all(
|
|
245
|
+
live.map(async (e) => {
|
|
246
|
+
let title = null;
|
|
247
|
+
try {
|
|
248
|
+
title = JSON.parse(await fs.readFile(path.join(e.dir, "board.json"), "utf8")).title ?? null;
|
|
249
|
+
} catch {
|
|
250
|
+
/* no title: the folder's name */
|
|
251
|
+
}
|
|
252
|
+
return { port: e.port, title: title || path.basename(e.root), root: e.root };
|
|
253
|
+
}),
|
|
254
|
+
);
|
|
255
|
+
sendJson(res, 200, { projects });
|
|
256
|
+
},
|
|
257
|
+
],
|
|
230
258
|
[
|
|
231
259
|
"GET",
|
|
232
260
|
"/api/board",
|
|
233
261
|
async (req, res) => {
|
|
234
262
|
const { board, files, missing } = await store.syncBoard();
|
|
235
|
-
sendJson(res, 200, { board, files, missing, dir, screens: screensRel });
|
|
263
|
+
sendJson(res, 200, { board, files, missing, dir, screens: screensRel, stamps: await ctx.stamps.stampAll(files) });
|
|
236
264
|
},
|
|
237
265
|
],
|
|
238
266
|
[
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// AI-generated with Claude Code, 2026-11-27
|
|
2
|
+
// Live patches: for an edit the app made, the exact DOM change that turns the board as it was loaded (before) into what a reload of
|
|
3
|
+
// the new source (after) would show, or null when that cannot be proven. The tab that made the edit applies it to the live board and
|
|
4
|
+
// skips the reload when the watcher's echo carries the same content hash (see app/src/livePatch.ts).
|
|
5
|
+
// Proof: the patch is replayed on parse5's tree of before (attributes set as setAttribute does, inner HTML parsed as innerHTML does,
|
|
6
|
+
// i.e. HTML fragment parsing in the element's context) and the result must serialize exactly like parse5's tree of after.
|
|
7
|
+
import crypto from "node:crypto";
|
|
8
|
+
|
|
9
|
+
import { parse, parseFragment, serialize } from "parse5";
|
|
10
|
+
|
|
11
|
+
import { elementChildren, findBody, isElement } from "./html.mjs";
|
|
12
|
+
|
|
13
|
+
/** Content hash of a whole board file: sent with file-changed, written into the served page (data-dc-src) and returned by /api/edit */
|
|
14
|
+
export const contentHash = (text) => crypto.createHash("sha1").update(text).digest("hex");
|
|
15
|
+
|
|
16
|
+
const HTML_NS = "http://www.w3.org/1999/xhtml";
|
|
17
|
+
/** Ops whose result can be patched in place; everything else (move, delete, insert, wrap, duplicate, tweaks) reloads */
|
|
18
|
+
const LIVE_OPS = new Set(["setText", "setStyle", "setAttr"]);
|
|
19
|
+
/** Inner HTML set by innerHTML differs from a page parse here (leading newline dropped by the parser, raw text, foster parenting) */
|
|
20
|
+
const NO_INNER = new Set("pre listing textarea title style script xmp iframe noembed noframes noscript plaintext template table tbody thead tfoot tr colgroup select option optgroup frameset head html body".split(" "));
|
|
21
|
+
/** Attributes that act only while the page loads, or that the person may have changed by using the board: a reload shows them anew */
|
|
22
|
+
const NO_ATTR = /^(on|autofocus$|value$|checked$|selected$|is$|xmlns)/i;
|
|
23
|
+
/** Script types that never run (data blocks) */
|
|
24
|
+
const DATA_SCRIPT = /^(application\/(ld\+)?json|text\/(template|plain|markdown|x-template))$/i;
|
|
25
|
+
|
|
26
|
+
/** A page whose own scripts or load-time handlers run could have changed its DOM since it loaded: only a reload shows it right */
|
|
27
|
+
function runsScripts(node) {
|
|
28
|
+
if (isElement(node)) {
|
|
29
|
+
if (node.tagName === "script") {
|
|
30
|
+
const type = node.attrs.find((a) => a.name === "type")?.value?.trim() ?? "";
|
|
31
|
+
if (!DATA_SCRIPT.test(type)) return true;
|
|
32
|
+
}
|
|
33
|
+
if (node.attrs.some((a) => /^on/i.test(a.name))) return true;
|
|
34
|
+
}
|
|
35
|
+
for (const c of node.childNodes ?? []) if (runsScripts(c)) return true;
|
|
36
|
+
if (node.content && runsScripts(node.content)) return true;
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The element at path, the way the browser's children walk finds it (never through <template> content), or null */
|
|
41
|
+
function at(doc, path) {
|
|
42
|
+
let node = findBody(doc);
|
|
43
|
+
if (!node) return null;
|
|
44
|
+
if (path === "" || path == null) return null; // body itself: its attributes reach the page's scripts and the probe; keep the reload
|
|
45
|
+
for (const part of String(path).split("/")) {
|
|
46
|
+
if (node.tagName === "template") return null;
|
|
47
|
+
node = elementChildren(node)[Number(part)];
|
|
48
|
+
if (!node) return null;
|
|
49
|
+
}
|
|
50
|
+
return node;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Ops of one request, flattened (batch → its ops) */
|
|
54
|
+
const opsOf = (req) => (req.op === "batch" ? (Array.isArray(req.ops) ? req.ops : []) : [req]);
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* before, after: the board source before and after the edit; req: the /api/edit body.
|
|
58
|
+
* → [{ path, tag, attrs?: [[name, value | null]], inner?: string }] or null (reload instead)
|
|
59
|
+
*/
|
|
60
|
+
export function livePatch(before, after, req) {
|
|
61
|
+
const ops = opsOf(req);
|
|
62
|
+
if (!ops.length || ops.some((o) => !LIVE_OPS.has(o?.op))) return null;
|
|
63
|
+
const a = parse(after, { sourceCodeLocationInfo: true });
|
|
64
|
+
const b = parse(before);
|
|
65
|
+
if (runsScripts(a) || runsScripts(b)) return null;
|
|
66
|
+
const paths = [...new Set(ops.map((o) => String(o.path ?? "")))];
|
|
67
|
+
const patch = [];
|
|
68
|
+
for (const p of paths) {
|
|
69
|
+
const na = at(a, p);
|
|
70
|
+
const nb = at(b, p);
|
|
71
|
+
if (!na || !nb || na.tagName !== nb.tagName || na.namespaceURI !== HTML_NS) return null;
|
|
72
|
+
const item = { path: p, tag: na.tagName };
|
|
73
|
+
// Attributes: new values in after's order, then removals
|
|
74
|
+
const attrs = [];
|
|
75
|
+
for (const x of na.attrs) {
|
|
76
|
+
const old = nb.attrs.find((y) => y.name === x.name && !y.namespace);
|
|
77
|
+
if (old?.value !== x.value) attrs.push([x.name, x.value]);
|
|
78
|
+
}
|
|
79
|
+
for (const y of nb.attrs) if (!na.attrs.some((x) => x.name === y.name)) attrs.push([y.name, null]);
|
|
80
|
+
if ([...na.attrs, ...nb.attrs].some((x) => x.namespace || x.prefix) && attrs.length) return null;
|
|
81
|
+
if (attrs.some(([n]) => NO_ATTR.test(n))) return null;
|
|
82
|
+
if (attrs.length) item.attrs = attrs;
|
|
83
|
+
if (ops.some((o) => o.op === "setText" && String(o.path ?? "") === p)) {
|
|
84
|
+
const st = na.sourceCodeLocation?.startTag;
|
|
85
|
+
const et = na.sourceCodeLocation?.endTag;
|
|
86
|
+
if (!st || !et || NO_INNER.has(na.tagName)) return null;
|
|
87
|
+
item.inner = after.slice(st.endOffset, et.startOffset);
|
|
88
|
+
}
|
|
89
|
+
if (item.attrs || item.inner != null) patch.push(item);
|
|
90
|
+
}
|
|
91
|
+
if (!patch.length) return null;
|
|
92
|
+
// Replay on before's tree and compare with after's: anything else that changed (or a parse difference) means reload
|
|
93
|
+
for (const item of patch) {
|
|
94
|
+
const node = at(b, item.path);
|
|
95
|
+
for (const [name, value] of item.attrs ?? []) {
|
|
96
|
+
const i = node.attrs.findIndex((x) => x.name === name);
|
|
97
|
+
if (value == null) {
|
|
98
|
+
if (i >= 0) node.attrs.splice(i, 1);
|
|
99
|
+
} else if (i >= 0) node.attrs[i] = { ...node.attrs[i], value };
|
|
100
|
+
else node.attrs.push({ name, value });
|
|
101
|
+
}
|
|
102
|
+
if (item.inner != null) {
|
|
103
|
+
const frag = parseFragment(node, item.inner);
|
|
104
|
+
node.childNodes = frag.childNodes;
|
|
105
|
+
for (const c of node.childNodes) c.parentNode = node;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return serialize(b) === serialize(parse(after)) ? patch : null;
|
|
109
|
+
}
|
package/server/occupancy.mjs
CHANGED
|
@@ -16,6 +16,8 @@ export function createOccupancy({ quietMs = QUIET_MS, doneMs = DONE_MS, onChange
|
|
|
16
16
|
/** file → { base, holders: Map<key, holder> } — holder: { key, kind, by | person, client, runs, clients, conns, since, quietUntil, doneAt, timer } */
|
|
17
17
|
const files = new Map();
|
|
18
18
|
const conns = new Map(); // WebSocket id → { file, key }
|
|
19
|
+
/** In-app runs that have ended: a write of theirs noticed after the end (the watcher can be late) must not hold a board again */
|
|
20
|
+
const ended = new Set();
|
|
19
21
|
const changed = () => onChange(snapshot());
|
|
20
22
|
const timer = (fn, ms) => {
|
|
21
23
|
const t = setTimeout(fn, ms);
|
|
@@ -70,7 +72,13 @@ export function createOccupancy({ quietMs = QUIET_MS, doneMs = DONE_MS, onChange
|
|
|
70
72
|
h.since = Date.now();
|
|
71
73
|
h.doneAt = null;
|
|
72
74
|
}
|
|
73
|
-
if (run
|
|
75
|
+
if (run && ended.has(run)) {
|
|
76
|
+
// A late write of a run that is over: the board shows the agent as done, not editing forever
|
|
77
|
+
if (!h.runs.size && !h.clients.size) {
|
|
78
|
+
h.quietUntil = 0;
|
|
79
|
+
settle(file, h);
|
|
80
|
+
}
|
|
81
|
+
} else if (run) h.runs.add(run);
|
|
74
82
|
else {
|
|
75
83
|
if (client) h.clients.add(client);
|
|
76
84
|
h.quietUntil = Date.now() + quietMs;
|
|
@@ -92,16 +100,19 @@ export function createOccupancy({ quietMs = QUIET_MS, doneMs = DONE_MS, onChange
|
|
|
92
100
|
}
|
|
93
101
|
|
|
94
102
|
function runEnded(run) {
|
|
103
|
+
ended.add(run);
|
|
104
|
+
if (ended.size > 500) ended.delete(ended.values().next().value);
|
|
95
105
|
for (const [file, r] of [...files])
|
|
96
106
|
for (const h of [...r.holders.values()])
|
|
97
|
-
|
|
107
|
+
// People on the board have no runs (an element picked there: the usual case for AI asked at the element); only agents end
|
|
108
|
+
if (h.kind === "agent" && 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
109
|
}
|
|
99
110
|
|
|
100
111
|
/** An MCP client disconnected: boards it alone kept busy are done now */
|
|
101
112
|
function clientGone(client) {
|
|
102
113
|
for (const [file, r] of [...files])
|
|
103
114
|
for (const h of [...r.holders.values()])
|
|
104
|
-
if (h.clients.delete(client) && !h.clients.size && !h.runs.size && !h.doneAt) {
|
|
115
|
+
if (h.kind === "agent" && h.clients.delete(client) && !h.clients.size && !h.runs.size && !h.doneAt) {
|
|
105
116
|
h.quietUntil = 0;
|
|
106
117
|
settle(file, h);
|
|
107
118
|
}
|
package/server/place.mjs
CHANGED
|
@@ -108,6 +108,17 @@ export function placeNew(board, size, page) {
|
|
|
108
108
|
return freeSpot(board, { x: left, y: bottom + GAP_Y, ...size }, { dir: "down", page });
|
|
109
109
|
}
|
|
110
110
|
|
|
111
|
+
/** A new board of size near a point (the view's centre) or beside board o: the nearer of the first free spot going right and the first
|
|
112
|
+
* going down, so it lands in free space close by and never on top of a board or a note */
|
|
113
|
+
export function nearSpot(board, rect, page) {
|
|
114
|
+
const right = freeSpot(board, rect, { dir: "right", page });
|
|
115
|
+
const down = freeSpot(board, rect, { dir: "down", page });
|
|
116
|
+
return Math.hypot(down.x - rect.x, down.y - rect.y) < Math.hypot(right.x - rect.x, right.y - rect.y) ? down : right;
|
|
117
|
+
}
|
|
118
|
+
export function besideOf(board, o, size) {
|
|
119
|
+
return nearSpot(board, { x: o.x + o.w + GAP_X, y: o.y, w: size.w, h: size.h }, o.page);
|
|
120
|
+
}
|
|
121
|
+
|
|
111
122
|
/** A row of n copies of board b (variants): the first free row below it */
|
|
112
123
|
export function freeRow(board, b, n) {
|
|
113
124
|
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 });
|
package/server/registry.mjs
CHANGED
|
@@ -10,7 +10,7 @@ import { DEFAULT_PORT } from "./args.mjs";
|
|
|
10
10
|
export const easelHome = (env = process.env) => env.EASEL_HOME || path.join(os.homedir(), ".easel");
|
|
11
11
|
const serversDir = (home) => path.join(home, "servers");
|
|
12
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) => {
|
|
13
|
+
export const real = (p) => {
|
|
14
14
|
const abs = path.resolve(p);
|
|
15
15
|
try {
|
|
16
16
|
return realpathSync(abs);
|