@marver-design/marver 0.26.1 → 0.27.2

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 (109) hide show
  1. package/CHANGELOG.md +198 -0
  2. package/README.md +12 -4
  3. package/dist/{anchor-check-l-ny3UzH.mjs → anchor-check-gkxkPAIv.mjs} +1 -1
  4. package/dist/{board-tree-DRioF94d.mjs → board-tree-BXR8dw4b.mjs} +3 -1
  5. package/dist/{boards-CGg6piKF.mjs → boards-BHKP5yhI.mjs} +1 -1
  6. package/dist/{boards-DYG22tOe.mjs → boards-BqUqKNW8.mjs} +4 -4
  7. package/dist/{build-BDRiO_mP.mjs → build-VgNg4rr8.mjs} +8 -23
  8. package/dist/cli.mjs +45 -19
  9. package/dist/{collab-Dxg2trOK.mjs → collab-BEAcXrBb.mjs} +1 -1
  10. package/dist/{comments-BqXua-XL.mjs → comments-YEU1Zhv9.mjs} +4 -4
  11. package/dist/{context-HQ4Giw58.mjs → context-Ccjrhr1J.mjs} +3 -3
  12. package/dist/{daemon-DL6Fwq6D.mjs → daemon-Dc9AH0M3.mjs} +9 -7
  13. package/dist/detect-C0wpaePX.mjs +125 -0
  14. package/dist/dev-lock-C_FC70Mu.mjs +65 -0
  15. package/dist/dev-ri6nAlRp.mjs +1273 -0
  16. package/dist/exclusive-B1RtpeeP.mjs +150 -0
  17. package/dist/{init-D8DtrK_F.mjs → init-W0nxR1OY.mjs} +8 -6
  18. package/dist/{link-BNzLvdhI.mjs → link-CdTgn94Y.mjs} +23 -11
  19. package/dist/ls-BZ5TAtd5.mjs +38 -0
  20. package/dist/{manifest-Nl3KSVOk.mjs → manifest-aFyDmL8C.mjs} +2 -2
  21. package/dist/{marks-DyWMv_Z1.mjs → marks-BF9pNEgH.mjs} +3 -3
  22. package/dist/{marks-CKgzucHZ.mjs → marks-CnCCfAbD.mjs} +3 -3
  23. package/dist/{marver-id-gate-BjF6v4bT.mjs → marver-id-gate-D-R0hSt_.mjs} +1 -1
  24. package/dist/perf-DkAUFT6W.mjs +1319 -0
  25. package/dist/perf-jam-BaH3Lg0m.mjs +635 -0
  26. package/dist/plugin-B8UghYuF.mjs +5242 -0
  27. package/dist/{poster-BdtSKMDm.mjs → poster-BNgafWMK.mjs} +1 -1
  28. package/dist/{profile-WU9qcbIo.mjs → profile-jIS6BcAs.mjs} +1 -1
  29. package/dist/{publish-bakes-9RzRToXV.mjs → publish-bakes-38Nja78p.mjs} +3 -3
  30. package/dist/{queue-29ok5_eZ.mjs → queue-CAM_vNmX.mjs} +1 -1
  31. package/dist/recover-B8AiI29B.mjs +66 -0
  32. package/dist/{serve-C8rVheYk.mjs → serve-Dp3nHstu.mjs} +3 -3
  33. package/dist/{share--oFJ1bCI.mjs → share-Ce4tP7ji.mjs} +1 -1
  34. package/dist/{shot-XQV7HC9A.mjs → shot-CMQgMVZm.mjs} +1 -1
  35. package/dist/{shot-DQeR_Pfn.mjs → shot-Ch24tiMO.mjs} +36 -5
  36. package/dist/slots-CFNnegCc.mjs +478 -0
  37. package/dist/{sync-DKk-yT1V.mjs → sync-CQdGARJ9.mjs} +4 -3
  38. package/dist/{work-VvX_JIgl.mjs → work-Bxz-ObF3.mjs} +4 -2
  39. package/dist/{work-F5u-twpJ.mjs → work-CNhFF9pU.mjs} +5 -3
  40. package/docs/boards-and-folders.md +3 -1
  41. package/docs/jam-session.md +57 -2
  42. package/docs/performance.md +424 -0
  43. package/package.json +2 -2
  44. package/src/client/content/index.tsx +3 -0
  45. package/src/client/content/video.tsx +16 -4
  46. package/src/client/frame-host/bridge.js +22 -6
  47. package/src/client/frame-host/main.tsx +17 -5
  48. package/src/client/shell/App.tsx +188 -26
  49. package/src/client/shell/BoardList.tsx +5 -5
  50. package/src/client/shell/Comments.tsx +8 -5
  51. package/src/client/shell/ContextMenu.tsx +5 -3
  52. package/src/client/shell/JamSurface.tsx +4 -2
  53. package/src/client/shell/LockedApp.tsx +8 -5
  54. package/src/client/shell/Play.tsx +20 -10
  55. package/src/client/shell/Tip.tsx +3 -1
  56. package/src/client/shell/Toolbar.tsx +12 -1
  57. package/src/client/shell/api.ts +233 -0
  58. package/src/client/shell/app-bridge.ts +254 -0
  59. package/src/client/shell/app-perf.ts +92 -0
  60. package/src/client/shell/canvas/Canvas.tsx +141 -21
  61. package/src/client/shell/canvas/FrameNode.tsx +22 -9
  62. package/src/client/shell/canvas/admission.ts +31 -9
  63. package/src/client/shell/canvas/camera-broadcast.ts +15 -5
  64. package/src/client/shell/canvas/ctl.ts +8 -0
  65. package/src/client/shell/canvas/frame-registry.ts +28 -2
  66. package/src/client/shell/canvas/sleep.ts +60 -17
  67. package/src/client/shell/canvas/updates.ts +2 -1
  68. package/src/client/shell/comments-store.ts +12 -4
  69. package/src/client/shell/goto.ts +22 -10
  70. package/src/client/shell/inset.ts +44 -0
  71. package/src/client/shell/jam-capture.ts +41 -22
  72. package/src/client/shell/jam-keys.ts +12 -3
  73. package/src/client/shell/jam-panel.tsx +9 -3
  74. package/src/client/shell/jam-queue.ts +3 -3
  75. package/src/client/shell/jam-session.tsx +14 -8
  76. package/src/client/shell/jam-voice.ts +55 -15
  77. package/src/client/shell/legacy-links.ts +2 -2
  78. package/src/client/shell/main.tsx +18 -1
  79. package/src/client/shell/marks-ui.tsx +5 -3
  80. package/src/client/shell/marver-app.ts +21 -0
  81. package/src/client/shell/notes.ts +8 -1
  82. package/src/client/shell/perf-run-probe.ts +34 -0
  83. package/src/client/shell/perf-run.ts +70 -0
  84. package/src/client/shell/perf.ts +80 -58
  85. package/src/client/shell/recorder-core.ts +183 -0
  86. package/src/client/shell/recorder.ts +607 -0
  87. package/src/client/shell/store.ts +294 -110
  88. package/src/client/shell/styles.css +72 -15
  89. package/src/client/shell/unsaved.ts +81 -0
  90. package/src/client/shell/whiteout-probes.ts +141 -0
  91. package/src/shared/app-api.ts +205 -0
  92. package/src/shared/app-perf.ts +308 -0
  93. package/src/shared/logo-sniff.ts +86 -0
  94. package/src/shared/machine.ts +132 -0
  95. package/src/shared/perf-run.ts +177 -0
  96. package/templates/AGENTS-embedded.md +25 -4
  97. package/templates/AGENTS-studio.md +25 -4
  98. package/templates/demo/dark.tsx +1 -1
  99. package/templates/demo/welcome.tsx +1 -1
  100. package/templates/instructions/boards.md +3 -1
  101. package/templates/instructions/welcome.md +6 -3
  102. package/dist/bake-C-awKgLA.mjs +0 -786
  103. package/dist/config-Cf7EjAMf.mjs +0 -292
  104. package/dist/dev-Bw_qYWWq.mjs +0 -755
  105. package/dist/dev-lock-DWSpa6nj.mjs +0 -179
  106. package/dist/perf-C75MZ73h.mjs +0 -167
  107. package/dist/perf-DPbLGhhO.mjs +0 -49
  108. package/dist/perf-jam-BU3TVrZu.mjs +0 -239
  109. package/dist/plugin-DkGmZs_r.mjs +0 -2423
@@ -1,14 +1,18 @@
1
1
  import { create } from 'zustand'
2
2
  import { ROUTE, slideSize } from '../const.ts'
3
3
  import { tidy, parseLayout, type BoardLayout, type TidyNode } from './tidy.ts'
4
- import { clearNoteHeights, noteHeight, noteReserve, notesCramped, setNoteHeight } from './notes.ts'
4
+ import { clearNoteHeights, noteHeight, noteReserve, notesCramped, scopeNotes, setNoteHeight } from './notes.ts'
5
5
  import { stableNodeKey } from './keys.ts'
6
6
  import { canvasCtl } from './canvas/ctl.ts'
