@marver-design/marver 0.26.1 → 0.27.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.
Files changed (82) hide show
  1. package/CHANGELOG.md +104 -0
  2. package/README.md +8 -3
  3. package/dist/{anchor-check-l-ny3UzH.mjs → anchor-check-ChdDqL5z.mjs} +1 -1
  4. package/dist/{bake-C-awKgLA.mjs → bake-DM_uWgAA.mjs} +1 -1
  5. package/dist/{boards-DYG22tOe.mjs → boards-DlTcpF47.mjs} +1 -1
  6. package/dist/{build-BDRiO_mP.mjs → build-DZnFysGU.mjs} +4 -4
  7. package/dist/cli.mjs +28 -16
  8. package/dist/{comments-BqXua-XL.mjs → comments-DxOkCSNE.mjs} +4 -4
  9. package/dist/{daemon-DL6Fwq6D.mjs → daemon-BSA0lV8d.mjs} +8 -6
  10. package/dist/detect-C0wpaePX.mjs +125 -0
  11. package/dist/dev-eQJhWsqg.mjs +1273 -0
  12. package/dist/dev-lock-C_FC70Mu.mjs +65 -0
  13. package/dist/exclusive-B1RtpeeP.mjs +150 -0
  14. package/dist/{init-D8DtrK_F.mjs → init-COD0x48i.mjs} +5 -3
  15. package/dist/{link-BNzLvdhI.mjs → link-DDXZVGtv.mjs} +20 -8
  16. package/dist/ls-D7O1G505.mjs +38 -0
  17. package/dist/{marks-DyWMv_Z1.mjs → marks-CWM3WJjc.mjs} +1 -1
  18. package/dist/perf-BWzQwZqj.mjs +369 -0
  19. package/dist/perf-BoDSkbEb.mjs +429 -0
  20. package/dist/{perf-jam-BU3TVrZu.mjs → perf-jam-D55U3FZK.mjs} +5 -2
  21. package/dist/{plugin-DkGmZs_r.mjs → plugin-C-E7omsh.mjs} +394 -55
  22. package/dist/{poster-BdtSKMDm.mjs → poster-Bx83ZYVK.mjs} +1 -1
  23. package/dist/{profile-WU9qcbIo.mjs → profile-Bh5Y5zpW.mjs} +1 -1
  24. package/dist/{publish-bakes-9RzRToXV.mjs → publish-bakes-aljgm45S.mjs} +2 -2
  25. package/dist/{queue-29ok5_eZ.mjs → queue-CAM_vNmX.mjs} +1 -1
  26. package/dist/recover-t9Pno3u9.mjs +66 -0
  27. package/dist/{share--oFJ1bCI.mjs → share-W5H3BNvP.mjs} +1 -1
  28. package/dist/{shot-XQV7HC9A.mjs → shot-DoHLl6ig.mjs} +1 -1
  29. package/dist/{shot-DQeR_Pfn.mjs → shot-LFhC-WYD.mjs} +9 -3
  30. package/dist/slots-DCDo3N0x.mjs +471 -0
  31. package/dist/{sync-DKk-yT1V.mjs → sync-BQVlHZpx.mjs} +4 -3
  32. package/dist/{work-F5u-twpJ.mjs → work-Bp1p39kq.mjs} +4 -2
  33. package/dist/{work-VvX_JIgl.mjs → work-BroFwnup.mjs} +4 -2
  34. package/docs/boards-and-folders.md +3 -1
  35. package/docs/jam-session.md +55 -1
  36. package/docs/performance.md +262 -0
  37. package/package.json +2 -2
  38. package/src/client/content/index.tsx +3 -0
  39. package/src/client/content/video.tsx +6 -2
  40. package/src/client/frame-host/bridge.js +22 -6
  41. package/src/client/frame-host/main.tsx +17 -5
  42. package/src/client/shell/App.tsx +180 -25
  43. package/src/client/shell/BoardList.tsx +5 -5
  44. package/src/client/shell/Comments.tsx +3 -2
  45. package/src/client/shell/JamSurface.tsx +4 -2
  46. package/src/client/shell/LockedApp.tsx +5 -5
  47. package/src/client/shell/Play.tsx +16 -8
  48. package/src/client/shell/Toolbar.tsx +12 -1
  49. package/src/client/shell/api.ts +206 -0
  50. package/src/client/shell/canvas/Canvas.tsx +30 -3
  51. package/src/client/shell/canvas/FrameNode.tsx +12 -3
  52. package/src/client/shell/canvas/admission.ts +8 -1
  53. package/src/client/shell/canvas/camera-broadcast.ts +15 -5
  54. package/src/client/shell/canvas/ctl.ts +2 -0
  55. package/src/client/shell/canvas/frame-registry.ts +28 -2
  56. package/src/client/shell/canvas/sleep.ts +4 -1
  57. package/src/client/shell/comments-store.ts +12 -4
  58. package/src/client/shell/goto.ts +22 -10
  59. package/src/client/shell/jam-capture.ts +22 -8
  60. package/src/client/shell/jam-keys.ts +4 -0
  61. package/src/client/shell/jam-panel.tsx +3 -0
  62. package/src/client/shell/jam-queue.ts +3 -3
  63. package/src/client/shell/jam-session.tsx +14 -8
  64. package/src/client/shell/jam-voice.ts +7 -5
  65. package/src/client/shell/legacy-links.ts +2 -2
  66. package/src/client/shell/main.tsx +4 -0
  67. package/src/client/shell/notes.ts +8 -1
  68. package/src/client/shell/perf.ts +69 -58
  69. package/src/client/shell/recorder-core.ts +183 -0
  70. package/src/client/shell/recorder.ts +565 -0
  71. package/src/client/shell/store.ts +254 -98
  72. package/src/client/shell/styles.css +26 -1
  73. package/templates/AGENTS-embedded.md +22 -4
  74. package/templates/AGENTS-studio.md +22 -4
  75. package/templates/demo/dark.tsx +1 -1
  76. package/templates/demo/welcome.tsx +1 -1
  77. package/templates/instructions/welcome.md +6 -3
  78. package/dist/config-Cf7EjAMf.mjs +0 -292
  79. package/dist/dev-Bw_qYWWq.mjs +0 -755
  80. package/dist/dev-lock-DWSpa6nj.mjs +0 -179
  81. package/dist/perf-C75MZ73h.mjs +0 -167
  82. package/dist/perf-DPbLGhhO.mjs +0 -49
@@ -1,14 +1,17 @@
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'
7
8
  // @ts-expect-error virtual module provided by the plugin
8
9
  import shConfig from 'virtual:sh-config'
9
10
  // @ts-expect-error virtual module: null in dev; a published build inlines manifest+boards
10
11
  import shData from 'virtual:sh-data'
11
12
 
13
+ scopeNotes(scoped('mv-notes')) // a per-viewer preference, kept per canvas (spec 28 A1.6)
14
+
12
15
  /** Published-build data. Non-null = static site: no API, no saves, no live events.
13
16
  * `names` is the switcher list; `default` is where `/` opens - never a synthesized
14
17
  * aggregate of a filtered build. */