7
+ import { api, beforeResume, canvasStopped, holdsReload, lostInResume, mvFetch, noteUnsaved, onLinkNotice, savedInResume, scoped, STOPPED_WAY, withWs } from './api.ts'
8
+ import { unsavedWhen, workChanged } from './unsaved.ts'
7
9
  // @ts-expect-error virtual module provided by the plugin
8
10
  import shConfig from 'virtual:sh-config'
9
11
  // @ts-expect-error virtual module: null in dev; a published build inlines manifest+boards
10
12
  import shData from 'virtual:sh-data'
11
13
 
14
+ scopeNotes(scoped('mv-notes')) // a per-viewer preference, kept per canvas (spec 28 A1.6)
15
+
12
16
  /** Published-build data. Non-null = static site: no API, no saves, no live events.
13
17
  * `names` is the switcher list; `default` is where `/` opens - never a synthesized
14
18
  * aggregate of a filtered build. */
@@ -124,7 +128,7 @@ export interface JamNote {
124
128
  }
125
129
  export interface Toast { id: number; text: string; jam?: JamNote }
126
130
 
127
- export const CONFIG: { viewports: Record<string, { width: number; height: number }>; themes: string[]; zoomSpeed?: number; noTheme: boolean; setup?: boolean; projectName?: string; branding?: boolean; jam?: { chime: boolean; capture: 'confirm' | 'at-once'; names?: boolean } | null; workspace?: string } = shConfig
131
+ export const CONFIG: { viewports: Record<string, { width: number; height: number }>; themes: string[]; zoomSpeed?: number; noTheme: boolean; setup?: boolean; projectName?: string; branding?: boolean; jam?: { chime: boolean; capture: 'confirm' | 'at-once'; names?: boolean } | null; workspace?: string; version?: string } = shConfig
128
132
 
129
133
  /** Invariant: `branding: false` strips every Marver mention - new chrome included. */
130
134
  export const BRANDING = CONFIG.branding !== false
@@ -197,8 +201,9 @@ export interface BoardMeta {
197
201
  export async function fetchBoardTree(): Promise<TreeSnapshot> {
198
202
  if (DATA) return { tree: DATA.tree ?? DATA.names.map((n) => ({ kind: 'board', name: n })), base: { boards: {}, folders: null }, titles: DATA.titles ?? {}, meta: DATA.meta ?? {} }
199
203
  const [boards, reg] = await Promise.all([
200
- fetch(`${ROUTE}/api/boards`).then((r) => r.json()) as Promise<{ name: string; sha256: string; order?: number; folder?: string; title?: string; type?: BoardType; status?: BoardMeta['status'] | null; settable?: StatusWord[]; error?: string }[]>,
201
- fetch(`${ROUTE}/api/folders`).then(async (r) => {
204
+ // a refusal says why in the server's own words (a symlinked design/boards: BoardList says it out loud)
205
+ api('boards').then(async (r) => { if (!r.ok) throw new Error((await r.json().catch(() => null))?.error ?? `boards ${r.status}`); return r.json() }) as Promise<{ name: string; sha256: string; order?: number; folder?: string; title?: string; type?: BoardType; status?: BoardMeta['status'] | null; settable?: StatusWord[]; error?: string }[]>,
206
+ api('folders').then(async (r) => {
202
207
  const j = await r.json() as { folders?: { name: string; order?: number; parent?: string; title?: string }[]; sha256?: string | null; error?: string }
203
208
  if (!r.ok) throw new Error(j?.error ?? `folders ${r.status}`)
204
209
  return j
@@ -239,7 +244,7 @@ export const landingBoard = async (): Promise<string> => (await fetchBoardNames(
239
244
  * off a published bundle (whose frames are all on a published board). Throws on transport failure. */
240
245
  export async function fetchMembership(): Promise<{ boards: { name: string; frames: string[] }[]; unplaced: string[] }> {
241
246
  if (!DATA) {
242
- const r = await fetch(`${ROUTE}/api/membership`)
247
+ const r = await api('membership')
243
248
  if (!r.ok) throw new Error(`membership ${r.status}`)
244
249
  return r.json()
245
250
  }
@@ -271,10 +276,10 @@ export const logReload = (entry: Record<string, unknown>) => {
271
276
  if (PUBLISHED) return
272
277
  const body = { tab: TAB, ...entry }
273
278
  // a page's very first request may go before its request cookie exists: a GET primes it, then once more
274
- void postOwner('perf/reload', body).then((r) => (r.status === 403 ? fetch(`${ROUTE}/api/work`).then(() => postOwner('perf/reload', body)) : r)).catch(() => {})
279
+ void postOwner('perf/reload', body).then((r) => (r.status === 403 ? api('work').then(() => postOwner('perf/reload', body)) : r)).catch(() => {})
275
280
  }
276
281
  const postOwner = (path: string, body: unknown) =>
277
- fetch(`${ROUTE}/api/${path}`, { method: 'POST', headers: { 'content-type': 'application/json', 'x-mv-c': csrf() }, body: JSON.stringify(body) })
282
+ api(path, { method: 'POST', headers: { 'content-type': 'application/json', 'x-mv-c': csrf() }, body: JSON.stringify(body) })
278
283
 
279
284
  /** Add to board (the Not on a board view): these frames appended to a board's file, as
280
285
  * `marver boards pin` does. The answer is said; the file change re-reads the sidebar and the view. */
@@ -313,17 +318,19 @@ const nodeKey = () => 'n_' + Math.random().toString(36).slice(2, 8)
313
318
  let manifestRev = 0
314
319
  export const bumpManifestRev = () => { manifestRev++ }
315
320
 
321
+ /** ws= binds the document to this canvas (spec 28 A1.11): another project on this port later answers a
322
+ * frame's own reload with the "another canvas" page (server/guard.ts), never with its frame. */
316
323
  export function frameUrl(frame: FrameEntry, theme: string): string {
317
- return frame.kind === 'html'
324
+ return withWs(frame.kind === 'html'
318
325
  ? `/${frame.file}?theme=${theme}&r=${manifestRev}` // r= carries the generation for the sh:ready guard (static serving ignores it)
319
- : `${ROUTE}/frame/?id=${encodeURIComponent(frame.id)}&theme=${theme}&r=${manifestRev}`
326
+ : `${ROUTE}/frame/?id=${encodeURIComponent(frame.id)}&theme=${theme}&r=${manifestRev}`)
320
327
  }
321
328
 
322
329
  /** The global view theme: the user's sticky preference, applied across boards and
323
330
  * reloads. Frames resolve to it unless they declare meta.theme or carry a user pin. */
324
331
  const initialViewTheme = () => {
325
332
  try {
326
- const t = localStorage.getItem('mv-view-theme')
333
+ const t = localStorage.getItem(scoped('mv-view-theme'))
327
334
  if (t && CONFIG.themes.includes(t)) return t
328
335
  } catch { /* storage unavailable */ }
329
336
  return CONFIG.themes[0] ?? 'light'
@@ -342,48 +349,74 @@ const measuredHeights = new Map<string, number>()
342
349
  * agent may have edited frames since), once from the bundle on a published canvas. A stale entry
343
350
  * is still the best first guess - the live measurement corrects it, and the dev shell writes the
344
351
  * correction back. */
345
- const savedHeights = new Map<string, number>()
346
- /** The frames that measure (render a Doc), as the dev server read their sources at the last load -
347
- * only theirs is a height to trust: a Doc turned bare Md keeps the size its board gives it, even
348
- * in a page that measured it as a Doc earlier. null = no such list (a published bundle ships only
349
- * measuring frames' heights). */
352
+ let savedHeights = new Map<string, number>()
353
+ /** The frames that measure (render a Doc), as the dev server read their sources at the load that
354
+ * committed - only theirs is a height to trust: a Doc turned bare Md keeps the size its board gives
355
+ * it, even in a page that measured it as a Doc earlier. null = no such list (a published bundle
356
+ * ships only measuring frames' heights). */
350
357
  let measuring: Set<string> | null = null
358
+ /** What one board load read of the sizes. Read by its request, installed by its commit (spec 28 A1.7): a
359
+ * request that never commits - another board chosen, a failed read - changes nothing the mounted board
360
+ * reads, its settle rule (settleRule) and its known heights included. */
361
+ interface SizeRead { saved: Map<string, number>; measuring: Set<string> | null }
362
+ /** Set only while a load prepares its nodes (the synchronous end of loadBoardState): the sizes it read. */
363
+ let preparing: SizeRead | null = null
364
+ const savedNow = () => preparing?.saved ?? savedHeights
351
365
  let publishedLoaded = false
352
- async function loadSavedHeights(): Promise<void> {
366
+ /** The sizes as the server has them now, for one load; null = nothing new to read (a published canvas reads its
367
+ * bundle once, here; no answer keeps what is installed). */
368
+ async function readSizes(): Promise<SizeRead | null> {
353
369
  if (DATA) {
354
- if (publishedLoaded) return
355
- publishedLoaded = true
356
- for (const [k, v] of Object.entries(DATA.sizes ?? {})) if (typeof v === 'number' && Number.isFinite(v) && v > 0) savedHeights.set(k, Math.round(v))
357
- return
370
+ if (!publishedLoaded) {
371
+ publishedLoaded = true
372
+ for (const [k, v] of Object.entries(DATA.sizes ?? {})) if (typeof v === 'number' && Number.isFinite(v) && v > 0) savedHeights.set(k, Math.round(v))
373
+ }
374
+ return null
358
375
  }
359
376
  try {
360
- const r = await fetch(`${ROUTE}/api/sizes`)
361
- if (!r.ok) return
377
+ const r = await api('sizes')
378
+ if (!r.ok) return null
362
379
  const body = (await r.json()) as { heights?: Record<string, unknown>; measuring?: unknown }
363
- savedHeights.clear()
364
- for (const [k, v] of Object.entries(body.heights ?? {})) if (typeof v === 'number' && Number.isFinite(v) && v > 0) savedHeights.set(k, Math.round(v))
365
- measuring = Array.isArray(body.measuring) ? new Set(body.measuring.filter((x): x is string => typeof x === 'string')) : null
366
- } catch { /* no cache: placeholders, as before */ }
380
+ const saved = new Map<string, number>()
381
+ for (const [k, v] of Object.entries(body.heights ?? {})) if (typeof v === 'number' && Number.isFinite(v) && v > 0) saved.set(k, Math.round(v))
382
+ return { saved, measuring: Array.isArray(body.measuring) ? new Set(body.measuring.filter((x): x is string => typeof x === 'string')) : null }
383
+ } catch { return null } // no cache: placeholders, as before
367
384
  }
368
- const measures = (frameId: string) => !measuring || measuring.has(frameId)
385
+ /** The committed load's sizes become the page's. */
386
+ function installSizes(read: SizeRead | null): void {
387
+ if (!read) return
388
+ savedHeights = read.saved
389
+ measuring = read.measuring
390
+ }
391
+ const measures = (frameId: string) => { const m = preparing ? preparing.measuring : measuring; return !m || m.has(frameId) }
369
392
 
370
393
  // settled heights that differ from the committed ones, written back in batches (dev only). One
371
394
  // write in flight at a time; a height that changes while its write is in flight queues behind it,
372
- // so the LAST settled height is the one the file ends with
395
+ // so the LAST settled height is the one the file ends with. A write the server did not take (no
396
+ // answer, or an error status) goes back in the queue - behind any newer height for the same key,
397
+ // which wins - so the heights stay unsaved until they reach the file, and is sent again after a
398
+ // wait that doubles with each failure in a row (1.5 s to 24 s)
373
399
  const pendingHeights = new Map<string, number>()
374
400
  const inflightHeights = new Map<string, number>()
375
401
  let heightsTimer: ReturnType<typeof setTimeout> | undefined
376
- let flushing = false
402
+ /** The write in flight, until it has answered and its heights are saved or queued again (the resume awaits it). */
403
+ let flushing: Promise<void> | null = null
404
+ let heightsFailed = 0
405
+ const HEIGHTS_MS = 1500
377
406
  const persistHeight = (key: string, h: number) => {
378
407
  if (DATA) return
379
- if (!inflightHeights.has(key) && savedHeights.get(key) === h) { pendingHeights.delete(key); return }
408
+ if (!inflightHeights.has(key) && savedHeights.get(key) === h) { if (pendingHeights.delete(key)) workChanged(); return }
409
+ if (!pendingHeights.size) workChanged() // heights not written yet: unsaved (unsaved.ts)
380
410
  pendingHeights.set(key, h)
381
- if (!flushing) heightsTimer ??= setTimeout(flushHeights, 1500) // a throttle, not a debounce: a board settling in waves still writes
411
+ if (!flushing) heightsTimer ??= setTimeout(flushHeights, HEIGHTS_MS) // a throttle, not a debounce: a board settling in waves still writes
382
412
  }
383
- async function flushHeights() {
413
+ async function flushHeights(): Promise<void> {
384
414
  heightsTimer = undefined
385
- if (flushing || !pendingHeights.size) return
386
- flushing = true
415
+ if (flushing) return flushing
416
+ if (!pendingHeights.size) return
417
+ if (canvasStopped()) return // held until the canvas answers again (A1.11): the resume flushes them
418
+ let done = () => {}
419
+ flushing = new Promise<void>((r) => { done = r })
387
420
  const batch = Object.fromEntries([...pendingHeights].slice(0, 500))
388
421
  for (const [k, v] of Object.entries(batch)) { pendingHeights.delete(k); inflightHeights.set(k, v) }
389
422
  let answered = false
@@ -396,16 +429,29 @@ async function flushHeights() {
396
429
  }
397
430
  } catch { /* lost: below */ }
398
431
  // no answer = the write may or may not have landed: what the file holds is unknown, so nothing is
399
- // deduplicated against it - a correction queued meanwhile still goes, the next report still writes
400
- if (!answered) for (const k of Object.keys(batch)) savedHeights.delete(k)
432
+ // deduplicated against it - a correction queued meanwhile still goes, the next report still writes.
433
+ // Each of its heights is owed again, unless a newer one for that key is already queued
434
+ if (!answered) for (const [k, v] of Object.entries(batch)) { savedHeights.delete(k); if (!pendingHeights.has(k)) pendingHeights.set(k, v) }
401
435
  for (const k of Object.keys(batch)) inflightHeights.delete(k)
402
436
  // a height that settled while the write was in flight: still owed only if it differs from what landed
403
437
  for (const [k, v] of pendingHeights) if (savedHeights.get(k) === v) pendingHeights.delete(k)
404
- flushing = false
405
- if (pendingHeights.size) heightsTimer ??= setTimeout(flushHeights, 1500)
438
+ heightsFailed = answered ? 0 : Math.min(heightsFailed + 1, 5)
439
+ flushing = null
440
+ workChanged()
441
+ if (pendingHeights.size) heightsTimer ??= setTimeout(flushHeights, HEIGHTS_MS * 2 ** Math.max(0, heightsFailed - 1))
442
+ done()
443
+ }
444
+ /** Every height this page measured is in the file: none queued, none in flight. */
445
+ const heightsSaved = () => !pendingHeights.size && !inflightHeights.size
446
+ /** The resume's turn (A1.11): the write in flight answers first, then what is queued goes now - unless it is waiting
447
+ * out a failure's backoff, which its own timer sends. True once every height is in the file. */
448
+ async function settleHeights(): Promise<boolean> {
449
+ await flushing
450
+ if (pendingHeights.size && !(heightsFailed && heightsTimer)) { clearTimeout(heightsTimer); await flushHeights() }
451
+ return heightsSaved()
406
452
  }
407
453
 
408
- const hasKnownHeight = (frameId: string, w: number) => measures(frameId) && (measuredHeights.has(`${frameId}@${w}`) || savedHeights.has(`${frameId}@${w}`))
454
+ const hasKnownHeight = (frameId: string, w: number) => measures(frameId) && (measuredHeights.has(`${frameId}@${w}`) || savedNow().has(`${frameId}@${w}`))
409
455
 
410
456
  /** The Doc sizes a layout was computed around: each auto content node whose height is known, by key,
411
457
  * as "WxH" (one line per node in the board file). A composed board saves it with its positions
@@ -439,7 +485,7 @@ function defaultSize(frame: FrameEntry) {
439
485
  const vp = CONFIG.viewports[frame.viewport ?? '']
440
486
  const w = vp?.width ?? frame.contentWidth
441
487
  const key = `${frame.id}@${w}`
442
- const known = measures(frame.id) ? measuredHeights.get(key) ?? savedHeights.get(key) : undefined
488
+ const known = measures(frame.id) ? measuredHeights.get(key) ?? savedNow().get(key) : undefined
443
489
  return { w, h: known ?? vp?.height ?? Math.round(w * 0.75) }
444
490
  }
445
491
  const vp = CONFIG.viewports[frame.viewport ?? ''] ?? CONFIG.viewports.mobile ?? { width: 390, height: 844 }
@@ -450,6 +496,58 @@ let resizedInGesture = false
450
496
  // set inside the store (they need it): a reload's height hold, and the marks-vs-documents check
451
497
  let holdHeight: (key: string) => void = () => {}
452
498
  let reconcile: () => void = () => {}
499
+
500
+ // ---- the recorder's view of the store (spec 28 A1.7) -------------------------------------------------------------
501
+ /** A change that moves or resizes nodes runs under a cause. The recorder's subscriber reads it while that change
502
+ * notifies it (zustand notifies inside set) and calls a move outside any cause `unknown`. The inner cause wins -
503
+ * except that runTidy keeps an outer one (a device preset, a resize, a reflow tidies through it). Synchronous code
504
+ * only: a cause never spans an await. */
505
+ let geoCause: string | null = null
506
+ export const geometryCause = (): string | null => geoCause
507
+ export function withCause<T>(cause: string, fn: () => T): T {
508
+ const was = geoCause
509
+ geoCause = cause
510
+ try { return fn() } finally { geoCause = was }
511
+ }
512
+ /** How a board load started: the page's first, a switch, or the open board read from disk again. */
513
+ export type LoadCause = 'boot' | 'switch' | 'disk-reload'
514
+ /** Why a requested load never committed: a newer load, a failed read, an edit or a board change meanwhile, unsaved edits. */
515
+ export type RequestCut = 'superseded' | 'error' | 'edited' | 'unsaved'
516
+ /** Board loads as the recorder sees them: recorder.ts installs these on a dev canvas - no-ops until then, and for good
517
+ * on a published one. A request owns the geometry from its commit, and `commit` runs right BEFORE the set that
518
+ * mounts the load: mounting it is never a move. */
519
+ export const recorderHooks = {
520
+ request: (_board: string, _cause: LoadCause): string => '',
521
+ /** a request is about to commit: the load that was up ends - before the incoming sizes are installed, so it ends by
522
+ * the sizes it read (which frames measure), its board's nodes still in the store */
523
+ handover: (_request: string): void => {},
524
+ commit: (_request: string, _nodes: readonly Node[], _manifest: Manifest): void => {},
525
+ cut: (_request: string, _reason: RequestCut): void => {},
526
+ /** nothing of the reflow story is left: no reflow pending, no height held, none owed */
527
+ reflowIdle: (): void => {},
528
+ }
529
+ let reflowIdleNow: () => boolean = () => true // set inside the store
530
+ /** switchBoard's calls so far - each switch, and each cancel (a switch to the board on screen): the router tells the
531
+ * second event of one navigation from a new one by nothing having switched since the first (App.tsx). */
532
+ let switchCalls = 0
533
+ export const switchCount = (): number => switchCalls
534
+ /** No reflow pending, no height held, none owed. */
535
+ export const reflowIdle = (): boolean => reflowIdleNow()
536
+ /** What a node waits for before its load settles (recorder.ts): a content frame that measures (renders a Doc) - a
537
+ * settled height at its width now; any other frame (hi-fi, html, a device-sized one, content without a Doc) - its
538
+ * ready; a frame not in the manifest - nothing: it is missing. */
539
+ export function settleRule(n: Node, manifest: Manifest | null): 'measure' | 'ready' | 'missing' {
540
+ const f = n.missing ? undefined : manifest?.frames.find((x) => x.id === n.frame)
541
+ if (!f) return 'missing'
542
+ return f.contentWidth && n.sizeMode !== 'device' && measures(f.id) ? 'measure' : 'ready'
543
+ }
544
+ /** Did a measuring node open at a height already known (committed in _sizes.json, or measured earlier in this page)? */
545
+ export const knownHeight = (frameId: string, w: number): boolean => hasKnownHeight(frameId, Math.round(w))
546
+ /** What measureNode took: `fit` - the report was taken at the node's width `w` (applied, or its height already) - the
547
+ * only one a settled report settles a node with; `width` - it adopted the Doc's own width `w`, and the next report is
548
+ * the one; `held` - kept for when the node's reload lets go; `ignored` - not taken. */
549
+ export interface MeasureResult { took: 'ignored' | 'held' | 'width' | 'fit'; w?: number }
550
+ const IGNORED: MeasureResult = { took: 'ignored' }
453
551
  // sidebar marks: the fetch in flight, and acknowledgements the server has not confirmed yet
454
552
  let marksSeq = 0
455
553
  let marksTimer: ReturnType<typeof setTimeout> | undefined
@@ -543,7 +641,7 @@ interface State {
543
641
  resizeNode(key: string, w: number, h: number): void
544
642
  /** `settled`: the Doc's fonts, images and diagrams are done (content/index.tsx). false = provisional
545
643
  * (an image still loading) - it may grow a frame, never shrink it under a known height. */
546
- measureNode(key: string, frameId: string, ownWidth: number, measuredWidth: number, height: number, settled?: boolean): void
644
+ measureNode(key: string, frameId: string, ownWidth: number, measuredWidth: number, height: number, settled?: boolean): MeasureResult
547
645
  /** A node's sticky column was drawn (or grew, or went): its extent from the node's top, world px. */
548
646
  noteMeasured(key: string, height: number): void
549
647
  setStatus(key: string, status: Node['status'], error?: string): void
@@ -644,12 +742,21 @@ export function frameIsLeased(frameId: string, s: State): boolean {
644
742
  !!s.externalLeases[n.key]))
645
743
  }
646
744
 
745
+ /** What a board save says when the board's file changed on disk meanwhile: the file wins, the board is read again. */
746
+ export const DISK_WON = 'board changed on disk - canvas layout reloaded'
747
+ /** What a board save says when the board was renamed or removed meanwhile: it is not created again. */
748
+ export const BOARD_GONE = 'this board was renamed or removed - not recreating it'
749
+
647
750
  export const useStore = create<State>((set, get) => {
648
751
  let saveTimer: ReturnType<typeof setTimeout> | undefined
649
752
  let saveChain: Promise<boolean> = Promise.resolve(true) // saves are serialized; responses only commit if the board is still active
650
753
  let editRev = 0 // bumps per edit; a stale save response may never clear dirty over a newer edit
651
754
  let loadSeq = 0 // stale boot() responses never overwrite a newer board
652
755
  let switchSeq = 0 // last click wins when board switches race
756
+ let firstLoad = true // the page's first boot() is its boot; every later one reads the board from disk again
757
+ // the recorder's requests in flight (spec 28 A1.7): a newer boot, a newer switch, or a switch that commits supersedes
758
+ // them the moment it does - not when their fetch answers, which may be never
759
+ let bootRequest = '', switchRequest = ''
653
760
  // While a board file is being renamed or rewritten by a structural write (rename, the
654
761
  // sidebar's tree arrange), autosave must not fire against it (a mustExist PUT would
655
762
  // 409-gone and clear dirty, losing the in-flight edit; a stale baseHash would 409 and
@@ -671,12 +778,17 @@ export const useStore = create<State>((set, get) => {
671
778
  // two conditions pending are EITHER one (a later ask never drops an earlier one).
672
779
  let reflowTimer: ReturnType<typeof setTimeout> | undefined
673
780
  let reflowCheck: (() => boolean) | null = null
781
+ /** Why the pending reflow runs (spec 28 A1.7) - merged across the calls it coalesces, kept through a drag, a camera
782
+ * in flight and held heights: the recorder names its moves `reflow:<reasons>`. */
783
+ type ReflowReason = 'measured' | 'cramped' | 'stale' | 'gesture-end'
784
+ let reflowReasons = new Set<ReflowReason>()
674
785
  /** A board load (boot, switch) starts its own reflow story: whatever was pending - an
675
786
  * unconditional reflow from the board that was up - must never carry over and tidy this one. */
676
- const cancelReflow = () => { clearTimeout(reflowTimer); reflowTimer = undefined; reflowCheck = null }
787
+ const cancelReflow = () => { clearTimeout(reflowTimer); reflowTimer = undefined; reflowCheck = null; reflowReasons = new Set() }
677
788
  /** How long a content reflow waits for a camera in flight - past it, the rows move anyway. */
678
789
  const REFLOW_CAMERA_WAIT = 1500
679
- const scheduleReflow = (onlyIf?: () => boolean, delay = 400, cameraSince?: number) => {
790
+ const scheduleReflow = (reason: ReflowReason | null, onlyIf?: () => boolean, delay = 400, cameraSince?: number) => {
791
+ if (reason) reflowReasons.add(reason)
680
792
  const boardAt = get().board
681
793
  const prev = reflowTimer !== undefined ? reflowCheck : undefined // undefined: nothing pending
682
794
  reflowCheck = prev === null || !onlyIf ? null : prev ? () => prev() || onlyIf() : onlyIf
@@ -686,20 +798,23 @@ export const useStore = create<State>((set, get) => {
686
798
  const check = reflowCheck
687
799
  reflowCheck = null
688
800
  const s = get()
689
- if (s.board !== boardAt) return
801
+ if (s.board !== boardAt) { reflowReasons = new Set(); reflowSettled(); return }
690
802
  // defer, never drop - retries after the drag
691
- if (s.gesture) { scheduleReflow(check ?? undefined); return }
803
+ if (s.gesture) { scheduleReflow('gesture-end', check ?? undefined); return }
692
804
  // and after a camera flight: a link's fit lands first, then the rows move around the frames it
693
805
  // showed (holdView keeps them where the fit put them). Looked at often, so the reflow follows the
694
806
  // landing closely - and never waited on past REFLOW_CAMERA_WAIT: a camera that keeps moving (fit
695
807
  // after fit) does not hold the rows apart forever
696
808
  const since = cameraSince ?? Date.now()
697
- if (canvasCtl.cameraBusy() && Date.now() - since < REFLOW_CAMERA_WAIT) { scheduleReflow(check ?? undefined, 60, since); return }
698
- if (check && !check()) return
809
+ if (canvasCtl.cameraBusy() && Date.now() - since < REFLOW_CAMERA_WAIT) { scheduleReflow(null, check ?? undefined, 60, since); return }
810
+ if (check && !check()) { reflowReasons = new Set(); reflowSettled(); return }
699
811
  for (const k of [...holds.keys()]) if (!s.nodes.some((n) => n.key === k && !n.missing)) letGo(k, false) // gone: no longer in the batch
700
- if (holds.size) { reflowOwed = true; return } // a batch is reloading: the rows move once, when it lets go
812
+ if (holds.size) { reflowOwed = true; return } // a batch is reloading: the rows move once, when it lets go (its reasons kept)
813
+ const why = `reflow:${[...reflowReasons].sort().join('+') || 'measured'}`
814
+ reflowReasons = new Set()
701
815
  // content moved the rows, not the human: hold what they are looking at still (Canvas.tsx)
702
- if (composed(s)) { canvasCtl.holdView(); s.runTidy() }
816
+ if (composed(s)) withCause(why, () => { canvasCtl.holdView(); s.runTidy() })
817
+ reflowSettled()
703
818
  }, delay)
704
819
  }
705
820
  /** Boards whose layout the shell owns: a recipe, scene rows, or the auto board. Room for a
@@ -723,11 +838,15 @@ export const useStore = create<State>((set, get) => {
723
838
  clearTimeout(h.timer)
724
839
  holds.delete(key)
725
840
  if (apply && h.last) get().measureNode(...h.last)
726
- if (!holds.size && reflowOwed) { reflowOwed = false; scheduleReflow() }
841
+ if (!holds.size && reflowOwed) { reflowOwed = false; scheduleReflow(null) }
842
+ else reflowSettled()
727
843
  }
728
844
  const dropHolds = () => { for (const h of holds.values()) clearTimeout(h.timer); holds.clear(); reflowOwed = false }
729
845
  /** A content measure moved the rows: once, after the last held node lets go. */
730
- const reflowAfterHolds = () => { if (holds.size) reflowOwed = true; else scheduleReflow() }
846
+ const reflowAfterHolds = () => { reflowReasons.add('measured'); if (holds.size) reflowOwed = true; else scheduleReflow('measured') }
847
+ /** The recorder hears when nothing of the reflow story is left (spec 28 A1.7): no timer, no held height, none owed. */
848
+ reflowIdleNow = () => reflowTimer === undefined && !holds.size && !reflowOwed
849
+ const reflowSettled = () => { if (reflowIdleNow()) recorderHooks.reflowIdle() }
731
850
 
732
851
  // Marks (spec 26): a node that shows an older revision than its frame's `doc` has missed an update
733
852
  // (an event lost while disconnected, an edit that landed while it loaded): it goes stale. The
@@ -765,7 +884,7 @@ export const useStore = create<State>((set, get) => {
765
884
 
766
885
  /** A note may have landed with no room (a frame note via the manifest, a scene note via
767
886
  * sh:scenes, either merged late by boot/switch): a composed board re-applies its layout. */
768
- const roomForNotes = () => { if (composed(get()) && cramped()) scheduleReflow(cramped) }
887
+ const roomForNotes = () => { if (composed(get()) && cramped()) scheduleReflow('cramped', cramped) }
769
888
  /** A composed board's saved positions were laid out around the heights of the session that saved
770
889
  * them. A committed height that changed since (the doc grew or shrank while another board was
771
890
  * open) opens at its new size over - or far above - the row below, and no measurement will re-flow
@@ -790,7 +909,7 @@ export const useStore = create<State>((set, get) => {
790
909
  }
791
910
  const recheckLayout = () => {
792
911
  const s = get()
793
- if (composed(s) && s.nodes.some((n) => n.sizeMode === 'auto' && hasKnownHeight(n.frame, Math.round(n.w)))) scheduleReflow(layoutStale)
912
+ if (composed(s) && s.nodes.some((n) => n.sizeMode === 'auto' && hasKnownHeight(n.frame, Math.round(n.w)))) scheduleReflow('stale', layoutStale)
794
913
  }
795
914
 
796
915
  /** Theme resolution ladder: user pin > the frame's declared meta.theme > viewTheme. */
@@ -834,22 +953,23 @@ export const useStore = create<State>((set, get) => {
834
953
  },
835
954
  }
836
955
 
837
- /** Fetch + normalize a board into ready-to-commit state, WITHOUT touching the store.
956
+ /** Fetch + normalize a board into ready-to-commit state, WITHOUT touching the store - nor the sizes the
957
+ * mounted board reads: those it read come back with it, for the commit to install (installSizes).
838
958
  * null = failure (transport, malformed manifest, non-404 board error) - the caller
839
959
  * keeps whatever board is currently mounted. */
840
- const loadBoardState = async (boardName: string): Promise<Partial<State> | null> => {
960
+ const loadBoardState = async (boardName: string): Promise<{ state: Partial<State>; sizes: SizeRead | null } | null> => {
841
961
  clearNoteHeights() // heights are per column drawn; a key shared by two board files carries none across
842
962
  loadErrors.delete(boardName)
843
963
  try {
844
964
  let raw: any
845
- const saved = loadSavedHeights() // in parallel with the manifest; every size below reads it
965
+ const saved = readSizes() // in parallel with the manifest; every size below reads it
846
966
  if (DATA) raw = DATA.manifest
847
967
  else {
848
- const mRes = await fetch('/design/manifest.json')
968
+ const mRes = await mvFetch('/design/manifest.json')
849
969
  if (!mRes.ok) return null
850
970
  raw = await mRes.json().catch(() => undefined)
851
971
  }
852
- await saved
972
+ const sizes = await saved
853
973
  if (raw === undefined || raw === null || typeof raw !== 'object') return null
854
974
  bumpManifestRev() // fresh manifest → fresh iframe URLs
855
975
  const manifest: Manifest = {
@@ -878,7 +998,7 @@ export const useStore = create<State>((set, get) => {
878
998
  const scenes = [...new Set(manifest.frames.filter((f) => m?.unplaced.includes(f.id)).map((f) => f.scene))]
879
999
  loaded = m ? { board: { nodes: m.unplaced.map((frame) => ({ frame })), ...(scenes.length ? { layout: { rows: [scenes] } } : {}) }, sha256: '' } : null
880
1000
  } else {
881
- const res = await fetch(`${ROUTE}/api/boards/${boardName}`)
1001
+ const res = await api(`boards/${boardName}`)
882
1002
  if (res.ok) {
883
1003
  const body = await res.json()
884
1004
  loaded = body?.board == null ? 'fresh' : body // board:null = not materialized yet
@@ -887,6 +1007,9 @@ export const useStore = create<State>((set, get) => {
887
1007
  else { loadErrors.set(boardName, (await res.json().catch(() => null))?.error ?? ''); loaded = null } // anything else must not commit an empty canvas - and says why (#6)
888
1008
  }
889
1009
  if (loaded === null) return null
1010
+ // from here to the return nothing is awaited: the sizes this load read are the ones its nodes are made from,
1011
+ // and no other code runs meanwhile to read them in place of the mounted board's
1012
+ preparing = sizes
890
1013
  if (loaded !== 'fresh') {
891
1014
  const { board, sha256 } = loaded
892
1015
  boardHash = sha256
@@ -1033,8 +1156,8 @@ export const useStore = create<State>((set, get) => {
1033
1156
  if (layout && boardHash && !needTidy && !cramped && nodes.length) {
1034
1157
  tidy(tidyInput(nodes, manifest), layout, layoutWarn, knownScenes(manifest))
1035
1158
  }
1036
- return { manifest, nodes, boardHash, boardAuto, deviceView, sceneRows, layout, layoutRaw, baseLayout, laidOut, baseLaidOut, selection: [], dirty: prunedAtLoad || cramped }
1037
- } catch { return null }
1159
+ return { state: { manifest, nodes, boardHash, boardAuto, deviceView, sceneRows, layout, layoutRaw, baseLayout, laidOut, baseLaidOut, selection: [], dirty: prunedAtLoad || cramped }, sizes }
1160
+ } catch { return null } finally { preparing = null }
1038
1161
  }
1039
1162
 
1040
1163
  return {
@@ -1045,14 +1168,22 @@ export const useStore = create<State>((set, get) => {
1045
1168
 
1046
1169
  async boot(mayCommit) {
1047
1170
  const seq = ++loadSeq
1171
+ recorderHooks.cut(bootRequest, 'superseded')
1048
1172
  const boardName = get().board
1173
+ // the recorder's request (spec 28 A1.7): the page's first load, else the open board read from disk again
1174
+ const request = bootRequest = recorderHooks.request(boardName, firstLoad ? 'boot' : 'disk-reload')
1175
+ firstLoad = false
1049
1176
  const revAtStart = editRev, scenesAtStart = scenesRev
1050
- const next = await loadBoardState(boardName)
1051
- if (seq !== loadSeq) return false // a newer load superseded this one
1052
- if (!next) { get().toast(`board "${boardName}" failed to load${whyNot(boardName)}`); return false }
1177
+ const loaded = await loadBoardState(boardName)
1178
+ if (seq !== loadSeq) { recorderHooks.cut(request, 'superseded'); return false } // a newer load superseded this one
1179
+ if (!loaded) { recorderHooks.cut(request, 'error'); get().toast(`board "${boardName}" failed to load${whyNot(boardName)}`); return false }
1053
1180
  // the user kept editing while we fetched - their newer state wins over the reload
1054
- if (get().board !== boardName || editRev !== revAtStart || (mayCommit && !mayCommit())) return false
1181
+ if (get().board !== boardName || editRev !== revAtStart || (mayCommit && !mayCommit())) { recorderHooks.cut(request, 'edited'); return false }
1182
+ const next = loaded.state
1055
1183
  const live = get().manifest // a WS manifest update may have landed mid-fetch
1184
+ recorderHooks.handover(request) // the load that was up ends by its own sizes
1185
+ installSizes(loaded.sizes) // the sizes this load read are the page's from its commit
1186
+ recorderHooks.commit(request, next.nodes as Node[], next.manifest as Manifest) // before the set: mounting is not a move
1056
1187
  set(next)
1057
1188
  cancelReflow(); dropHolds(); reloadCause.clear()
1058
1189
  if (next.dirty) scheduleSave() // load-time prune must reach the disk
@@ -1065,31 +1196,41 @@ export const useStore = create<State>((set, get) => {
1065
1196
 
1066
1197
  async switchBoard(name) {
1067
1198
  const mySwitch = ++switchSeq // also cancels any pending switch (incl. re-clicking the current board)
1199
+ switchCalls++
1200
+ recorderHooks.cut(switchRequest, 'superseded')
1068
1201
  const scenesAtStart = scenesRev
1069
1202
  if (name === get().board) return
1203
+ // the recorder's request (spec 28 A1.7): the wait starts here, the flush included; the board still mounted
1204
+ // owns the geometry until this one commits
1205
+ const request = switchRequest = recorderHooks.request(name, 'switch')
1070
1206
  // a resize held across a switch: settle THIS board (retidy if it has a recipe)
1071
1207
  // before the flush, so the torn mid-gesture state is never what reaches disk
1072
1208
  if (resizedInGesture) {
1073
1209
  resizedInGesture = false
1074
- if (get().layout || get().sceneRows?.length) get().runTidy()
1210
+ if (get().layout || get().sceneRows?.length) withCause('resize', () => get().runTidy())
1075
1211
  }
1076
1212
  // flush loop: an edit landing mid-save keeps dirty set and gets its own pass
1077
1213
  let ok = true
1078
1214
  for (let i = 0; i < 5 && get().dirty && ok; i++) { clearTimeout(saveTimer); ok = await get().save() }
1079
- if (mySwitch !== switchSeq) return
1080
- if (get().dirty) { get().toast('current board could not be saved - staying here'); return }
1215
+ if (mySwitch !== switchSeq) return recorderHooks.cut(request, 'superseded')
1216
+ if (get().dirty) { recorderHooks.cut(request, 'unsaved'); get().toast('current board could not be saved - staying here'); return }
1081
1217
  // load the target while the current board stays mounted; commit atomically on success -
1082
1218
  // there is never an empty intermediate state and nothing to roll back
1083
- const next = await loadBoardState(name)
1084
- if (mySwitch !== switchSeq) return
1085
- if (!next) { get().toast(`could not load "${name}"${whyNot(name)} - staying on ${get().board}`); return }
1219
+ const loaded = await loadBoardState(name)
1220
+ if (mySwitch !== switchSeq) return recorderHooks.cut(request, 'superseded')
1221
+ if (!loaded) { recorderHooks.cut(request, 'error'); get().toast(`could not load "${name}"${whyNot(name)} - staying on ${get().board}`); return }
1222
+ const next = loaded.state
1086
1223
  // edits may have landed on the still-mounted old board during the target load
1087
1224
  for (let i = 0; i < 5 && get().dirty && ok; i++) { clearTimeout(saveTimer); ok = await get().save() }
1088
- if (mySwitch !== switchSeq) return
1089
- if (get().dirty) { get().toast('current board could not be saved - staying here'); return }
1225
+ if (mySwitch !== switchSeq) return recorderHooks.cut(request, 'superseded')
1226
+ if (get().dirty) { recorderHooks.cut(request, 'unsaved'); get().toast('current board could not be saved - staying here'); return }
1090
1227
  clearTimeout(saveTimer) // a scheduled-but-clean timer must not fire against the new board
1091
1228
  ++loadSeq // invalidate any in-flight boot of the old board
1229
+ recorderHooks.cut(bootRequest, 'superseded')
1092
1230
  const live = get().manifest // a WS manifest update may have landed mid-load
1231
+ recorderHooks.handover(request) // the load that was up ends by its own sizes
1232
+ installSizes(loaded.sizes) // the sizes this load read are the page's from its commit
1233
+ recorderHooks.commit(request, next.nodes as Node[], next.manifest as Manifest) // before the set: mounting is not a move
1093
1234
  set({ board: name, interact: null, ...next })
1094
1235
  cancelReflow(); dropHolds(); reloadCause.clear()
1095
1236
  if (next.dirty) scheduleSave() // load-time prune must reach the disk
@@ -1318,13 +1459,14 @@ export const useStore = create<State>((set, get) => {
1318
1459
  toast(dropped === 1 ? 'removed 1 deleted frame' : `removed ${dropped} deleted frames`)
1319
1460
  }
1320
1461
  }
1321
- set((s) => ({
1462
+ // a guessed size corrected above (in place) is a move, seen when this set notifies the recorder
1463
+ withCause('manifest', () => set((s) => ({
1322
1464
  manifest: m,
1323
1465
  nodes: changed || retinted ? [...final] : final,
1324
1466
  selection: s.selection.filter((k) => final.some((n) => n.key === k)),
1325
1467
  interact: s.interact && final.some((n) => n.key === s.interact) ? s.interact : null,
1326
1468
  ...(changed ? { dirty: true, baseLayout: nextBase } : {}),
1327
- }))
1469
+ })))
1328
1470
  if (changed) scheduleSave()
1329
1471
  roomForNotes() // a frame note file arrived: room in front of its frame
1330
1472
  },
@@ -1343,15 +1485,15 @@ export const useStore = create<State>((set, get) => {
1343
1485
  frameFor(node) { return get().manifest?.frames.find((f) => f.id === node.frame) },
1344
1486
 
1345
1487
  moveNode(key, x, y) {
1346
- set((s) => ({ nodes: s.nodes.map((n) => (n.key === key ? { ...n, x, y } : n)), dirty: true }))
1488
+ withCause('drag', () => set((s) => ({ nodes: s.nodes.map((n) => (n.key === key ? { ...n, x, y } : n)), dirty: true })))
1347
1489
  scheduleSave()
1348
1490
  },
1349
1491
  // group drag: every selected node moves by the same delta from its gesture-start position
1350
1492
  moveSelectedBy(dx, dy, starts) {
1351
- set((s) => ({
1493
+ withCause('drag', () => set((s) => ({
1352
1494
  nodes: s.nodes.map((n) => (starts[n.key] ? { ...n, x: starts[n.key].x + dx, y: starts[n.key].y + dy } : n)),
1353
1495
  dirty: true,
1354
- }))
1496
+ })))
1355
1497
  scheduleSave()
1356
1498
  },
1357
1499
  // scoped theme = an explicit per-frame PIN; it survives board reloads and yields
@@ -1368,7 +1510,7 @@ export const useStore = create<State>((set, get) => {
1368
1510
  const inGesture = get().gesture
1369
1511
  // a manual resize means the board no longer uniformly shows one device; the resized
1370
1512
  // frame's snapshot entry follows the user's new size so Default will not undo it
1371
- set((s) => {
1513
+ withCause('resize', () => set((s) => {
1372
1514
  const W = Math.max(120, w), H = Math.max(80, h)
1373
1515
  const cur = s.nodes.find((n) => n.key === key)
1374
1516
  // a human-resized CONTENT frame goes 'manual': measurements never overwrite it
@@ -1382,7 +1524,7 @@ export const useStore = create<State>((set, get) => {
1382
1524
  ? { ...s.baseLayout, [key]: { ...(s.baseLayout[key] ?? { x: cur.x, y: cur.y }), w: W, h: H } }
1383
1525
  : s.baseLayout,
1384
1526
  }
1385
- })
1527
+ }))
1386
1528
  // mid-gesture saves would persist torn state (new sizes, pre-recipe positions);
1387
1529
  // the gesture-end hook saves once, after any retidy
1388
1530
  if (!inGesture) scheduleSave()
@@ -1399,22 +1541,23 @@ export const useStore = create<State>((set, get) => {
1399
1541
  // auto-fit height: a content frame must always grow/shrink to show ALL its content, even after
1400
1542
  // the human drags its WIDTH. 'manual' just means the human owns the WIDTH; the
1401
1543
  // HEIGHT is still measured, so resizing width reflows and refits height (no clipped/empty frame).
1402
- if (!node || node.sizeMode === 'device') return
1403
- if (node.frame !== frameId) return // generation guard: a reused node key
1544
+ if (!node || node.sizeMode === 'device') return IGNORED
1545
+ if (node.frame !== frameId) return IGNORED // generation guard: a reused node key
1404
1546
  // across a board switch never mis-attributes
1405
1547
  const f = s.manifest?.frames.find((x) => x.id === node.frame)
1406
- if (!f?.contentWidth) return // not a content frame - spoof-proofing
1407
- if (![ownWidth, measuredWidth, height].every((v) => Number.isFinite(v) && v > 0)) return
1548
+ if (!f?.contentWidth) return IGNORED // not a content frame - spoof-proofing
1549
+ if (![ownWidth, measuredWidth, height].every((v) => Number.isFinite(v) && v > 0)) return IGNORED
1408
1550
  // a Doc that reports IS one, whatever the last load's scan said (it arrived since): its heights
1409
1551
  // count until the next load re-reads the sources
1410
1552
  measuring?.add(f.id)
1411
1553
  // held while it reloads (spec 26): only a settled measure lands now; the last other one waits
1412
1554
  const held = holds.get(key)
1413
1555
  if (held) {
1414
- if (settled !== true) { held.last = [key, frameId, ownWidth, measuredWidth, height, settled]; return }
1556
+ if (settled !== true) { held.last = [key, frameId, ownWidth, measuredWidth, height, settled]; return { took: 'held' } }
1415
1557
  holds.delete(key); clearTimeout(held.timer)
1416
1558
  logReload({ kind: 'settled', node: key, frame: frameId, ms: performance.now() - held.at })
1417
- if (!holds.size && reflowOwed) { reflowOwed = false; scheduleReflow() }
1559
+ if (!holds.size && reflowOwed) { reflowOwed = false; scheduleReflow(null) }
1560
+ else reflowSettled()
1418
1561
  }
1419
1562
  // Generous cap: a reference doc with many screenshots is legitimately very tall and must fit in
1420
1563
  // FULL (this was 2.5x a viewport ~= 2700px, which clipped image-heavy docs). Still bounded so a
@@ -1427,7 +1570,7 @@ export const useStore = create<State>((set, get) => {
1427
1570
  // shrink it under a height already known for this width: that one is what the finished doc
1428
1571
  // measures, and shrinking now would only grow back when the image lands - the swim again
1429
1572
  const known = measuredHeights.get(mKey) ?? savedHeights.get(mKey)
1430
- if (settled === false && known !== undefined && H < known) return
1573
+ if (settled === false && known !== undefined && H < known) return IGNORED
1431
1574
  measuredHeights.set(mKey, H)
1432
1575
  // AUTO owns the width too - adopt the Doc's declared/own width. MANUAL keeps the human's width
1433
1576
  // and only fits the height.
@@ -1438,25 +1581,26 @@ export const useStore = create<State>((set, get) => {
1438
1581
  if (W !== curW) {
1439
1582
  // Doc layout changed (document<->wide): adopt the new own width first; the
1440
1583
  // iframe resizes, remeasures, and the height commits on the next message
1441
- set((st) => ({ nodes: st.nodes.map((n) => (n.key === key ? { ...n, w: W } : n)) }))
1584
+ withCause('measure-width', () => set((st) => ({ nodes: st.nodes.map((n) => (n.key === key ? { ...n, w: W } : n)) })))
1442
1585
  reflowAfterHolds()
1443
- return
1586
+ return { took: 'width', w: W }
1444
1587
  }
1445
1588
  }
1446
- if (Math.round(measuredWidth) !== curW) return // height only true at the width it was measured at
1589
+ if (Math.round(measuredWidth) !== curW) return IGNORED // height only true at the width it was measured at
1447
1590
  // a settled height at the frame's OWN width is the one the next load should open at (sizes.ts);
1448
1591
  // a human-owned width is the board file's business (manual sizes save there)
1449
1592
  if (settled === true && node.sizeMode !== 'manual') persistHeight(mKey, H)
1450
- if (Math.round(node.h) === H) return
1451
- set((st) => ({ nodes: st.nodes.map((n) => (n.key === key ? { ...n, h: H } : n)) }))
1593
+ if (Math.round(node.h) === H) return { took: 'fit', w: curW }
1594
+ withCause('measure-height', () => set((st) => ({ nodes: st.nodes.map((n) => (n.key === key ? { ...n, h: H } : n)) })))
1452
1595
  reflowAfterHolds()
1596
+ return { took: 'fit', w: curW }
1453
1597
  },
1454
1598
  noteMeasured(key, height) {
1455
1599
  // the column's height is its content's - the layout learns it here, and a composed board
1456
1600
  // whose next row now stands under a long note re-applies its recipe (0.19.2)
1457
1601
  if (setNoteHeight(key, height)) roomForNotes()
1458
1602
  },
1459
- setDeviceView(name) {
1603
+ setDeviceView(name) { withCause('device', () => {
1460
1604
  const vp = name ? CONFIG.viewports[name] : null
1461
1605
  if (name && !vp) return
1462
1606
  set((s) => {
@@ -1492,7 +1636,7 @@ export const useStore = create<State>((set, get) => {
1492
1636
  })
1493
1637
  if (name) get().runTidy() // restore must NOT tidy - it would destroy positions
1494
1638
  else { scheduleSave(); roomForNotes(); recheckLayout() } // ...unless a note grew meanwhile, or a Doc changed size, under the restored rows
1495
- },
1639
+ }) },
1496
1640
  bumpRev(key) { set((s) => ({ nodes: s.nodes.map((n) => (n.key === key ? { ...n, rev: (n.rev ?? 0) + 1 } : n)) })) },
1497
1641
  setThemeOn(key, theme) { set((s) => ({ nodes: s.nodes.map((n) => (n.key === key ? { ...n, themeOn: theme } : n)) })) },
1498
1642
  setStatus(key, status, error) {
@@ -1532,7 +1676,7 @@ export const useStore = create<State>((set, get) => {
1532
1676
  },
1533
1677
  // scoped device sizing: only the selected frames change; null restores their defaults.
1534
1678
  // Always followed by a tidy - a preset change must never scramble the layout.
1535
- resizeSelected(name) {
1679
+ resizeSelected(name) { withCause('device', () => {
1536
1680
  const vp = name ? CONFIG.viewports[name] : null
1537
1681
  if (name && !vp) return
1538
1682
  set((s) => {
@@ -1555,7 +1699,7 @@ export const useStore = create<State>((set, get) => {
1555
1699
  return { nodes, dirty: true, deviceView: null, baseLayout }
1556
1700
  })
1557
1701
  get().runTidy()
1558
- },
1702
+ }) },
1559
1703
  selectAll() {
1560
1704
  set((s) => ({ selection: s.nodes.map((n) => n.key) }))
1561
1705
  },
@@ -1599,7 +1743,7 @@ export const useStore = create<State>((set, get) => {
1599
1743
  // gesture ends - sizes changed, so lanes and gaps must recompute
1600
1744
  if (!gesture && resizedInGesture) {
1601
1745
  resizedInGesture = false
1602
- if (get().layout || get().sceneRows?.length) get().runTidy() // schedules the save
1746
+ if (get().layout || get().sceneRows?.length) withCause('resize', () => get().runTidy()) // schedules the save
1603
1747
  else scheduleSave()
1604
1748
  }
1605
1749
  if (!gesture) get().flushFrameUpdates() // A6: gesture end is a safe point for deferred updates
@@ -1686,7 +1830,7 @@ export const useStore = create<State>((set, get) => {
1686
1830
  const ctl = new AbortController()
1687
1831
  const timer = setTimeout(() => ctl.abort(), 60_000)
1688
1832
  let meta: { scale?: number; note?: string } = {}
1689
- const png = fetch(`${ROUTE}/api/shot?${qs}`, { headers: { 'x-mv-c': csrf() }, signal: ctl.signal }).then(async (r) => {
1833
+ const png = api(`shot?${qs}`, { headers: { 'x-mv-c': csrf() }, signal: ctl.signal }).then(async (r) => {
1690
1834
  if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error ?? `shot failed (${r.status})`)
1691
1835
  try { meta = JSON.parse(atob((r.headers.get('x-mv-shot') ?? '').replace(/-/g, '+').replace(/_/g, '/'))) } catch { /* summary is advisory */ }
1692
1836
  return r.blob()
@@ -1715,7 +1859,7 @@ export const useStore = create<State>((set, get) => {
1715
1859
  // global theme = the VIEW preference: persists across boards + reloads, clears
1716
1860
  // per-frame pins. Frames declaring meta.theme keep their mode (they only work there).
1717
1861
  setTheme(theme) {
1718
- try { localStorage.setItem('mv-view-theme', theme) } catch { /* storage unavailable */ }
1862
+ try { localStorage.setItem(scoped('mv-view-theme'), theme) } catch { /* storage unavailable */ }
1719
1863
  set((s) => ({
1720
1864
  viewTheme: theme,
1721
1865
  nodes: s.nodes.map((n) => {
@@ -1729,14 +1873,15 @@ export const useStore = create<State>((set, get) => {
1729
1873
  runTidy() {
1730
1874
  const { nodes, manifest, sceneRows, layout } = get()
1731
1875
  const placed = tidy(tidyInput(nodes, manifest), effectiveLayout(layout, sceneRows), layoutWarn, knownScenes(manifest))
1732
- set((s) => ({
1876
+ // a tidy asked for by hand; one a preset, a resize, a reflow or the unplaced view runs keeps its cause
1877
+ withCause(geoCause ?? 'tidy', () => set((s) => ({
1733
1878
  nodes: s.nodes.map((n) => {
1734
1879
  const p = placed.find((x) => x.key === n.key)
1735
1880
  return p ? { ...n, x: p.x, y: p.y } : n
1736
1881
  }),
1737
1882
  laidOut: sizeRecord(nodes),
1738
1883
  dirty: true,
1739
- }))
1884
+ })))
1740
1885
  scheduleSave()
1741
1886
  },
1742
1887
  toast(text) {
@@ -1806,7 +1951,7 @@ export const useStore = create<State>((set, get) => {
1806
1951
  const seq = ++marksSeq
1807
1952
  try {
1808
1953
  for (let i = 0; i < 2; i++) { // the first ask may prime the CSRF cookie (as syncWorking)
1809
- const r = await fetch(`${ROUTE}/api/marks`, { headers: { 'x-mv-c': csrf() } })
1954
+ const r = await api('marks', { headers: { 'x-mv-c': csrf() } })
1810
1955
  if (seq !== marksSeq) return
1811
1956
  if (r.ok) {
1812
1957
  const m = await r.json() as Marks | null
@@ -1873,7 +2018,7 @@ export const useStore = create<State>((set, get) => {
1873
2018
  // a fresh page may ask before its double-submit cookie exists: the refusal primes it (api.ts),
1874
2019
  // so one more try carries it
1875
2020
  for (let i = 0; i < 2; i++) {
1876
- const r = await fetch(`${ROUTE}/api/work`, { headers: { 'x-mv-c': csrf() } })
2021
+ const r = await api('work', { headers: { 'x-mv-c': csrf() } })
1877
2022
  if (r.ok) return get().setWorkingFrom(await r.json())
1878
2023
  if (r.status !== 403) return
1879
2024
  }
@@ -1895,17 +2040,17 @@ export const useStore = create<State>((set, get) => {
1895
2040
  const vp = deviceView ? CONFIG.viewports[deviceView] : null
1896
2041
  const maxX = nodes.reduce((a, n) => Math.max(a, n.x + n.w), 0)
1897
2042
  const node: Node = { key: nodeKey(), frame: f.id, x: maxX + 96, y: 0, w: vp?.width ?? d.w, h: vp?.height ?? d.h, theme: resolveTheme(f), status: 'loading', ...(f.contentWidth ? { sizeMode: (vp ? 'device' : 'auto') as Node['sizeMode'] } : {}) }
1898
- set((s) => ({
2043
+ withCause('spawn', () => set((s) => ({
1899
2044
  nodes: [...s.nodes, node],
1900
2045
  dirty: true,
1901
2046
  ...(vp && baseLayout ? { baseLayout: { ...baseLayout, [node.key]: { x: node.x, y: node.y, w: d.w, h: d.h } } } : {}),
1902
- }))
2047
+ })))
1903
2048
  scheduleSave()
1904
2049
  get().toast(`added ${f.id}`)
1905
2050
  return node
1906
2051
  },
1907
2052
 
1908
- syncUnplaced(ids) {
2053
+ syncUnplaced(ids) { withCause('unplaced', () => {
1909
2054
  const s = get()
1910
2055
  if (s.board !== UNPLACED || !s.manifest) return
1911
2056
  const want = new Set(ids)
@@ -1923,12 +2068,14 @@ export const useStore = create<State>((set, get) => {
1923
2068
  const scenes = [...new Set(nodes.map((n) => s.manifest!.frames.find((f) => f.id === n.frame)?.scene).filter((x): x is string => !!x))]
1924
2069
  set({ nodes, selection: s.selection.filter((k) => nodes.some((n) => n.key === k)), layout: scenes.length ? { rows: [scenes] } : null })
1925
2070
  get().runTidy() // one band of its scenes again; the view is never saved
1926
- },
2071
+ }) },
1927
2072
 
1928
2073
  save() {
1929
2074
  // a rename is moving this board's file - defer every save so nothing writes to the OLD
1930
2075
  // name mid-move (renameBoard reschedules once the move commits under the new name)
1931
2076
  if (saveHolds > 0) return Promise.resolve(false)
2077
+ // the canvas stopped (A1.11): the edits stay here, dirty, until it answers on this address again
2078
+ if (canvasStopped()) return Promise.resolve(false)
1932
2079
  // a resize gesture in flight = torn state (new sizes, pre-recipe positions):
1933
2080
  // even a PREVIOUSLY scheduled timer must defer to the gesture-end save
1934
2081
  if (get().gesture && resizedInGesture) { scheduleSave(); return Promise.resolve(false) }
@@ -1981,7 +2128,9 @@ export const useStore = create<State>((set, get) => {
1981
2128
  })),
1982
2129
  }
1983
2130
  try {
1984
- const res = await fetch(`${ROUTE}/api/boards/${boardName}`, {
2131
+ // a refusal by another canvas comes back as the helper's 503 and takes the `return false` below,
2132
+ // never the 409 branch (disk wins)
2133
+ const res = await api(`boards/${boardName}`, {
1985
2134
  method: 'PUT', headers: { 'content-type': 'application/json' },
1986
2135
  // A9: a board loaded from disk (boardHash set) autosaves with mustExist so a
1987
2136
  // rename/delete out from under us returns 409 instead of resurrecting a ghost.
@@ -1993,17 +2142,19 @@ export const useStore = create<State>((set, get) => {
1993
2142
  if (info?.gone) {
1994
2143
  // renamed/deleted externally - drop the write, don't recreate it or loop
1995
2144
  set({ dirty: false })
1996
- get().toast('this board was renamed or removed - not recreating it')
2145
+ get().toast(BOARD_GONE)
2146
+ lostInResume('gone') // a save while a resume is owed: the page after its reload says this, not "saved"
1997
2147
  return true
1998
2148
  }
1999
2149
  const reloaded = await get().boot() // hash advances only when the authoritative reload commits
2000
- if (reloaded) get().toast('board changed on disk - canvas layout reloaded')
2150
+ if (reloaded) { get().toast(DISK_WON); lostInResume('disk') }
2001
2151
  return reloaded // false keeps dirty set; the next debounce retries once edits settle
2002
2152
  }
2003
2153
  if (res.ok) {
2004
2154
  const { sha256 } = await res.json()
2005
2155
  // an edit that landed after this save started keeps dirty set for the next save
2006
2156
  set({ boardHash: sha256, ...(editRev === rev ? { dirty: false } : {}) })
2157
+ savedInResume() // a save while a resume is owed (the resume's, or this autosave): the page after its reload says the edits were saved
2007
2158
  return true
2008
2159
  }
2009
2160
  return false
@@ -2023,5 +2174,38 @@ useStore.subscribe((s, prev) => {
2023
2174
  if (!s.play && prev.play) { useStore.setState({ stageShown: null, playUpdateRevision: null }); pumpUpdates() }
2024
2175
  })
2025
2176
 
2177
+ // spec 28 A1.11: the canvas answered again on this address - what this page holds is saved before it reloads
2178
+ // (never mid-drag: a frame held by the pointer is asked about again a second later)
2179
+ beforeResume(async () => {
2180
+ const s = () => useStore.getState()
2181
+ if (s().gesture) return false
2182
+ for (let i = 0; i < 5 && s().dirty; i++) if (!(await s().save())) break
2183
+ // heights a write did not land (a 500, no answer) hold the reload too: queued again, they go on their timer while
2184
+ // the page works as live, and it reloads the second after they reach the file
2185
+ const heights = await settleHeights()
2186
+ return heights && !s().dirty && !s().gesture
2187
+ })
2188
+ // and an edit made, a drag begun, or a height measured or sent back to the queue while that save was on its way holds
2189
+ // the reload as well
2190
+ holdsReload(() => { const s = useStore.getState(); return s.dirty || !!s.gesture || !heightsSaved() })
2191
+ // while stopped, the banner says "your unsaved edits are kept" from the edit that makes some
2192
+ useStore.subscribe((s, p) => { if ((s.dirty !== p.dirty || s.gesture !== p.gesture) && canvasStopped()) noteUnsaved() })
2193
+ onLinkNotice((text) => useStore.getState().toast(text))
2194
+ /** A tool that needs the server, asked for while the canvas is stopped (A1.11): it says why and the way back, and
2195
+ * does nothing. `what`: "Comments need the canvas running". */
2196
+ export function stoppedFor(what: string): boolean {
2197
+ if (!canvasStopped()) return false
2198
+ useStore.getState().toast(`${what} - ${STOPPED_WAY}`)
2199
+ return true
2200
+ }
2201
+ // spec 28 A2.9: leaving a page that holds a board edit not on disk yet - dirty, a save in flight or one that failed -
2202
+ // or heights not written yet asks first (unsaved.ts's one beforeunload), live or stopped; the Mac app hears it too.
2203
+ // A drag is not work until it drops. A published canvas keeps its pins and sizes in the session: nothing to lose
2204
+ if (!PUBLISHED) {
2205
+ unsavedWhen('board-unsaved', () => useStore.getState().dirty)
2206
+ unsavedWhen('heights', () => !heightsSaved())
2207
+ useStore.subscribe((s, p) => { if (s.dirty !== p.dirty) workChanged() })
2208
+ }
2209
+
2026
2210
  // dev-only inspection hook for tests/debugging (never installed in published builds)
2027
2211
  if (import.meta.env.DEV) (window as unknown as { __mvStore: unknown }).__mvStore = useStore