@@ -197,8 +200,9 @@ export interface BoardMeta {
197
200
  export async function fetchBoardTree(): Promise<TreeSnapshot> {
198
201
  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
202
  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) => {
203
+ // a refusal says why in the server's own words (a symlinked design/boards: BoardList says it out loud)
204
+ 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 }[]>,
205
+ api('folders').then(async (r) => {
202
206
  const j = await r.json() as { folders?: { name: string; order?: number; parent?: string; title?: string }[]; sha256?: string | null; error?: string }
203
207
  if (!r.ok) throw new Error(j?.error ?? `folders ${r.status}`)
204
208
  return j
@@ -239,7 +243,7 @@ export const landingBoard = async (): Promise<string> => (await fetchBoardNames(
239
243
  * off a published bundle (whose frames are all on a published board). Throws on transport failure. */
240
244
  export async function fetchMembership(): Promise<{ boards: { name: string; frames: string[] }[]; unplaced: string[] }> {
241
245
  if (!DATA) {
242
- const r = await fetch(`${ROUTE}/api/membership`)
246
+ const r = await api('membership')
243
247
  if (!r.ok) throw new Error(`membership ${r.status}`)
244
248
  return r.json()
245
249
  }
@@ -271,10 +275,10 @@ export const logReload = (entry: Record<string, unknown>) => {
271
275
  if (PUBLISHED) return
272
276
  const body = { tab: TAB, ...entry }
273
277
  // 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(() => {})
278
+ void postOwner('perf/reload', body).then((r) => (r.status === 403 ? api('work').then(() => postOwner('perf/reload', body)) : r)).catch(() => {})
275
279
  }
276
280
  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) })
281
+ api(path, { method: 'POST', headers: { 'content-type': 'application/json', 'x-mv-c': csrf() }, body: JSON.stringify(body) })
278
282
 
279
283
  /** Add to board (the Not on a board view): these frames appended to a board's file, as
280
284
  * `marver boards pin` does. The answer is said; the file change re-reads the sidebar and the view. */
@@ -313,17 +317,19 @@ const nodeKey = () => 'n_' + Math.random().toString(36).slice(2, 8)
313
317
  let manifestRev = 0
314
318
  export const bumpManifestRev = () => { manifestRev++ }
315
319
 
320
+ /** ws= binds the document to this canvas (spec 28 A1.11): another project on this port later answers a
321
+ * frame's own reload with the "another canvas" page (server/guard.ts), never with its frame. */
316
322
  export function frameUrl(frame: FrameEntry, theme: string): string {
317
- return frame.kind === 'html'
323
+ return withWs(frame.kind === 'html'
318
324
  ? `/${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}`
325
+ : `${ROUTE}/frame/?id=${encodeURIComponent(frame.id)}&theme=${theme}&r=${manifestRev}`)
320
326
  }
321
327
 
322
328
  /** The global view theme: the user's sticky preference, applied across boards and
323
329
  * reloads. Frames resolve to it unless they declare meta.theme or carry a user pin. */
324
330
  const initialViewTheme = () => {
325
331
  try {
326
- const t = localStorage.getItem('mv-view-theme')
332
+ const t = localStorage.getItem(scoped('mv-view-theme'))
327
333
  if (t && CONFIG.themes.includes(t)) return t
328
334
  } catch { /* storage unavailable */ }
329
335
  return CONFIG.themes[0] ?? 'light'
@@ -342,30 +348,46 @@ const measuredHeights = new Map<string, number>()
342
348
  * agent may have edited frames since), once from the bundle on a published canvas. A stale entry
343
349
  * is still the best first guess - the live measurement corrects it, and the dev shell writes the
344
350
  * 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). */
351
+ let savedHeights = new Map<string, number>()
352
+ /** The frames that measure (render a Doc), as the dev server read their sources at the load that
353
+ * committed - only theirs is a height to trust: a Doc turned bare Md keeps the size its board gives
354
+ * it, even in a page that measured it as a Doc earlier. null = no such list (a published bundle
355
+ * ships only measuring frames' heights). */
350
356
  let measuring: Set<string> | null = null
357
+ /** What one board load read of the sizes. Read by its request, installed by its commit (spec 28 A1.7): a
358
+ * request that never commits - another board chosen, a failed read - changes nothing the mounted board
359
+ * reads, its settle rule (settleRule) and its known heights included. */
360
+ interface SizeRead { saved: Map<string, number>; measuring: Set<string> | null }
361
+ /** Set only while a load prepares its nodes (the synchronous end of loadBoardState): the sizes it read. */
362
+ let preparing: SizeRead | null = null
363
+ const savedNow = () => preparing?.saved ?? savedHeights
351
364
  let publishedLoaded = false
352
- async function loadSavedHeights(): Promise<void> {
365
+ /** The sizes as the server has them now, for one load; null = nothing new to read (a published canvas reads its
366
+ * bundle once, here; no answer keeps what is installed). */
367
+ async function readSizes(): Promise<SizeRead | null> {
353
368
  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
369
+ if (!publishedLoaded) {
370
+ publishedLoaded = true
371
+ for (const [k, v] of Object.entries(DATA.sizes ?? {})) if (typeof v === 'number' && Number.isFinite(v) && v > 0) savedHeights.set(k, Math.round(v))
372
+ }
373
+ return null
358
374
  }
359
375
  try {
360
- const r = await fetch(`${ROUTE}/api/sizes`)
361
- if (!r.ok) return
376
+ const r = await api('sizes')
377
+ if (!r.ok) return null
362
378
  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 */ }
379
+ const saved = new Map<string, number>()
380
+ for (const [k, v] of Object.entries(body.heights ?? {})) if (typeof v === 'number' && Number.isFinite(v) && v > 0) saved.set(k, Math.round(v))
381
+ return { saved, measuring: Array.isArray(body.measuring) ? new Set(body.measuring.filter((x): x is string => typeof x === 'string')) : null }
382
+ } catch { return null } // no cache: placeholders, as before
367
383
  }
368
- const measures = (frameId: string) => !measuring || measuring.has(frameId)
384
+ /** The committed load's sizes become the page's. */
385
+ function installSizes(read: SizeRead | null): void {
386
+ if (!read) return
387
+ savedHeights = read.saved
388
+ measuring = read.measuring
389
+ }
390
+ const measures = (frameId: string) => { const m = preparing ? preparing.measuring : measuring; return !m || m.has(frameId) }
369
391
 
370
392
  // settled heights that differ from the committed ones, written back in batches (dev only). One
371
393
  // write in flight at a time; a height that changes while its write is in flight queues behind it,
@@ -383,6 +405,7 @@ const persistHeight = (key: string, h: number) => {
383
405
  async function flushHeights() {
384
406
  heightsTimer = undefined
385
407
  if (flushing || !pendingHeights.size) return
408
+ if (canvasStopped()) return // held until the canvas answers again (A1.11): the resume flushes them
386
409
  flushing = true
387
410
  const batch = Object.fromEntries([...pendingHeights].slice(0, 500))
388
411
  for (const [k, v] of Object.entries(batch)) { pendingHeights.delete(k); inflightHeights.set(k, v) }
@@ -405,7 +428,7 @@ async function flushHeights() {
405
428
  if (pendingHeights.size) heightsTimer ??= setTimeout(flushHeights, 1500)
406
429
  }
407
430
 
408
- const hasKnownHeight = (frameId: string, w: number) => measures(frameId) && (measuredHeights.has(`${frameId}@${w}`) || savedHeights.has(`${frameId}@${w}`))
431
+ const hasKnownHeight = (frameId: string, w: number) => measures(frameId) && (measuredHeights.has(`${frameId}@${w}`) || savedNow().has(`${frameId}@${w}`))
409
432
 
410
433
  /** The Doc sizes a layout was computed around: each auto content node whose height is known, by key,
411
434
  * as "WxH" (one line per node in the board file). A composed board saves it with its positions
@@ -439,7 +462,7 @@ function defaultSize(frame: FrameEntry) {
439
462
  const vp = CONFIG.viewports[frame.viewport ?? '']
440
463
  const w = vp?.width ?? frame.contentWidth
441
464
  const key = `${frame.id}@${w}`
442
- const known = measures(frame.id) ? measuredHeights.get(key) ?? savedHeights.get(key) : undefined
465
+ const known = measures(frame.id) ? measuredHeights.get(key) ?? savedNow().get(key) : undefined
443
466
  return { w, h: known ?? vp?.height ?? Math.round(w * 0.75) }
444
467
  }
445
468
  const vp = CONFIG.viewports[frame.viewport ?? ''] ?? CONFIG.viewports.mobile ?? { width: 390, height: 844 }
@@ -450,6 +473,58 @@ let resizedInGesture = false
450
473
  // set inside the store (they need it): a reload's height hold, and the marks-vs-documents check
451
474
  let holdHeight: (key: string) => void = () => {}
452
475
  let reconcile: () => void = () => {}
476
+
477
+ // ---- the recorder's view of the store (spec 28 A1.7) -------------------------------------------------------------
478
+ /** A change that moves or resizes nodes runs under a cause. The recorder's subscriber reads it while that change
479
+ * notifies it (zustand notifies inside set) and calls a move outside any cause `unknown`. The inner cause wins -
480
+ * except that runTidy keeps an outer one (a device preset, a resize, a reflow tidies through it). Synchronous code
481
+ * only: a cause never spans an await. */
482
+ let geoCause: string | null = null
483
+ export const geometryCause = (): string | null => geoCause
484
+ export function withCause<T>(cause: string, fn: () => T): T {
485
+ const was = geoCause
486
+ geoCause = cause
487
+ try { return fn() } finally { geoCause = was }
488
+ }
489
+ /** How a board load started: the page's first, a switch, or the open board read from disk again. */
490
+ export type LoadCause = 'boot' | 'switch' | 'disk-reload'
491
+ /** Why a requested load never committed: a newer load, a failed read, an edit or a board change meanwhile, unsaved edits. */
492
+ export type RequestCut = 'superseded' | 'error' | 'edited' | 'unsaved'
493
+ /** Board loads as the recorder sees them: recorder.ts installs these on a dev canvas - no-ops until then, and for good
494
+ * on a published one. A request owns the geometry from its commit, and `commit` runs right BEFORE the set that
495
+ * mounts the load: mounting it is never a move. */
496
+ export const recorderHooks = {
497
+ request: (_board: string, _cause: LoadCause): string => '',
498
+ /** a request is about to commit: the load that was up ends - before the incoming sizes are installed, so it ends by
499
+ * the sizes it read (which frames measure), its board's nodes still in the store */
500
+ handover: (_request: string): void => {},
501
+ commit: (_request: string, _nodes: readonly Node[], _manifest: Manifest): void => {},
502
+ cut: (_request: string, _reason: RequestCut): void => {},
503
+ /** nothing of the reflow story is left: no reflow pending, no height held, none owed */
504
+ reflowIdle: (): void => {},
505
+ }
506
+ let reflowIdleNow: () => boolean = () => true // set inside the store
507
+ /** switchBoard's calls so far - each switch, and each cancel (a switch to the board on screen): the router tells the
508
+ * second event of one navigation from a new one by nothing having switched since the first (App.tsx). */
509
+ let switchCalls = 0
510
+ export const switchCount = (): number => switchCalls
511
+ /** No reflow pending, no height held, none owed. */
512
+ export const reflowIdle = (): boolean => reflowIdleNow()
513
+ /** What a node waits for before its load settles (recorder.ts): a content frame that measures (renders a Doc) - a
514
+ * settled height at its width now; any other frame (hi-fi, html, a device-sized one, content without a Doc) - its
515
+ * ready; a frame not in the manifest - nothing: it is missing. */
516
+ export function settleRule(n: Node, manifest: Manifest | null): 'measure' | 'ready' | 'missing' {
517
+ const f = n.missing ? undefined : manifest?.frames.find((x) => x.id === n.frame)
518
+ if (!f) return 'missing'
519
+ return f.contentWidth && n.sizeMode !== 'device' && measures(f.id) ? 'measure' : 'ready'
520
+ }
521
+ /** Did a measuring node open at a height already known (committed in _sizes.json, or measured earlier in this page)? */
522
+ export const knownHeight = (frameId: string, w: number): boolean => hasKnownHeight(frameId, Math.round(w))
523
+ /** What measureNode took: `fit` - the report was taken at the node's width `w` (applied, or its height already) - the
524
+ * only one a settled report settles a node with; `width` - it adopted the Doc's own width `w`, and the next report is
525
+ * the one; `held` - kept for when the node's reload lets go; `ignored` - not taken. */
526
+ export interface MeasureResult { took: 'ignored' | 'held' | 'width' | 'fit'; w?: number }
527
+ const IGNORED: MeasureResult = { took: 'ignored' }
453
528
  // sidebar marks: the fetch in flight, and acknowledgements the server has not confirmed yet
454
529
  let marksSeq = 0
455
530
  let marksTimer: ReturnType<typeof setTimeout> | undefined
@@ -543,7 +618,7 @@ interface State {
543
618
  resizeNode(key: string, w: number, h: number): void
544
619
  /** `settled`: the Doc's fonts, images and diagrams are done (content/index.tsx). false = provisional
545
620
  * (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
621
+ measureNode(key: string, frameId: string, ownWidth: number, measuredWidth: number, height: number, settled?: boolean): MeasureResult
547
622
  /** A node's sticky column was drawn (or grew, or went): its extent from the node's top, world px. */
548
623
  noteMeasured(key: string, height: number): void
549
624
  setStatus(key: string, status: Node['status'], error?: string): void
@@ -644,12 +719,21 @@ export function frameIsLeased(frameId: string, s: State): boolean {
644
719
  !!s.externalLeases[n.key]))
645
720
  }
646
721
 
722
+ /** What a board save says when the board's file changed on disk meanwhile: the file wins, the board is read again. */
723
+ export const DISK_WON = 'board changed on disk - canvas layout reloaded'
724
+ /** What a board save says when the board was renamed or removed meanwhile: it is not created again. */
725
+ export const BOARD_GONE = 'this board was renamed or removed - not recreating it'
726
+
647
727
  export const useStore = create<State>((set, get) => {
648
728
  let saveTimer: ReturnType<typeof setTimeout> | undefined
649
729
  let saveChain: Promise<boolean> = Promise.resolve(true) // saves are serialized; responses only commit if the board is still active
650
730
  let editRev = 0 // bumps per edit; a stale save response may never clear dirty over a newer edit
651
731
  let loadSeq = 0 // stale boot() responses never overwrite a newer board
652
732
  let switchSeq = 0 // last click wins when board switches race
733
+ let firstLoad = true // the page's first boot() is its boot; every later one reads the board from disk again
734
+ // the recorder's requests in flight (spec 28 A1.7): a newer boot, a newer switch, or a switch that commits supersedes
735
+ // them the moment it does - not when their fetch answers, which may be never
736
+ let bootRequest = '', switchRequest = ''
653
737
  // While a board file is being renamed or rewritten by a structural write (rename, the
654
738
  // sidebar's tree arrange), autosave must not fire against it (a mustExist PUT would
655
739
  // 409-gone and clear dirty, losing the in-flight edit; a stale baseHash would 409 and
@@ -671,12 +755,17 @@ export const useStore = create<State>((set, get) => {
671
755
  // two conditions pending are EITHER one (a later ask never drops an earlier one).
672
756
  let reflowTimer: ReturnType<typeof setTimeout> | undefined
673
757
  let reflowCheck: (() => boolean) | null = null
758
+ /** Why the pending reflow runs (spec 28 A1.7) - merged across the calls it coalesces, kept through a drag, a camera
759
+ * in flight and held heights: the recorder names its moves `reflow:<reasons>`. */
760
+ type ReflowReason = 'measured' | 'cramped' | 'stale' | 'gesture-end'
761
+ let reflowReasons = new Set<ReflowReason>()
674
762
  /** A board load (boot, switch) starts its own reflow story: whatever was pending - an
675
763
  * 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 }
764
+ const cancelReflow = () => { clearTimeout(reflowTimer); reflowTimer = undefined; reflowCheck = null; reflowReasons = new Set() }
677
765
  /** How long a content reflow waits for a camera in flight - past it, the rows move anyway. */
678
766
  const REFLOW_CAMERA_WAIT = 1500
679
- const scheduleReflow = (onlyIf?: () => boolean, delay = 400, cameraSince?: number) => {
767
+ const scheduleReflow = (reason: ReflowReason | null, onlyIf?: () => boolean, delay = 400, cameraSince?: number) => {
768
+ if (reason) reflowReasons.add(reason)
680
769
  const boardAt = get().board
681
770
  const prev = reflowTimer !== undefined ? reflowCheck : undefined // undefined: nothing pending
682
771
  reflowCheck = prev === null || !onlyIf ? null : prev ? () => prev() || onlyIf() : onlyIf
@@ -686,20 +775,23 @@ export const useStore = create<State>((set, get) => {
686
775
  const check = reflowCheck
687
776
  reflowCheck = null
688
777
  const s = get()
689
- if (s.board !== boardAt) return
778
+ if (s.board !== boardAt) { reflowReasons = new Set(); reflowSettled(); return }
690
779
  // defer, never drop - retries after the drag
691
- if (s.gesture) { scheduleReflow(check ?? undefined); return }
780
+ if (s.gesture) { scheduleReflow('gesture-end', check ?? undefined); return }
692
781
  // and after a camera flight: a link's fit lands first, then the rows move around the frames it
693
782
  // showed (holdView keeps them where the fit put them). Looked at often, so the reflow follows the
694
783
  // landing closely - and never waited on past REFLOW_CAMERA_WAIT: a camera that keeps moving (fit
695
784
  // after fit) does not hold the rows apart forever
696
785
  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
786
+ if (canvasCtl.cameraBusy() && Date.now() - since < REFLOW_CAMERA_WAIT) { scheduleReflow(null, check ?? undefined, 60, since); return }
787
+ if (check && !check()) { reflowReasons = new Set(); reflowSettled(); return }
699
788
  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
789
+ if (holds.size) { reflowOwed = true; return } // a batch is reloading: the rows move once, when it lets go (its reasons kept)
790
+ const why = `reflow:${[...reflowReasons].sort().join('+') || 'measured'}`
791
+ reflowReasons = new Set()
701
792
  // content moved the rows, not the human: hold what they are looking at still (Canvas.tsx)
702
- if (composed(s)) { canvasCtl.holdView(); s.runTidy() }
793
+ if (composed(s)) withCause(why, () => { canvasCtl.holdView(); s.runTidy() })
794
+ reflowSettled()
703
795
  }, delay)
704
796
  }
705
797
  /** Boards whose layout the shell owns: a recipe, scene rows, or the auto board. Room for a
@@ -723,11 +815,15 @@ export const useStore = create<State>((set, get) => {
723
815
  clearTimeout(h.timer)
724
816
  holds.delete(key)
725
817
  if (apply && h.last) get().measureNode(...h.last)
726
- if (!holds.size && reflowOwed) { reflowOwed = false; scheduleReflow() }
818
+ if (!holds.size && reflowOwed) { reflowOwed = false; scheduleReflow(null) }
819
+ else reflowSettled()
727
820
  }
728
821
  const dropHolds = () => { for (const h of holds.values()) clearTimeout(h.timer); holds.clear(); reflowOwed = false }
729
822
  /** A content measure moved the rows: once, after the last held node lets go. */
730
- const reflowAfterHolds = () => { if (holds.size) reflowOwed = true; else scheduleReflow() }
823
+ const reflowAfterHolds = () => { reflowReasons.add('measured'); if (holds.size) reflowOwed = true; else scheduleReflow('measured') }
824
+ /** The recorder hears when nothing of the reflow story is left (spec 28 A1.7): no timer, no held height, none owed. */
825
+ reflowIdleNow = () => reflowTimer === undefined && !holds.size && !reflowOwed
826
+ const reflowSettled = () => { if (reflowIdleNow()) recorderHooks.reflowIdle() }
731
827
 
732
828
  // Marks (spec 26): a node that shows an older revision than its frame's `doc` has missed an update
733
829
  // (an event lost while disconnected, an edit that landed while it loaded): it goes stale. The
@@ -765,7 +861,7 @@ export const useStore = create<State>((set, get) => {
765
861
 
766
862
  /** A note may have landed with no room (a frame note via the manifest, a scene note via
767
863
  * sh:scenes, either merged late by boot/switch): a composed board re-applies its layout. */
768
- const roomForNotes = () => { if (composed(get()) && cramped()) scheduleReflow(cramped) }
864
+ const roomForNotes = () => { if (composed(get()) && cramped()) scheduleReflow('cramped', cramped) }
769
865
  /** A composed board's saved positions were laid out around the heights of the session that saved
770
866
  * them. A committed height that changed since (the doc grew or shrank while another board was
771
867
  * open) opens at its new size over - or far above - the row below, and no measurement will re-flow
@@ -790,7 +886,7 @@ export const useStore = create<State>((set, get) => {
790
886
  }
791
887
  const recheckLayout = () => {
792
888
  const s = get()
793
- if (composed(s) && s.nodes.some((n) => n.sizeMode === 'auto' && hasKnownHeight(n.frame, Math.round(n.w)))) scheduleReflow(layoutStale)
889
+ if (composed(s) && s.nodes.some((n) => n.sizeMode === 'auto' && hasKnownHeight(n.frame, Math.round(n.w)))) scheduleReflow('stale', layoutStale)
794
890
  }
795
891
 
796
892
  /** Theme resolution ladder: user pin > the frame's declared meta.theme > viewTheme. */
@@ -834,22 +930,23 @@ export const useStore = create<State>((set, get) => {
834
930
  },
835
931
  }
836
932
 
837
- /** Fetch + normalize a board into ready-to-commit state, WITHOUT touching the store.
933
+ /** Fetch + normalize a board into ready-to-commit state, WITHOUT touching the store - nor the sizes the
934
+ * mounted board reads: those it read come back with it, for the commit to install (installSizes).
838
935
  * null = failure (transport, malformed manifest, non-404 board error) - the caller
839
936
  * keeps whatever board is currently mounted. */
840
- const loadBoardState = async (boardName: string): Promise<Partial<State> | null> => {
937
+ const loadBoardState = async (boardName: string): Promise<{ state: Partial<State>; sizes: SizeRead | null } | null> => {
841
938
  clearNoteHeights() // heights are per column drawn; a key shared by two board files carries none across
842
939
  loadErrors.delete(boardName)
843
940
  try {
844
941
  let raw: any
845
- const saved = loadSavedHeights() // in parallel with the manifest; every size below reads it
942
+ const saved = readSizes() // in parallel with the manifest; every size below reads it
846
943
  if (DATA) raw = DATA.manifest
847
944
  else {
848
- const mRes = await fetch('/design/manifest.json')
945
+ const mRes = await mvFetch('/design/manifest.json')
849
946
  if (!mRes.ok) return null
850
947
  raw = await mRes.json().catch(() => undefined)
851
948
  }
852
- await saved
949
+ const sizes = await saved
853
950
  if (raw === undefined || raw === null || typeof raw !== 'object') return null
854
951
  bumpManifestRev() // fresh manifest → fresh iframe URLs
855
952
  const manifest: Manifest = {
@@ -878,7 +975,7 @@ export const useStore = create<State>((set, get) => {
878
975
  const scenes = [...new Set(manifest.frames.filter((f) => m?.unplaced.includes(f.id)).map((f) => f.scene))]
879
976
  loaded = m ? { board: { nodes: m.unplaced.map((frame) => ({ frame })), ...(scenes.length ? { layout: { rows: [scenes] } } : {}) }, sha256: '' } : null
880
977
  } else {
881
- const res = await fetch(`${ROUTE}/api/boards/${boardName}`)
978
+ const res = await api(`boards/${boardName}`)
882
979
  if (res.ok) {
883
980
  const body = await res.json()
884
981
  loaded = body?.board == null ? 'fresh' : body // board:null = not materialized yet
@@ -887,6 +984,9 @@ export const useStore = create<State>((set, get) => {
887
984
  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
985
  }
889
986
  if (loaded === null) return null
987
+ // from here to the return nothing is awaited: the sizes this load read are the ones its nodes are made from,
988
+ // and no other code runs meanwhile to read them in place of the mounted board's
989
+ preparing = sizes
890
990
  if (loaded !== 'fresh') {
891
991
  const { board, sha256 } = loaded
892
992
  boardHash = sha256
@@ -1033,8 +1133,8 @@ export const useStore = create<State>((set, get) => {
1033
1133
  if (layout && boardHash && !needTidy && !cramped && nodes.length) {
1034
1134
  tidy(tidyInput(nodes, manifest), layout, layoutWarn, knownScenes(manifest))
1035
1135
  }
1036
- return { manifest, nodes, boardHash, boardAuto, deviceView, sceneRows, layout, layoutRaw, baseLayout, laidOut, baseLaidOut, selection: [], dirty: prunedAtLoad || cramped }
1037
- } catch { return null }
1136
+ return { state: { manifest, nodes, boardHash, boardAuto, deviceView, sceneRows, layout, layoutRaw, baseLayout, laidOut, baseLaidOut, selection: [], dirty: prunedAtLoad || cramped }, sizes }
1137
+ } catch { return null } finally { preparing = null }
1038
1138
  }
1039
1139
 
1040
1140
  return {
@@ -1045,14 +1145,22 @@ export const useStore = create<State>((set, get) => {
1045
1145
 
1046
1146
  async boot(mayCommit) {
1047
1147
  const seq = ++loadSeq
1148
+ recorderHooks.cut(bootRequest, 'superseded')
1048
1149
  const boardName = get().board
1150
+ // the recorder's request (spec 28 A1.7): the page's first load, else the open board read from disk again
1151
+ const request = bootRequest = recorderHooks.request(boardName, firstLoad ? 'boot' : 'disk-reload')
1152
+ firstLoad = false
1049
1153
  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 }
1154
+ const loaded = await loadBoardState(boardName)
1155
+ if (seq !== loadSeq) { recorderHooks.cut(request, 'superseded'); return false } // a newer load superseded this one
1156
+ if (!loaded) { recorderHooks.cut(request, 'error'); get().toast(`board "${boardName}" failed to load${whyNot(boardName)}`); return false }
1053
1157
  // 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
1158
+ if (get().board !== boardName || editRev !== revAtStart || (mayCommit && !mayCommit())) { recorderHooks.cut(request, 'edited'); return false }
1159
+ const next = loaded.state
1055
1160
  const live = get().manifest // a WS manifest update may have landed mid-fetch
1161
+ recorderHooks.handover(request) // the load that was up ends by its own sizes
1162
+ installSizes(loaded.sizes) // the sizes this load read are the page's from its commit
1163
+ recorderHooks.commit(request, next.nodes as Node[], next.manifest as Manifest) // before the set: mounting is not a move
1056
1164
  set(next)
1057
1165
  cancelReflow(); dropHolds(); reloadCause.clear()
1058
1166
  if (next.dirty) scheduleSave() // load-time prune must reach the disk
@@ -1065,31 +1173,41 @@ export const useStore = create<State>((set, get) => {
1065
1173
 
1066
1174
  async switchBoard(name) {
1067
1175
  const mySwitch = ++switchSeq // also cancels any pending switch (incl. re-clicking the current board)
1176
+ switchCalls++
1177
+ recorderHooks.cut(switchRequest, 'superseded')
1068
1178
  const scenesAtStart = scenesRev
1069
1179
  if (name === get().board) return
1180
+ // the recorder's request (spec 28 A1.7): the wait starts here, the flush included; the board still mounted
1181
+ // owns the geometry until this one commits
1182
+ const request = switchRequest = recorderHooks.request(name, 'switch')
1070
1183
  // a resize held across a switch: settle THIS board (retidy if it has a recipe)
1071
1184
  // before the flush, so the torn mid-gesture state is never what reaches disk
1072
1185
  if (resizedInGesture) {
1073
1186
  resizedInGesture = false
1074
- if (get().layout || get().sceneRows?.length) get().runTidy()
1187
+ if (get().layout || get().sceneRows?.length) withCause('resize', () => get().runTidy())
1075
1188
  }
1076
1189
  // flush loop: an edit landing mid-save keeps dirty set and gets its own pass
1077
1190
  let ok = true
1078
1191
  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 }
1192
+ if (mySwitch !== switchSeq) return recorderHooks.cut(request, 'superseded')
1193
+ if (get().dirty) { recorderHooks.cut(request, 'unsaved'); get().toast('current board could not be saved - staying here'); return }
1081
1194
  // load the target while the current board stays mounted; commit atomically on success -
1082
1195
  // 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 }
1196
+ const loaded = await loadBoardState(name)
1197
+ if (mySwitch !== switchSeq) return recorderHooks.cut(request, 'superseded')
1198
+ if (!loaded) { recorderHooks.cut(request, 'error'); get().toast(`could not load "${name}"${whyNot(name)} - staying on ${get().board}`); return }
1199
+ const next = loaded.state
1086
1200
  // edits may have landed on the still-mounted old board during the target load
1087
1201
  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 }
1202
+ if (mySwitch !== switchSeq) return recorderHooks.cut(request, 'superseded')
1203
+ if (get().dirty) { recorderHooks.cut(request, 'unsaved'); get().toast('current board could not be saved - staying here'); return }
1090
1204
  clearTimeout(saveTimer) // a scheduled-but-clean timer must not fire against the new board
1091
1205
  ++loadSeq // invalidate any in-flight boot of the old board
1206
+ recorderHooks.cut(bootRequest, 'superseded')
1092
1207
  const live = get().manifest // a WS manifest update may have landed mid-load
1208
+ recorderHooks.handover(request) // the load that was up ends by its own sizes
1209
+ installSizes(loaded.sizes) // the sizes this load read are the page's from its commit
1210
+ recorderHooks.commit(request, next.nodes as Node[], next.manifest as Manifest) // before the set: mounting is not a move
1093
1211
  set({ board: name, interact: null, ...next })
1094
1212
  cancelReflow(); dropHolds(); reloadCause.clear()
1095
1213
  if (next.dirty) scheduleSave() // load-time prune must reach the disk
@@ -1318,13 +1436,14 @@ export const useStore = create<State>((set, get) => {
1318
1436
  toast(dropped === 1 ? 'removed 1 deleted frame' : `removed ${dropped} deleted frames`)
1319
1437
  }
1320
1438
  }
1321
- set((s) => ({
1439
+ // a guessed size corrected above (in place) is a move, seen when this set notifies the recorder
1440
+ withCause('manifest', () => set((s) => ({
1322
1441
  manifest: m,
1323
1442
  nodes: changed || retinted ? [...final] : final,
1324
1443
  selection: s.selection.filter((k) => final.some((n) => n.key === k)),
1325
1444
  interact: s.interact && final.some((n) => n.key === s.interact) ? s.interact : null,
1326
1445
  ...(changed ? { dirty: true, baseLayout: nextBase } : {}),
1327
- }))
1446
+ })))
1328
1447
  if (changed) scheduleSave()
1329
1448
  roomForNotes() // a frame note file arrived: room in front of its frame
1330
1449
  },
@@ -1343,15 +1462,15 @@ export const useStore = create<State>((set, get) => {
1343
1462
  frameFor(node) { return get().manifest?.frames.find((f) => f.id === node.frame) },
1344
1463
 
1345
1464
  moveNode(key, x, y) {
1346
- set((s) => ({ nodes: s.nodes.map((n) => (n.key === key ? { ...n, x, y } : n)), dirty: true }))
1465
+ withCause('drag', () => set((s) => ({ nodes: s.nodes.map((n) => (n.key === key ? { ...n, x, y } : n)), dirty: true })))
1347
1466
  scheduleSave()
1348
1467
  },
1349
1468
  // group drag: every selected node moves by the same delta from its gesture-start position
1350
1469
  moveSelectedBy(dx, dy, starts) {
1351
- set((s) => ({
1470
+ withCause('drag', () => set((s) => ({
1352
1471
  nodes: s.nodes.map((n) => (starts[n.key] ? { ...n, x: starts[n.key].x + dx, y: starts[n.key].y + dy } : n)),
1353
1472
  dirty: true,
1354
- }))
1473
+ })))
1355
1474
  scheduleSave()
1356
1475
  },
1357
1476
  // scoped theme = an explicit per-frame PIN; it survives board reloads and yields
@@ -1368,7 +1487,7 @@ export const useStore = create<State>((set, get) => {
1368
1487
  const inGesture = get().gesture
1369
1488
  // a manual resize means the board no longer uniformly shows one device; the resized
1370
1489
  // frame's snapshot entry follows the user's new size so Default will not undo it
1371
- set((s) => {
1490
+ withCause('resize', () => set((s) => {
1372
1491
  const W = Math.max(120, w), H = Math.max(80, h)
1373
1492
  const cur = s.nodes.find((n) => n.key === key)
1374
1493
  // a human-resized CONTENT frame goes 'manual': measurements never overwrite it
@@ -1382,7 +1501,7 @@ export const useStore = create<State>((set, get) => {
1382
1501
  ? { ...s.baseLayout, [key]: { ...(s.baseLayout[key] ?? { x: cur.x, y: cur.y }), w: W, h: H } }
1383
1502
  : s.baseLayout,
1384
1503
  }
1385
- })
1504
+ }))
1386
1505
  // mid-gesture saves would persist torn state (new sizes, pre-recipe positions);
1387
1506
  // the gesture-end hook saves once, after any retidy
1388
1507
  if (!inGesture) scheduleSave()
@@ -1399,22 +1518,23 @@ export const useStore = create<State>((set, get) => {
1399
1518
  // auto-fit height: a content frame must always grow/shrink to show ALL its content, even after
1400
1519
  // the human drags its WIDTH. 'manual' just means the human owns the WIDTH; the
1401
1520
  // 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
1521
+ if (!node || node.sizeMode === 'device') return IGNORED
1522
+ if (node.frame !== frameId) return IGNORED // generation guard: a reused node key
1404
1523
  // across a board switch never mis-attributes
1405
1524
  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
1525
+ if (!f?.contentWidth) return IGNORED // not a content frame - spoof-proofing
1526
+ if (![ownWidth, measuredWidth, height].every((v) => Number.isFinite(v) && v > 0)) return IGNORED
1408
1527
  // a Doc that reports IS one, whatever the last load's scan said (it arrived since): its heights
1409
1528
  // count until the next load re-reads the sources
1410
1529
  measuring?.add(f.id)
1411
1530
  // held while it reloads (spec 26): only a settled measure lands now; the last other one waits
1412
1531
  const held = holds.get(key)
1413
1532
  if (held) {
1414
- if (settled !== true) { held.last = [key, frameId, ownWidth, measuredWidth, height, settled]; return }
1533
+ if (settled !== true) { held.last = [key, frameId, ownWidth, measuredWidth, height, settled]; return { took: 'held' } }
1415
1534
  holds.delete(key); clearTimeout(held.timer)
1416
1535
  logReload({ kind: 'settled', node: key, frame: frameId, ms: performance.now() - held.at })
1417
- if (!holds.size && reflowOwed) { reflowOwed = false; scheduleReflow() }
1536
+ if (!holds.size && reflowOwed) { reflowOwed = false; scheduleReflow(null) }
1537
+ else reflowSettled()
1418
1538
  }
1419
1539
  // Generous cap: a reference doc with many screenshots is legitimately very tall and must fit in
1420
1540
  // FULL (this was 2.5x a viewport ~= 2700px, which clipped image-heavy docs). Still bounded so a
@@ -1427,7 +1547,7 @@ export const useStore = create<State>((set, get) => {
1427
1547
  // shrink it under a height already known for this width: that one is what the finished doc
1428
1548
  // measures, and shrinking now would only grow back when the image lands - the swim again
1429
1549
  const known = measuredHeights.get(mKey) ?? savedHeights.get(mKey)
1430
- if (settled === false && known !== undefined && H < known) return
1550
+ if (settled === false && known !== undefined && H < known) return IGNORED
1431
1551
  measuredHeights.set(mKey, H)
1432
1552
  // AUTO owns the width too - adopt the Doc's declared/own width. MANUAL keeps the human's width
1433
1553
  // and only fits the height.
@@ -1438,25 +1558,26 @@ export const useStore = create<State>((set, get) => {
1438
1558
  if (W !== curW) {
1439
1559
  // Doc layout changed (document<->wide): adopt the new own width first; the
1440
1560
  // 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)) }))
1561
+ withCause('measure-width', () => set((st) => ({ nodes: st.nodes.map((n) => (n.key === key ? { ...n, w: W } : n)) })))
1442
1562
  reflowAfterHolds()
1443
- return
1563
+ return { took: 'width', w: W }
1444
1564
  }
1445
1565
  }
1446
- if (Math.round(measuredWidth) !== curW) return // height only true at the width it was measured at
1566
+ if (Math.round(measuredWidth) !== curW) return IGNORED // height only true at the width it was measured at
1447
1567
  // a settled height at the frame's OWN width is the one the next load should open at (sizes.ts);
1448
1568
  // a human-owned width is the board file's business (manual sizes save there)
1449
1569
  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)) }))
1570
+ if (Math.round(node.h) === H) return { took: 'fit', w: curW }
1571
+ withCause('measure-height', () => set((st) => ({ nodes: st.nodes.map((n) => (n.key === key ? { ...n, h: H } : n)) })))
1452
1572
  reflowAfterHolds()
1573
+ return { took: 'fit', w: curW }
1453
1574
  },
1454
1575
  noteMeasured(key, height) {
1455
1576
  // the column's height is its content's - the layout learns it here, and a composed board
1456
1577
  // whose next row now stands under a long note re-applies its recipe (0.19.2)
1457
1578
  if (setNoteHeight(key, height)) roomForNotes()
1458
1579
  },
1459
- setDeviceView(name) {
1580
+ setDeviceView(name) { withCause('device', () => {
1460
1581
  const vp = name ? CONFIG.viewports[name] : null
1461
1582
  if (name && !vp) return
1462
1583
  set((s) => {
@@ -1492,7 +1613,7 @@ export const useStore = create<State>((set, get) => {
1492
1613
  })
1493
1614
  if (name) get().runTidy() // restore must NOT tidy - it would destroy positions
1494
1615
  else { scheduleSave(); roomForNotes(); recheckLayout() } // ...unless a note grew meanwhile, or a Doc changed size, under the restored rows
1495
- },
1616
+ }) },
1496
1617
  bumpRev(key) { set((s) => ({ nodes: s.nodes.map((n) => (n.key === key ? { ...n, rev: (n.rev ?? 0) + 1 } : n)) })) },
1497
1618
  setThemeOn(key, theme) { set((s) => ({ nodes: s.nodes.map((n) => (n.key === key ? { ...n, themeOn: theme } : n)) })) },
1498
1619
  setStatus(key, status, error) {
@@ -1532,7 +1653,7 @@ export const useStore = create<State>((set, get) => {
1532
1653
  },
1533
1654
  // scoped device sizing: only the selected frames change; null restores their defaults.
1534
1655
  // Always followed by a tidy - a preset change must never scramble the layout.
1535
- resizeSelected(name) {
1656
+ resizeSelected(name) { withCause('device', () => {
1536
1657
  const vp = name ? CONFIG.viewports[name] : null
1537
1658
  if (name && !vp) return
1538
1659
  set((s) => {
@@ -1555,7 +1676,7 @@ export const useStore = create<State>((set, get) => {
1555
1676
  return { nodes, dirty: true, deviceView: null, baseLayout }
1556
1677
  })
1557
1678
  get().runTidy()
1558
- },
1679
+ }) },
1559
1680
  selectAll() {
1560
1681
  set((s) => ({ selection: s.nodes.map((n) => n.key) }))
1561
1682
  },
@@ -1599,7 +1720,7 @@ export const useStore = create<State>((set, get) => {
1599
1720
  // gesture ends - sizes changed, so lanes and gaps must recompute
1600
1721
  if (!gesture && resizedInGesture) {
1601
1722
  resizedInGesture = false
1602
- if (get().layout || get().sceneRows?.length) get().runTidy() // schedules the save
1723
+ if (get().layout || get().sceneRows?.length) withCause('resize', () => get().runTidy()) // schedules the save
1603
1724
  else scheduleSave()
1604
1725
  }
1605
1726
  if (!gesture) get().flushFrameUpdates() // A6: gesture end is a safe point for deferred updates
@@ -1686,7 +1807,7 @@ export const useStore = create<State>((set, get) => {
1686
1807
  const ctl = new AbortController()
1687
1808
  const timer = setTimeout(() => ctl.abort(), 60_000)
1688
1809
  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) => {
1810
+ const png = api(`shot?${qs}`, { headers: { 'x-mv-c': csrf() }, signal: ctl.signal }).then(async (r) => {
1690
1811
  if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error ?? `shot failed (${r.status})`)
1691
1812
  try { meta = JSON.parse(atob((r.headers.get('x-mv-shot') ?? '').replace(/-/g, '+').replace(/_/g, '/'))) } catch { /* summary is advisory */ }
1692
1813
  return r.blob()
@@ -1715,7 +1836,7 @@ export const useStore = create<State>((set, get) => {
1715
1836
  // global theme = the VIEW preference: persists across boards + reloads, clears
1716
1837
  // per-frame pins. Frames declaring meta.theme keep their mode (they only work there).
1717
1838
  setTheme(theme) {
1718
- try { localStorage.setItem('mv-view-theme', theme) } catch { /* storage unavailable */ }
1839
+ try { localStorage.setItem(scoped('mv-view-theme'), theme) } catch { /* storage unavailable */ }
1719
1840
  set((s) => ({
1720
1841
  viewTheme: theme,
1721
1842
  nodes: s.nodes.map((n) => {
@@ -1729,14 +1850,15 @@ export const useStore = create<State>((set, get) => {
1729
1850
  runTidy() {
1730
1851
  const { nodes, manifest, sceneRows, layout } = get()
1731
1852
  const placed = tidy(tidyInput(nodes, manifest), effectiveLayout(layout, sceneRows), layoutWarn, knownScenes(manifest))
1732
- set((s) => ({
1853
+ // a tidy asked for by hand; one a preset, a resize, a reflow or the unplaced view runs keeps its cause
1854
+ withCause(geoCause ?? 'tidy', () => set((s) => ({
1733
1855
  nodes: s.nodes.map((n) => {
1734
1856
  const p = placed.find((x) => x.key === n.key)
1735
1857
  return p ? { ...n, x: p.x, y: p.y } : n
1736
1858
  }),
1737
1859
  laidOut: sizeRecord(nodes),
1738
1860
  dirty: true,
1739
- }))
1861
+ })))
1740
1862
  scheduleSave()
1741
1863
  },
1742
1864
  toast(text) {
@@ -1806,7 +1928,7 @@ export const useStore = create<State>((set, get) => {
1806
1928
  const seq = ++marksSeq
1807
1929
  try {
1808
1930
  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() } })
1931
+ const r = await api('marks', { headers: { 'x-mv-c': csrf() } })
1810
1932
  if (seq !== marksSeq) return
1811
1933
  if (r.ok) {
1812
1934
  const m = await r.json() as Marks | null
@@ -1873,7 +1995,7 @@ export const useStore = create<State>((set, get) => {
1873
1995
  // a fresh page may ask before its double-submit cookie exists: the refusal primes it (api.ts),
1874
1996
  // so one more try carries it
1875
1997
  for (let i = 0; i < 2; i++) {
1876
- const r = await fetch(`${ROUTE}/api/work`, { headers: { 'x-mv-c': csrf() } })
1998
+ const r = await api('work', { headers: { 'x-mv-c': csrf() } })
1877
1999
  if (r.ok) return get().setWorkingFrom(await r.json())
1878
2000
  if (r.status !== 403) return
1879
2001
  }
@@ -1895,17 +2017,17 @@ export const useStore = create<State>((set, get) => {
1895
2017
  const vp = deviceView ? CONFIG.viewports[deviceView] : null
1896
2018
  const maxX = nodes.reduce((a, n) => Math.max(a, n.x + n.w), 0)
1897
2019
  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) => ({
2020
+ withCause('spawn', () => set((s) => ({
1899
2021
  nodes: [...s.nodes, node],
1900
2022
  dirty: true,
1901
2023
  ...(vp && baseLayout ? { baseLayout: { ...baseLayout, [node.key]: { x: node.x, y: node.y, w: d.w, h: d.h } } } : {}),
1902
- }))
2024
+ })))
1903
2025
  scheduleSave()
1904
2026
  get().toast(`added ${f.id}`)
1905
2027
  return node
1906
2028
  },
1907
2029
 
1908
- syncUnplaced(ids) {
2030
+ syncUnplaced(ids) { withCause('unplaced', () => {
1909
2031
  const s = get()
1910
2032
  if (s.board !== UNPLACED || !s.manifest) return
1911
2033
  const want = new Set(ids)
@@ -1923,12 +2045,14 @@ export const useStore = create<State>((set, get) => {
1923
2045
  const scenes = [...new Set(nodes.map((n) => s.manifest!.frames.find((f) => f.id === n.frame)?.scene).filter((x): x is string => !!x))]
1924
2046
  set({ nodes, selection: s.selection.filter((k) => nodes.some((n) => n.key === k)), layout: scenes.length ? { rows: [scenes] } : null })
1925
2047
  get().runTidy() // one band of its scenes again; the view is never saved
1926
- },
2048
+ }) },
1927
2049
 
1928
2050
  save() {
1929
2051
  // a rename is moving this board's file - defer every save so nothing writes to the OLD
1930
2052
  // name mid-move (renameBoard reschedules once the move commits under the new name)
1931
2053
  if (saveHolds > 0) return Promise.resolve(false)
2054
+ // the canvas stopped (A1.11): the edits stay here, dirty, until it answers on this address again
2055
+ if (canvasStopped()) return Promise.resolve(false)
1932
2056
  // a resize gesture in flight = torn state (new sizes, pre-recipe positions):
1933
2057
  // even a PREVIOUSLY scheduled timer must defer to the gesture-end save
1934
2058
  if (get().gesture && resizedInGesture) { scheduleSave(); return Promise.resolve(false) }
@@ -1981,7 +2105,9 @@ export const useStore = create<State>((set, get) => {
1981
2105
  })),
1982
2106
  }
1983
2107
  try {
1984
- const res = await fetch(`${ROUTE}/api/boards/${boardName}`, {
2108
+ // a refusal by another canvas comes back as the helper's 503 and takes the `return false` below,
2109
+ // never the 409 branch (disk wins)
2110
+ const res = await api(`boards/${boardName}`, {
1985
2111
  method: 'PUT', headers: { 'content-type': 'application/json' },
1986
2112
  // A9: a board loaded from disk (boardHash set) autosaves with mustExist so a
1987
2113
  // rename/delete out from under us returns 409 instead of resurrecting a ghost.
@@ -1993,17 +2119,19 @@ export const useStore = create<State>((set, get) => {
1993
2119
  if (info?.gone) {
1994
2120
  // renamed/deleted externally - drop the write, don't recreate it or loop
1995
2121
  set({ dirty: false })
1996
- get().toast('this board was renamed or removed - not recreating it')
2122
+ get().toast(BOARD_GONE)
2123
+ lostInResume('gone') // a resume's save: the page after its reload says this, not "saved"
1997
2124
  return true
1998
2125
  }
1999
2126
  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')
2127
+ if (reloaded) { get().toast(DISK_WON); lostInResume('disk') }
2001
2128
  return reloaded // false keeps dirty set; the next debounce retries once edits settle
2002
2129
  }
2003
2130
  if (res.ok) {
2004
2131
  const { sha256 } = await res.json()
2005
2132
  // an edit that landed after this save started keeps dirty set for the next save
2006
2133
  set({ boardHash: sha256, ...(editRev === rev ? { dirty: false } : {}) })
2134
+ savedInResume() // a resume's save: the page after its reload says the edits were saved
2007
2135
  return true
2008
2136
  }
2009
2137
  return false
@@ -2023,5 +2151,33 @@ useStore.subscribe((s, prev) => {
2023
2151
  if (!s.play && prev.play) { useStore.setState({ stageShown: null, playUpdateRevision: null }); pumpUpdates() }
2024
2152
  })
2025
2153
 
2154
+ // spec 28 A1.11: the canvas answered again on this address - what this page holds is saved before it reloads
2155
+ // (never mid-drag: a frame held by the pointer is asked about again a second later)
2156
+ beforeResume(async () => {
2157
+ const s = () => useStore.getState()
2158
+ if (s().gesture) return false
2159
+ for (let i = 0; i < 5 && s().dirty; i++) if (!(await s().save())) break
2160
+ await flushHeights()
2161
+ return !s().dirty && !s().gesture
2162
+ })
2163
+ // and an edit made, or a drag begun, while that save was on its way holds the reload as well
2164
+ holdsReload(() => { const s = useStore.getState(); return s.dirty || !!s.gesture })
2165
+ // while stopped, the banner says "your unsaved edits are kept" from the edit that makes some
2166
+ useStore.subscribe((s, p) => { if ((s.dirty !== p.dirty || s.gesture !== p.gesture) && canvasStopped()) noteUnsaved() })
2167
+ onLinkNotice((text) => useStore.getState().toast(text))
2168
+ /** A tool that needs the server, asked for while the canvas is stopped (A1.11): it says why and the way back, and
2169
+ * does nothing. `what`: "Comments need the canvas running". */
2170
+ export function stoppedFor(what: string): boolean {
2171
+ if (!canvasStopped()) return false
2172
+ useStore.getState().toast(`${what} - ${STOPPED_WAY}`)
2173
+ return true
2174
+ }
2175
+ // a stopped page holds edits only it has: leaving it (a reload by hand, a close) asks first
2176
+ if (typeof window !== 'undefined') window.addEventListener('beforeunload', (e) => {
2177
+ if (!canvasStopped() || !useStore.getState().dirty) return
2178
+ e.preventDefault()
2179
+ e.returnValue = ''
2180
+ })
2181
+
2026
2182
  // dev-only inspection hook for tests/debugging (never installed in published builds)
2027
2183
  if (import.meta.env.DEV) (window as unknown as { __mvStore: unknown }).__mvStore = useStore