@marver-design/marver 0.24.0 → 0.25.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 (80) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +1 -1
  3. package/dist/anchor-DVV732zR.mjs +33 -0
  4. package/dist/anchor-check-BE5VVN6Q.mjs +135 -0
  5. package/dist/{bake-ZhXq-X9f.mjs → bake-D8byeRzB.mjs} +1 -1
  6. package/dist/{boards-BRLnoTC3.mjs → board-tree-DRioF94d.mjs} +21 -277
  7. package/dist/boards-CGg6piKF.mjs +342 -0
  8. package/dist/{boards-Dv-Ipd8G.mjs → boards-Csxj2WJn.mjs} +23 -9
  9. package/dist/{build-ckcinlWH.mjs → build-BHoWLvSj.mjs} +63 -37
  10. package/dist/cli.mjs +31 -17
  11. package/dist/{collab-mAiNZlDj.mjs → collab-gqNdScUE.mjs} +39 -9
  12. package/dist/{comments-DZyobpxG.mjs → comments-Zoch254k.mjs} +19 -1
  13. package/dist/{comments-Dx1hCVOT.mjs → comments-pTLlhjh4.mjs} +150 -20
  14. package/dist/{config-BUKprFAp.mjs → config-cKgZBRj0.mjs} +1 -1
  15. package/dist/{context-BncTXjLB.mjs → context-D2ugHqwO.mjs} +17 -123
  16. package/dist/{daemon-CQv73-jM.mjs → daemon-Cl8KXGW4.mjs} +146 -64
  17. package/dist/{dev-gv4NS6Fk.mjs → dev-DJdgow47.mjs} +23 -11
  18. package/dist/{events-B3LBn74P.mjs → events-DnK_AnrW.mjs} +13 -15
  19. package/dist/imports-WBSnnHLb.mjs +143 -0
  20. package/dist/{init--3Moc4J7.mjs → init-DO4DhUt_.mjs} +28 -6
  21. package/dist/link-C-qUIuKU.mjs +160 -0
  22. package/dist/{board-status-BZSzc9Hp.mjs → manifest-DnAte_fB.mjs} +537 -13
  23. package/dist/marks-DFuintmJ.mjs +50 -0
  24. package/dist/marks-koRsbHfe.mjs +397 -0
  25. package/dist/{marver-id-gate-B_idGdHm.mjs → marver-id-gate-DGANtVyC.mjs} +2 -2
  26. package/dist/perf-CCisg-ny.mjs +49 -0
  27. package/dist/perf-QJIWtTw1.mjs +68 -0
  28. package/dist/{plugin-Sa08E7wO.mjs → plugin-CTyhjwoJ.mjs} +424 -207
  29. package/dist/{poster-B2QPvKOq.mjs → poster-D0cbV7hi.mjs} +1 -1
  30. package/dist/{profile-CrZohD6g.mjs → profile-Do0nGkXO.mjs} +1 -1
  31. package/dist/{publish-bakes-BJR3huhu.mjs → publish-bakes--l8ot2eQ.mjs} +9 -9
  32. package/dist/{serve-z5qtj_wJ.mjs → serve-wv2QWdxB.mjs} +6 -6
  33. package/dist/{share-BD-wcDQq.mjs → share-ScamJcks.mjs} +1 -1
  34. package/dist/{shot-Cw96h5Kk.mjs → shot-CckrGW-J.mjs} +19 -11
  35. package/dist/{shot-Dh6fV1Lm.mjs → shot-jdO_B6Qw.mjs} +1 -1
  36. package/dist/{summary-C7CAypbB.mjs → summary-CrW88e3q.mjs} +1 -1
  37. package/dist/{sync-DoA1vf4u.mjs → sync-C3035OnJ.mjs} +18 -8
  38. package/dist/{work-CBUfsOOT.mjs → work-CpJn1gwY.mjs} +8 -4
  39. package/dist/{work-ayuL_9Kk.mjs → work-GE88wb_3.mjs} +4 -4
  40. package/docs/boards-and-folders.md +62 -21
  41. package/docs/live-jam.md +10 -5
  42. package/package.json +1 -1
  43. package/src/client/frame-host/bridge.js +2 -1
  44. package/src/client/frame-host/inspect.js +195 -84
  45. package/src/client/frame-host/main.tsx +7 -2
  46. package/src/client/frame-host/registry.ts +5 -5
  47. package/src/client/shell/App.tsx +66 -22
  48. package/src/client/shell/BoardList.tsx +54 -11
  49. package/src/client/shell/Comments.tsx +79 -34
  50. package/src/client/shell/ContextMenu.tsx +5 -2
  51. package/src/client/shell/LockedApp.tsx +45 -12
  52. package/src/client/shell/Play.tsx +35 -34
  53. package/src/client/shell/Toolbar.tsx +3 -1
  54. package/src/client/shell/canvas/Canvas.tsx +1 -1
  55. package/src/client/shell/canvas/FrameNode.tsx +10 -5
  56. package/src/client/shell/canvas/sleep.ts +4 -3
  57. package/src/client/shell/canvas/updates.ts +55 -0
  58. package/src/client/shell/comments-store.ts +48 -19
  59. package/src/client/shell/goto.ts +11 -14
  60. package/src/client/shell/hash.ts +12 -5
  61. package/src/client/shell/icons.tsx +1 -2
  62. package/src/client/shell/legacy-links.ts +67 -0
  63. package/src/client/shell/marks-ui.tsx +17 -19
  64. package/src/client/shell/pin-layout.ts +37 -0
  65. package/src/client/shell/store.ts +312 -92
  66. package/src/client/shell/styles.css +10 -8
  67. package/src/client/stage/main.tsx +19 -2
  68. package/src/shared/anchor.ts +57 -0
  69. package/src/shared/board-tree.ts +27 -10
  70. package/src/shared/events.ts +19 -10
  71. package/src/shared/marks.ts +17 -12
  72. package/templates/AGENTS-embedded.md +34 -15
  73. package/templates/AGENTS-studio.md +34 -15
  74. package/templates/instructions/boards.md +9 -5
  75. package/templates/instructions/iterate.md +20 -10
  76. package/templates/instructions/jam.md +13 -4
  77. package/templates/instructions/publish.md +2 -1
  78. package/templates/instructions/reference/deck-story.md +2 -2
  79. package/dist/link-vXjxMHTG.mjs +0 -132
  80. package/dist/manifest-cyG3kbhk.mjs +0 -528
@@ -10,8 +10,8 @@ import shConfig from 'virtual:sh-config'
10
10
  import shData from 'virtual:sh-data'
11
11
 
12
12
  /** Published-build data. Non-null = static site: no API, no saves, no live events.
13
- * `names` is the switcher list (all-scenes only when actually published); `default`
14
- * is where `/` opens - never a synthesized aggregate of a filtered build. */
13
+ * `names` is the switcher list; `default` is where `/` opens - never a synthesized
14
+ * aggregate of a filtered build. */
15
15
  const DATA: {
16
16
  manifest: Manifest; boards: Record<string, unknown>; names: string[]; default: string
17
17
  /** the sidebar's folder tree over the published boards (0.16.0 bundles; older ones have none) */
@@ -28,8 +28,12 @@ const DATA: {
28
28
  bakes?: number
29
29
  /** content-frame heights, `scene/frame@width` -> px (design/boards/_sizes.json, published frames only) */
30
30
  sizes?: Record<string, number>
31
+ /** node key -> frame, off a leftover all-scenes.json, for old links naming keys (spec 26; shipped frames only) */
32
+ allScenesKeys?: Record<string, string>
31
33
  } | null = shData
32
34
 
35
+ /** An old All Scenes link's node keys a published bundle can still turn back into frames (legacy-links.ts). */
36
+ export const ALL_SCENES_KEYS: Record<string, string> = DATA?.allScenesKeys ?? {}
33
37
  /** The published textures' generation, or 0: the static index this build shipped is at /__mv/bakes/<gen>/index.json. */
34
38
  export const BAKES = DATA?.bakes ?? 0
35
39
  /** When a published bundle's statuses were read (spec 20) - absent in dev, where they are live. */
@@ -92,6 +96,15 @@ export interface Node {
92
96
  * as a failed frame; see canvas/ready-watch.ts). Transient - cleared on any real ready/error and
93
97
  * on every fresh navigation. */
94
98
  readyRetried?: boolean
99
+ /** spec 26: an update waits for this node - it reloads through the boot queue once the frame is on
100
+ * screen and not in use (canvas/updates.ts). Transient. */
101
+ stale?: boolean
102
+ /** spec 26: the revision of the document it shows - "epoch:doc", stamped by the dev server when it
103
+ * served the document, echoed by its sh:ready. A look counts only up to it. Transient. */
104
+ shown?: string
105
+ /** spec 26: the revision ("epoch:doc") a stale node waits for - a document showing it (or later)
106
+ * clears the wait, an older one keeps it. Transient. */
107
+ want?: string
95
108
  }
96
109
  /** A comment notification: a persistent bottom-right glass pill. Three kinds
97
110
  * share it - a Marver (agent) reply renders frame-first with the mark; a
@@ -151,7 +164,9 @@ export const modeAllowed = (board: string, mode: 'present' | 'focus' | 'slides')
151
164
  export { cap, humanize } from './labels.ts'
152
165
  import { cap, humanize } from './labels.ts'
153
166
  import { canAutoReload } from './canvas/ready-watch.ts'
154
- import { buildTree, flatten, labelOf, toWire, TREE_PROTOCOL, type TreeItem } from '../../shared/board-tree.ts'
167
+ import { pumpUpdates } from './canvas/updates.ts'
168
+ import { archiveLast, buildTree, flatten, framesOn, labelOf, toWire, TREE_PROTOCOL, type TreeItem } from '../../shared/board-tree.ts'
169
+ import { UNPLACED } from './hash.ts'
155
170
  import type { BoardType, StatusWord } from '../../shared/board-types.ts'
156
171
  import type { Phase, Status } from '../../shared/status.ts'
157
172
  import { isNew, type Marks } from '../../shared/marks.ts'
@@ -174,11 +189,11 @@ export interface BoardMeta {
174
189
  }
175
190
 
176
191
  /** The sidebar tree: root boards and folders in rank order, each folder's boards and
177
- * sub-folders inside (shared/board-tree.ts), plus the hashes it was built from. `all-scenes` is not in it - it
178
- * is pinned last by the callers. Throws on transport failure and on a malformed registry
179
- * (the server's 422 message) - callers keep their last known tree. */
192
+ * sub-folders inside (shared/board-tree.ts), plus the hashes it was built from. Throws on
193
+ * transport failure and on a malformed registry (the server's 422 message) - callers keep
194
+ * their last known tree. */
180
195
  export async function fetchBoardTree(): Promise<TreeSnapshot> {
181
- if (DATA) return { tree: DATA.tree ?? DATA.names.filter((n) => n !== 'all-scenes').map((n) => ({ kind: 'board', name: n })), base: { boards: {}, folders: null }, titles: DATA.titles ?? {}, meta: DATA.meta ?? {} }
196
+ if (DATA) return { tree: DATA.tree ?? DATA.names.map((n) => ({ kind: 'board', name: n })), base: { boards: {}, folders: null }, titles: DATA.titles ?? {}, meta: DATA.meta ?? {} }
182
197
  const [boards, reg] = await Promise.all([
183
198
  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 }[]>,
184
199
  fetch(`${ROUTE}/api/folders`).then(async (r) => {
@@ -205,21 +220,34 @@ export function rememberTitles(titles: Record<string, string>) {
205
220
  if (JSON.stringify(useStore.getState().boardTitles) !== JSON.stringify(titles)) useStore.setState({ boardTitles: titles })
206
221
  }
207
222
 
208
- /** Board names for switchers: the sidebar's reading order (folders flattened depth-first) and
209
- * the auto `all-scenes` everything-board LAST - it is the expensive one, never the landing.
210
- * Throws on transport failure - callers keep their last known list. */
223
+ /** Board names for switchers: the sidebar's reading order (folders flattened depth-first); the
224
+ * first is the landing board. Throws on transport failure - callers keep their last known list. */
211
225
  export async function fetchBoardNames(): Promise<string[]> {
212
226
  if (DATA) return DATA.names
213
227
  const snap = await fetchBoardTree()
214
228
  rememberTitles(snap.titles)
215
229
  rememberMeta(snap.meta)
216
- return [...flatten(snap.tree), 'all-scenes']
230
+ return flatten(snap.tree)
231
+ }
232
+ /** Where the canvas opens with no link: the first board in sidebar order, else (no board yet) the
233
+ * Not on a board view - empty, on a canvas with no frames either. */
234
+ export const landingBoard = async (): Promise<string> => (await fetchBoardNames().catch(() => [] as string[]))[0] ?? UNPLACED
235
+ /** Which board shows which frame (spec 26, Part 7): every board in sidebar order with archive
236
+ * boards last, the live frames each shows, and the frames on no board - from the dev server, or
237
+ * off a published bundle (whose frames are all on a published board). Throws on transport failure. */
238
+ export async function fetchMembership(): Promise<{ boards: { name: string; frames: string[] }[]; unplaced: string[] }> {
239
+ if (!DATA) {
240
+ const r = await fetch(`${ROUTE}/api/membership`)
241
+ if (!r.ok) throw new Error(`membership ${r.status}`)
242
+ return r.json()
243
+ }
244
+ const live = DATA.manifest.frames.map((f) => f.id)
245
+ const names = archiveLast(DATA.names, (n) => n === 'archive' || DATA.meta?.[n]?.type === 'archive')
246
+ return { boards: names.map((name) => ({ name, frames: framesOn(DATA.boards[name], live) })), unplaced: [] }
217
247
  }
218
- /** Does the switcher carry the auto `all-scenes` board? Always in dev; published only when it shipped. */
219
- export const HAS_ALL_SCENES = !DATA || DATA.names.includes('all-scenes')
220
248
  /** Display name for a board: its title when one is set (subscribe to `boardTitles` to
221
- * re-render on change), else the Title-Cased slug ('all-scenes' reads "All Scenes"). */
222
- export const boardLabel = (n: string) => labelOf(n, useStore.getState().boardTitles[n])
249
+ * re-render on change), else the Title-Cased slug. */
250
+ export const boardLabel = (n: string) => (n === UNPLACED ? 'Not on a board' : labelOf(n, useStore.getState().boardTitles[n]))
223
251
  /** The canvas's name, as the sidebar heads it: the project's (share.name, else the repo folder). */
224
252
  export const CANVAS_NAME = CONFIG.projectName ? humanize(CONFIG.projectName) : 'Marver'
225
253
  /** The browser tab: the board, then the canvas - "Start here - Acme Studio" - so a row of canvas tabs
@@ -231,19 +259,30 @@ export const sceneLabel = (n: string) => labelOf(n, useStore.getState().manifest
231
259
  /** The double-submit CSRF token the owner gate wants echoed (same read as comments-store). */
232
260
  const csrf = () => /(?:^|;\s*)mv_c=([\w-]+)/.exec(document.cookie)?.[1] ?? ''
233
261
  /** POST to an owner-gated dev API route, echoing the CSRF cookie the gate requires. */
262
+ /** The reload log (spec 26 Part 1): what this page saw boot or settle - best effort, dev only. */
263
+ const TAB = Math.random().toString(36).slice(2, 8)
264
+ /** Why a node's next document boots - a reload job, a reload by hand, the watchdog's retry; none known
265
+ * means a first load, or a document that reloaded itself (the reload log tells them apart). */
266
+ const reloadCause = new Map<string, 'job' | 'manual' | 'retry'>()
267
+ export const takeReloadCause = (key: string) => { const c = reloadCause.get(key); reloadCause.delete(key); return c }
268
+ export const logReload = (entry: Record<string, unknown>) => {
269
+ if (PUBLISHED) return
270
+ const body = { tab: TAB, ...entry }
271
+ // a page's very first request may go before its request cookie exists: a GET primes it, then once more
272
+ void postOwner('perf/reload', body).then((r) => (r.status === 403 ? fetch(`${ROUTE}/api/work`).then(() => postOwner('perf/reload', body)) : r)).catch(() => {})
273
+ }
234
274
  const postOwner = (path: string, body: unknown) =>
235
275
  fetch(`${ROUTE}/api/${path}`, { method: 'POST', headers: { 'content-type': 'application/json', 'x-mv-c': csrf() }, body: JSON.stringify(body) })
236
276
 
237
- /** The frames a board pins, straight from its file (dev fetch / published inline) -
238
- * membership only, never a load. Cross-board data-goto asks "which board shows this
239
- * frame?" without touching the live board state. */
240
- export async function boardFrames(name: string): Promise<string[]> {
241
- const board: any = DATA
242
- ? DATA.boards[name]
243
- : (await (await fetch(`${ROUTE}/api/boards/${name}`)).json())?.board
244
- return Array.isArray(board?.nodes)
245
- ? board.nodes.map((n: any) => (n && typeof n.frame === 'string' ? n.frame : '')).filter(Boolean)
246
- : []
277
+ /** Add to board (the Not on a board view): these frames appended to a board's file, as
278
+ * `marver boards pin` does. The answer is said; the file change re-reads the sidebar and the view. */
279
+ export async function addToBoard(board: string, frames: string[]): Promise<void> {
280
+ const { toast } = useStore.getState()
281
+ try {
282
+ const r = await postOwner('boards/pin', { board, frames })
283
+ const body = await r.json().catch(() => ({})) as { added?: string[]; error?: string }
284
+ toast(r.ok ? `${body.added?.length ? 'pinned' : 'already'} on ${boardLabel(board)}` : body.error ?? `could not pin (${r.status})`)
285
+ } catch { toast('could not reach the dev server') }
247
286
  }
248
287
 
249
288
  const HEADER = 28
@@ -406,12 +445,32 @@ function defaultSize(frame: FrameEntry) {
406
445
  }
407
446
 
408
447
  let resizedInGesture = false
448
+ // set inside the store (they need it): a reload's height hold, and the marks-vs-documents check
449
+ let holdHeight: (key: string) => void = () => {}
450
+ let reconcile: () => void = () => {}
409
451
  // sidebar marks: the fetch in flight, and acknowledgements the server has not confirmed yet
410
452
  let marksSeq = 0
411
453
  let marksTimer: ReturnType<typeof setTimeout> | undefined
412
454
  const pendingSeen: Record<string, number> = {}
413
- /** frames looked at before the first marks arrived (a link, a click, focus) - acknowledged when they land */
455
+ let pendingEpoch = ''
456
+ /** nodes (or 'stage') looked at before the first marks arrived (a link, a click, focus) - counted when they land */
414
457
  const lookedEarly = new Set<string>()
458
+ /** a look at a node (or 'stage') whose new version was still loading: it completes when that version is up,
459
+ * within ARMED_MS of the look (spec 26) */
460
+ const armed = new Map<string, { until: number; board: string; frame: string }>()
461
+ const ARMED_MS = 10_000
462
+ /** The doc revision a node's document shows, in this epoch - -1 when unknown or from another one. */
463
+ /** "epoch:rev" stamps: does `a` show at least `b` (same epoch, revision as high)? */
464
+ const atLeast = (a: string | undefined, b: string) => {
465
+ const [ea, ra] = (a ?? '').split(':'), [eb, rb] = b.split(':')
466
+ return ea === eb && Number(ra) >= Number(rb)
467
+ }
468
+ /** The later of two waits (a new epoch replaces the old one's). */
469
+ const later = (a: string | undefined, b: string | undefined) => (!a || !b ? a ?? b : atLeast(a, b) ? a : b)
470
+ export const shownRev = (n: Node, m: Marks): number => {
471
+ const [epoch, rev] = (n.shown ?? '').split(':')
472
+ return epoch === m.epoch && rev !== undefined && /^\d+$/.test(rev) ? Number(rev) : -1
473
+ }
415
474
  /** Why a board's last load failed, from the server (a parse error names its line) - for its toast. */
416
475
  const loadErrors = new Map<string, string>()
417
476
  const whyNot = (name: string) => { const e = loadErrors.get(name); return e ? ` - ${e}` : '' }
@@ -444,7 +503,7 @@ interface State {
444
503
  play: { at: string; device: string; theme: string; focus?: boolean; deep?: boolean; slides?: boolean } | null
445
504
  gesture: boolean // a frame drag/resize is in progress - canvas panning is disabled
446
505
  laser: boolean // laser/inspect mode: frames outline their structure
447
- board: string // active board name; 'all-scenes' is the auto board
506
+ board: string // active board name; UNPLACED is the Not on a board view
448
507
  boardAuto: boolean // auto boards gain new frames on arrival; curated boards never do
449
508
  deviceView: string | null // board-wide device preview (viewport name), null = free-form layout
450
509
  sceneRows: string[][] | null // LEGACY scene arrangement; still round-trips through save
@@ -458,13 +517,13 @@ interface State {
458
517
  toasts: Toast[]
459
518
  boardHash: string | null // sha256 of the board file on disk, when materialized
460
519
  dirty: boolean
461
- // A6/A7 controlled HMR (transient, never persisted): a frame the user is actively using
462
- // (interact/play target, mid-gesture, laser/comment engaged) is "leased" - a hot update to
463
- // it is DEFERRED (coalesced to the latest revision) until a safe point, so an agent edit
464
- // never yanks the user out of their flow.
465
- pendingFrameRevisions: Record<string, string> // frameId -> latest deferred revision
520
+ // Calm updates (spec 26, transient): an edit marks its frames' nodes stale; a stale node reloads
521
+ // through the boot queue once it is on screen and not in use - a frame the user is actively using
522
+ // (interact/play target, mid-gesture, laser/comment engaged) is "leased" and waits for a safe point.
466
523
  externalLeases: Record<string, { laser?: true; comment?: true }> // nodeKey -> transient engagement
467
524
  playUpdateRevision: string | null // a revision arrived while play is open
525
+ /** the frame the play/focus stage committed last, and the revision it shows (sh:stage-shown) */
526
+ stageShown: { at: string; shown: string } | null
468
527
  playNav: number // bumps to reload the play stage on demand
469
528
  pathPulse: number // bumps on each successful path copy - flashes the toolbar icon into a check
470
529
  imagePulse: number // bumps on each successful image copy - same flash, the images-square icon
@@ -494,9 +553,10 @@ interface State {
494
553
  setPlay(p: State['play']): void
495
554
  setGesture(g: boolean): void
496
555
  setLaser(on: boolean): void
497
- invalidateFrames(frameIds: string[], revision: string): void
556
+ invalidateFrames(frameIds: string[], revision: string, docs?: { epoch?: string; docs?: Record<string, number> }): void
498
557
  setExternalLease(nodeKey: string, reason: 'laser' | 'comment', on: boolean): void
499
- flushFrameUpdates(frameIds?: string[]): void
558
+ /** A safe point (a lease ended, a gesture ended): stale nodes may reload now. */
559
+ flushFrameUpdates(): void
500
560
  applyPlayUpdate(): void
501
561
  moveSelectedBy(dx: number, dy: number, starts: Record<string, { x: number; y: number }>): void
502
562
  setSelectedTheme(theme: string): void
@@ -545,20 +605,29 @@ interface State {
545
605
  /** Sidebar marks (spec 25): what changed since you looked - null on a published canvas. */
546
606
  marks: Marks | null
547
607
  syncMarks(): Promise<void>
548
- /** You looked at these frames: clear their "new", here and on disk - skipping one still holding a
549
- * deferred update, unless `shown` (the dwell and the play stage know what is on screen; Mark all as seen) */
550
- markSeen(frameIds: readonly string[], shown?: boolean): void
608
+ /** Mark all as seen: clear these frames' "new", here and on disk, whatever is loaded. */
609
+ markSeen(frameIds: readonly string[]): void
610
+ /** You looked at these nodes (or 'stage'): each clears its frame's "new" up to the revision it shows -
611
+ * one whose new version is not up yet waits for it (`rearm` false: a check, not a new look). */
612
+ look(keys: readonly string[], rearm?: boolean): void
613
+ /** A node's document reported the revision it shows (sh:ready). */
614
+ setShown(key: string, shown: string): void
615
+ /** A stale node's turn: it reloads now, its height held until it settles (canvas/updates.ts). */
616
+ startReload(key: string): void
551
617
  /** Boards showing a working frame - their sidebar icon shimmers while an agent works. */
552
618
  workingBoards: string[]
553
619
  /** The place in the server's order of the activity last applied - an older answer is dropped. */
554
620
  workingSeq: number
555
621
  spawn(frameId: string): Node | null
622
+ /** The Not on a board view follows its list in place: frames that left go, new ones join - the
623
+ * frames that stay keep their documents (no reload, no lost input). */
624
+ syncUnplaced(ids: readonly string[]): void
556
625
  save(): Promise<boolean>
557
626
  }
558
627
 
559
628
  /** A6: is any node of this frame in active use, so a hot update must DEFER? Frame-scoped -
560
629
  * if the same frame is placed twice and one copy is active, both stay on the same revision. */
561
- function frameIsLeased(frameId: string, s: State): boolean {
630
+ export function frameIsLeased(frameId: string, s: State): boolean {
562
631
  return s.nodes.some((n) =>
563
632
  n.frame === frameId && n.status !== 'error' && (
564
633
  s.interact === n.key ||
@@ -618,6 +687,8 @@ export const useStore = create<State>((set, get) => {
618
687
  const since = cameraSince ?? Date.now()
619
688
  if (canvasCtl.cameraBusy() && Date.now() - since < REFLOW_CAMERA_WAIT) { scheduleReflow(check ?? undefined, 60, since); return }
620
689
  if (check && !check()) return
690
+ 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
691
+ if (holds.size) { reflowOwed = true; return } // a batch is reloading: the rows move once, when it lets go
621
692
  // content moved the rows, not the human: hold what they are looking at still (Canvas.tsx)
622
693
  if (composed(s)) { canvasCtl.holdView(); s.runTidy() }
623
694
  }, delay)
@@ -626,6 +697,63 @@ export const useStore = create<State>((set, get) => {
626
697
  * note is made here; a board the human placed by hand is never moved (spec 18, 0.19.1). */
627
698
  const composed = (s: { layout: BoardLayout | null; sceneRows: string[][] | null; boardAuto: boolean }) => !!(s.layout || s.sceneRows?.length || s.boardAuto)
628
699
  const cramped = () => { const s = get(); return !!s.manifest && notesCramped(s.nodes, s.manifest) }
700
+ // Calm updates (spec 26): a node reloading keeps its height until its frame says it has settled
701
+ // (or HOLD_MS pass); a provisional measure in either direction waits, the last one is kept. The
702
+ // board reflows once, when the last held node lets go - never once per frame of a burst.
703
+ const HOLD_MS = 4000
704
+ const holds = new Map<string, { timer: ReturnType<typeof setTimeout>; at: number; last?: Parameters<State['measureNode']> }>()
705
+ let reflowOwed = false
706
+ holdHeight = (key) => {
707
+ const was = holds.get(key)
708
+ if (was) clearTimeout(was.timer)
709
+ holds.set(key, { timer: setTimeout(() => letGo(key, true), HOLD_MS), at: performance.now() })
710
+ }
711
+ const letGo = (key: string, apply: boolean) => {
712
+ const h = holds.get(key)
713
+ if (!h) return
714
+ clearTimeout(h.timer)
715
+ holds.delete(key)
716
+ if (apply && h.last) get().measureNode(...h.last)
717
+ if (!holds.size && reflowOwed) { reflowOwed = false; scheduleReflow() }
718
+ }
719
+ const dropHolds = () => { for (const h of holds.values()) clearTimeout(h.timer); holds.clear(); reflowOwed = false }
720
+ /** A content measure moved the rows: once, after the last held node lets go. */
721
+ const reflowAfterHolds = () => { if (holds.size) reflowOwed = true; else scheduleReflow() }
722
+
723
+ // Marks (spec 26): a node that shows an older revision than its frame's `doc` has missed an update
724
+ // (an event lost while disconnected, an edit that landed while it loaded): it goes stale. The
725
+ // snapshot is the truth; events only make it faster.
726
+ reconcile = () => {
727
+ const s = get(), m = s.marks
728
+ if (!m) return
729
+ let any = false
730
+ const nodes = s.nodes.map((n) => {
731
+ if (n.stale || n.status !== 'ready' || n.missing || !n.shown) return n
732
+ if (shownRev(n, m) >= (m.doc[n.frame] ?? 0)) return n
733
+ any = true
734
+ return { ...n, stale: true, want: later(n.want, `${m.epoch}:${m.doc[n.frame] ?? 0}`) }
735
+ })
736
+ if (any) { set({ nodes }); pumpUpdates() }
737
+ // the stage too: one that missed an update (a lost event) offers Update
738
+ const st = s.stageShown, f = st?.at
739
+ if (s.play && st && f && !s.playUpdateRevision) {
740
+ const [e, r] = st.shown.split(':')
741
+ if (e !== m.epoch || Number(r) < (m.doc[f] ?? 0)) set({ playUpdateRevision: 'missed' })
742
+ }
743
+ }
744
+
745
+ /** Acknowledge these revisions: here at once, and on disk - refused there from another epoch. */
746
+ const ack = (seen: Record<string, number>) => {
747
+ const m = get().marks
748
+ if (!m || !Object.keys(seen).length) return
749
+ Object.assign(pendingSeen, seen)
750
+ set({ marks: { ...m, seen: { ...m.seen, ...seen } } })
751
+ void postOwner('marks/seen', { epoch: m.epoch, frames: seen })
752
+ // kept once confirmed too (revisions only ever rise): an answer that left before this one cannot undo it
753
+ .then((r) => { if (!r.ok) throw new Error(String(r.status)) })
754
+ .catch(() => { for (const [id, at] of Object.entries(seen)) if (pendingSeen[id] === at) delete pendingSeen[id]; void get().syncMarks() })
755
+ }
756
+
629
757
  /** A note may have landed with no room (a frame note via the manifest, a scene note via
630
758
  * sh:scenes, either merged late by boot/switch): a composed board re-applies its layout. */
631
759
  const roomForNotes = () => { if (composed(get()) && cramped()) scheduleReflow(cramped) }
@@ -722,7 +850,7 @@ export const useStore = create<State>((set, get) => {
722
850
  }
723
851
  let nodes: Node[] = []
724
852
  let boardHash: string | null = null
725
- let boardAuto = boardName === 'all-scenes'
853
+ let boardAuto = false
726
854
  let deviceView: string | null = null
727
855
  let sceneRows: string[][] | null = null
728
856
  let layout: BoardLayout | null = null
@@ -734,7 +862,13 @@ export const useStore = create<State>((set, get) => {
734
862
  // published build: boards come from the inlined data; absent = fresh (the 404 path)
735
863
  let loaded: { board: any; sha256: string } | 'fresh' | null
736
864
  if (DATA) loaded = DATA.boards[boardName] ? { board: DATA.boards[boardName], sha256: 'published' } : 'fresh'
737
- else {
865
+ // the Not on a board view: a board of the frames no board shows, never saved - laid out
866
+ // fresh on every load (no hash) in one band of their scenes, its keys minted like any keyless node's
867
+ else if (boardName === UNPLACED) {
868
+ const m = await fetchMembership().catch(() => null)
869
+ const scenes = [...new Set(manifest.frames.filter((f) => m?.unplaced.includes(f.id)).map((f) => f.scene))]
870
+ loaded = m ? { board: { nodes: m.unplaced.map((frame) => ({ frame })), ...(scenes.length ? { layout: { rows: [scenes] } } : {}) }, sha256: '' } : null
871
+ } else {
738
872
  const res = await fetch(`${ROUTE}/api/boards/${boardName}`)
739
873
  if (res.ok) {
740
874
  const body = await res.json()
@@ -828,11 +962,11 @@ export const useStore = create<State>((set, get) => {
828
962
  // frames not on the board yet → auto boards only (a curated board shows exactly its list).
829
963
  // Grouped newcomers land beside their siblings (like the live JOIN); ungrouped ones
830
964
  // go past the board's right edge (the live JOIN flows them below) - NEVER at (0,0)
831
- // (the published all-scenes bug: frames created after the board file was last
965
+ // (the old published everything-board bug: frames created after the board file was last
832
966
  // saved piled up at the origin)
833
967
  if (boardAuto) {
834
968
  const placed = new Set(nodes.map((n) => n.frame))
835
- // newcomers get deterministic keys too - on published auto boards (all-scenes)
969
+ // newcomers get deterministic keys too - on a published auto board
836
970
  // this path mints EVERY key, every visit, and comments anchor to them
837
971
  const haveKeys = new Set(nodes.map((n) => n.key))
838
972
  const mint = (frame: string) => {
@@ -896,9 +1030,9 @@ export const useStore = create<State>((set, get) => {
896
1030
 
897
1031
  return {
898
1032
  manifest: null, nodes: [], selection: [], interact: null, viewTheme: initialViewTheme(), play: null, gesture: false, laser: false,
899
- board: DATA?.default ?? 'all-scenes', boardAuto: (DATA?.default ?? 'all-scenes') === 'all-scenes', deviceView: null, sceneRows: null, layout: null, layoutRaw: undefined, baseLayout: null, laidOut: null, baseLaidOut: null,
1033
+ board: DATA?.default ?? UNPLACED, boardAuto: false, deviceView: null, sceneRows: null, layout: null, layoutRaw: undefined, baseLayout: null, laidOut: null, baseLaidOut: null,
900
1034
  panelOpen: true, scale: 1, toasts: [], working: [], workingSince: {}, workingBoards: [], workingSeq: -1, boardHash: null, dirty: false, boardTitles: DATA?.titles ?? {}, boardMeta: DATA?.meta ?? {},
901
- pendingFrameRevisions: {}, externalLeases: {}, playUpdateRevision: null, playNav: 0, pathPulse: 0, imagePulse: 0, imageBusy: false,
1035
+ externalLeases: {}, playUpdateRevision: null, stageShown: null, playNav: 0, pathPulse: 0, imagePulse: 0, imageBusy: false,
902
1036
 
903
1037
  async boot(mayCommit) {
904
1038
  const seq = ++loadSeq
@@ -911,7 +1045,7 @@ export const useStore = create<State>((set, get) => {
911
1045
  if (get().board !== boardName || editRev !== revAtStart || (mayCommit && !mayCommit())) return false
912
1046
  const live = get().manifest // a WS manifest update may have landed mid-fetch
913
1047
  set(next)
914
- cancelReflow()
1048
+ cancelReflow(); dropHolds(); reloadCause.clear()
915
1049
  if (next.dirty) scheduleSave() // load-time prune must reach the disk
916
1050
  if (live && manifestKey(live) !== manifestKey(next.manifest as Manifest)) get().applyManifest(live)
917
1051
  else if (scenesRev !== scenesAtStart && liveScenes) set({ manifest: { ...get().manifest!, scenes: liveScenes } }) // an sh:scenes that landed mid-fetch outranks the file we read
@@ -948,7 +1082,7 @@ export const useStore = create<State>((set, get) => {
948
1082
  ++loadSeq // invalidate any in-flight boot of the old board
949
1083
  const live = get().manifest // a WS manifest update may have landed mid-load
950
1084
  set({ board: name, interact: null, ...next })
951
- cancelReflow()
1085
+ cancelReflow(); dropHolds(); reloadCause.clear()
952
1086
  if (next.dirty) scheduleSave() // load-time prune must reach the disk
953
1087
  if (live && manifestKey(live) !== manifestKey(next.manifest as Manifest)) get().applyManifest(live)
954
1088
  else if (scenesRev !== scenesAtStart && liveScenes) set({ manifest: { ...get().manifest!, scenes: liveScenes } })
@@ -1142,6 +1276,10 @@ export const useStore = create<State>((set, get) => {
1142
1276
  n.h = vp?.height ?? d.h
1143
1277
  }
1144
1278
  if (arrived) { delete n.sizeFallback; n.readyRetried = false } // a fresh mount earns a fresh allowance
1279
+ // gone or back, the node has no document: an update waiting for the old one is void, and the
1280
+ // next document boots fresh through admission (a reload job must never stand in for it)
1281
+ delete n.stale; delete n.shown; delete n.want
1282
+ if (missing) letGo(n.key, false)
1145
1283
  n.missing = missing
1146
1284
  changed = true
1147
1285
  }
@@ -1183,6 +1321,7 @@ export const useStore = create<State>((set, get) => {
1183
1321
  },
1184
1322
 
1185
1323
  removeNode(key) {
1324
+ letGo(key, false) // a node that goes holds no batch
1186
1325
  set((s) => ({
1187
1326
  nodes: s.nodes.filter((n) => n.key !== key),
1188
1327
  selection: s.selection.filter((k) => k !== key),
@@ -1259,6 +1398,14 @@ export const useStore = create<State>((set, get) => {
1259
1398
  // a Doc that reports IS one, whatever the last load's scan said (it arrived since): its heights
1260
1399
  // count until the next load re-reads the sources
1261
1400
  measuring?.add(f.id)
1401
+ // held while it reloads (spec 26): only a settled measure lands now; the last other one waits
1402
+ const held = holds.get(key)
1403
+ if (held) {
1404
+ if (settled !== true) { held.last = [key, frameId, ownWidth, measuredWidth, height, settled]; return }
1405
+ holds.delete(key); clearTimeout(held.timer)
1406
+ logReload({ kind: 'settled', node: key, frame: frameId, ms: performance.now() - held.at })
1407
+ if (!holds.size && reflowOwed) { reflowOwed = false; scheduleReflow() }
1408
+ }
1262
1409
  // Generous cap: a reference doc with many screenshots is legitimately very tall and must fit in
1263
1410
  // FULL (this was 2.5x a viewport ~= 2700px, which clipped image-heavy docs). Still bounded so a
1264
1411
  // broken measurement can't mint an infinite frame.
@@ -1282,7 +1429,7 @@ export const useStore = create<State>((set, get) => {
1282
1429
  // Doc layout changed (document<->wide): adopt the new own width first; the
1283
1430
  // iframe resizes, remeasures, and the height commits on the next message
1284
1431
  set((st) => ({ nodes: st.nodes.map((n) => (n.key === key ? { ...n, w: W } : n)) }))
1285
- scheduleReflow()
1432
+ reflowAfterHolds()
1286
1433
  return
1287
1434
  }
1288
1435
  }
@@ -1292,7 +1439,7 @@ export const useStore = create<State>((set, get) => {
1292
1439
  if (settled === true && node.sizeMode !== 'manual') persistHeight(mKey, H)
1293
1440
  if (Math.round(node.h) === H) return
1294
1441
  set((st) => ({ nodes: st.nodes.map((n) => (n.key === key ? { ...n, h: H } : n)) }))
1295
- scheduleReflow()
1442
+ reflowAfterHolds()
1296
1443
  },
1297
1444
  noteMeasured(key, height) {
1298
1445
  // the column's height is its content's - the layout learns it here, and a composed board
@@ -1342,6 +1489,8 @@ export const useStore = create<State>((set, get) => {
1342
1489
  // any real ready/error resets the one-shot retry allowance, so a later manual reload or a
1343
1490
  // fresh manifest earns its own auto-retry again
1344
1491
  set((s) => ({ nodes: s.nodes.map((n) => (n.key === key ? { ...n, status, error, readyRetried: false } : n)) }))
1492
+ if (status === 'error') letGo(key, false) // an error holds no batch
1493
+ if (status !== 'loading') pumpUpdates() // a slot, or a lease, may be free
1345
1494
  },
1346
1495
  // Reload a frame on a fresh rev-stamped URL (dodges a poisoned-cache document, #20). The
1347
1496
  // watchdog calls this with automatic=true after a silent deadline: it fires at most once per
@@ -1351,6 +1500,7 @@ export const useStore = create<State>((set, get) => {
1351
1500
  const n = get().nodes.find((x) => x.key === key)
1352
1501
  if (!n) return
1353
1502
  if (automatic && !canAutoReload(n)) return
1503
+ reloadCause.set(key, automatic ? 'retry' : 'manual')
1354
1504
  bumpManifestRev()
1355
1505
  set((s) => ({ nodes: s.nodes.map((x) => (x.key === key
1356
1506
  ? { ...x, status: 'loading' as const, error: undefined, nav: (x.nav ?? 0) + 1, readyRetried: automatic }
@@ -1368,7 +1518,7 @@ export const useStore = create<State>((set, get) => {
1368
1518
  return { selection, interact: s.interact && selection.includes(s.interact) ? s.interact : null }
1369
1519
  })
1370
1520
  // selecting a frame is looking at it, every time - even one already selected (spec 25)
1371
- if (key != null) { const f = get().nodes.find((n) => n.key === key)?.frame; if (f) get().markSeen([f]) }
1521
+ if (key != null) get().look([key])
1372
1522
  },
1373
1523
  // scoped device sizing: only the selected frames change; null restores their defaults.
1374
1524
  // Always followed by a tidy - a preset change must never scramble the layout.
@@ -1406,7 +1556,7 @@ export const useStore = create<State>((set, get) => {
1406
1556
  return { selection: valid, interact: s.interact && valid.includes(s.interact) ? s.interact : null }
1407
1557
  })
1408
1558
  // a frame link, a scene's name: the frames brought in front of you are looked at (⌘A is selectAll - not a look)
1409
- const st = get(); st.markSeen(st.selection.map((k) => st.nodes.find((n) => n.key === k)?.frame).filter((f): f is string => !!f))
1559
+ get().look(get().selection)
1410
1560
  },
1411
1561
  // interact is a ONE-frame mode: entering it collapses any multi-selection to the
1412
1562
  // interacted frame (a 4-frame selection double-clicked otherwise leaves all four
@@ -1438,32 +1588,43 @@ export const useStore = create<State>((set, get) => {
1438
1588
  }
1439
1589
  if (!gesture) get().flushFrameUpdates() // A6: gesture end is a safe point for deferred updates
1440
1590
  },
1441
- // A6/A7: apply a controlled hot update. A leased frame's revision is deferred (coalesced to
1442
- // the latest) and applied at the next safe point; an idle frame reloads now via its nav nonce.
1443
- invalidateFrames(frameIds, revision) {
1591
+ // Calm updates (spec 26): an edit reached these frames. Their nodes that show a document go
1592
+ // stale and reload through the boot queue - on screen first, never while in use; one still loading
1593
+ // its first document is checked against the marks when it is ready (setShown).
1594
+ invalidateFrames(frameIds, revision, docs) {
1444
1595
  const ids = new Set(frameIds.filter((x) => typeof x === 'string'))
1445
1596
  if (!ids.size) return
1446
- bumpManifestRev()
1447
1597
  const s = get()
1448
- const pending = { ...s.pendingFrameRevisions }
1449
- const nodes = s.nodes.map((n) => {
1450
- if (!ids.has(n.frame)) return n
1451
- if (frameIsLeased(n.frame, s)) { pending[n.frame] = revision; return n }
1452
- return { ...n, status: 'loading' as const, error: undefined, nav: (n.nav ?? 0) + 1, readyRetried: false }
1453
- })
1454
- set({ nodes, pendingFrameRevisions: pending, ...(s.play ? { playUpdateRevision: revision } : {}) })
1598
+ // every document of these frames is behind - one loading too (one running, one waiting): a document
1599
+ // that shows the revision the edit made clears it when it is ready (setShown)
1600
+ const want = (f: string) => (docs?.epoch && typeof docs.docs?.[f] === 'number' ? `${docs.epoch}:${docs.docs[f]}` : undefined)
1601
+ const nodes = s.nodes.map((n) => (ids.has(n.frame) && !n.missing ? { ...n, stale: true, want: later(n.want, want(n.frame)) } : n))
1602
+ set({ nodes, ...(s.play ? { playUpdateRevision: revision } : {}) })
1603
+ pumpUpdates()
1455
1604
  },
1456
- flushFrameUpdates(frameIds) {
1457
- const s = get()
1458
- const ids = (frameIds ?? Object.keys(s.pendingFrameRevisions)).filter((id) => s.pendingFrameRevisions[id] && !frameIsLeased(id, s))
1459
- if (!ids.length) return
1605
+ flushFrameUpdates() { pumpUpdates() },
1606
+ startReload(key) {
1607
+ const n = get().nodes.find((x) => x.key === key)
1608
+ if (!n) return
1609
+ reloadCause.set(key, 'job')
1460
1610
  bumpManifestRev()
1461
- const apply = new Set(ids)
1462
- const pending = { ...s.pendingFrameRevisions }
1463
- for (const id of ids) delete pending[id]
1464
- const nodes = s.nodes.map((n) => apply.has(n.frame)
1465
- ? { ...n, status: 'loading' as const, error: undefined, nav: (n.nav ?? 0) + 1, readyRetried: false } : n)
1466
- set({ nodes, pendingFrameRevisions: pending })
1611
+ holdHeight(key)
1612
+ set((s) => ({ nodes: s.nodes.map((x) => (x.key === key
1613
+ ? { ...x, stale: false, status: 'loading' as const, error: undefined, nav: (x.nav ?? 0) + 1, readyRetried: false }
1614
+ : x)) }))
1615
+ },
1616
+ setShown(key, shown) {
1617
+ set((s) => ({ nodes: s.nodes.map((x) => {
1618
+ if (x.key !== key) return x
1619
+ // a document that shows the revision its node waits for (or later) clears the wait; an older
1620
+ // one - a reload that started before the edit - keeps it, so the edit still lands
1621
+ const n = { ...x, shown }
1622
+ if (n.want) { if (atLeast(shown, n.want)) { n.stale = false; delete n.want } else n.stale = true }
1623
+ return n
1624
+ }) }))
1625
+ pumpUpdates()
1626
+ reconcile()
1627
+ if (armed.has(key)) get().look([key], false) // a look you made while it loaded
1467
1628
  },
1468
1629
  setExternalLease(nodeKey, reason, on) {
1469
1630
  set((s) => {
@@ -1478,7 +1639,11 @@ export const useStore = create<State>((set, get) => {
1478
1639
  applyPlayUpdate() {
1479
1640
  if (!get().playUpdateRevision) return
1480
1641
  bumpManifestRev()
1481
- set((s) => ({ playUpdateRevision: null, playNav: s.playNav + 1 }))
1642
+ set((s) => ({ playUpdateRevision: null, playNav: s.playNav + 1, stageShown: null })) // counted again once the new stage commits
1643
+ // pending until the new stage commits: one that never reports (its document failed before it
1644
+ // could) offers Update again
1645
+ const nav = get().playNav
1646
+ setTimeout(() => { const s = get(); if (s.play && s.playNav === nav && !s.stageShown && !s.playUpdateRevision) set({ playUpdateRevision: 'retry' }) }, 15_000)
1482
1647
  },
1483
1648
  setScale(scale) { set({ scale }) },
1484
1649
  pulsePath() { set((s) => ({ pathPulse: s.pathPulse + 1 })) },
@@ -1614,31 +1779,63 @@ export const useStore = create<State>((set, get) => {
1614
1779
  const r = await fetch(`${ROUTE}/api/marks`, { headers: { 'x-mv-c': csrf() } })
1615
1780
  if (seq !== marksSeq) return
1616
1781
  if (r.ok) {
1617
- const m = await r.json() as Marks
1618
- if (seq !== marksSeq) return
1782
+ const m = await r.json() as Marks | null
1783
+ if (seq !== marksSeq || !m) return
1784
+ // a new epoch (the marks started over): what this page held belongs to the old one
1785
+ if (m.epoch !== pendingEpoch) { for (const id of Object.keys(pendingSeen)) delete pendingSeen[id]; armed.clear(); pendingEpoch = m.epoch }
1619
1786
  const seen = { ...m.seen }
1620
1787
  for (const [id, at] of Object.entries(pendingSeen)) seen[id] = Math.max(seen[id] ?? 0, at)
1621
1788
  set({ marks: { ...m, seen } })
1622
- if (lookedEarly.size) { const early = [...lookedEarly]; lookedEarly.clear(); get().markSeen(early) }
1789
+ reconcile()
1790
+ if (lookedEarly.size) { const early = [...lookedEarly]; lookedEarly.clear(); get().look(early) }
1791
+ if (armed.size) get().look([...armed.keys()], false) // a look that waited on a newer version than the page knew
1623
1792
  return
1624
1793
  }
1625
1794
  if (r.status !== 403) return
1626
1795
  }
1627
1796
  } catch { /* the next broadcast heals it */ }
1628
1797
  },
1629
- markSeen(frameIds, shown) {
1630
- const m = get().marks, held = get().pendingFrameRevisions
1631
- if (!m) { if (!PUBLISHED) for (const id of frameIds) lookedEarly.add(id); return }
1632
- const fresh = frameIds.filter((id) => isNew(m, id) && (shown || !held[id]))
1633
- if (!m || !fresh.length) return
1634
- // you saw the change the page shows - its stamp, never a clock: an edit landing after this is new
1635
- const seen = Object.fromEntries(fresh.map((id) => [id, m.changed[id] ?? 0]))
1636
- Object.assign(pendingSeen, seen)
1637
- set({ marks: { ...m, seen: { ...m.seen, ...seen } } })
1638
- void postOwner('marks/seen', { frames: seen })
1639
- // kept once confirmed too (stamps only ever rise): an answer that left before this one cannot undo it
1640
- .then((r) => { if (!r.ok) throw new Error(String(r.status)) })
1641
- .catch(() => { for (const [id, at] of Object.entries(seen)) if (pendingSeen[id] === at) delete pendingSeen[id]; void get().syncMarks() })
1798
+ markSeen(frameIds) {
1799
+ const m = get().marks
1800
+ if (!m) return
1801
+ ack(Object.fromEntries(frameIds.filter((id) => isNew(m, id)).map((id) => [id, m.changed[id] ?? 0])))
1802
+ },
1803
+ look(keys, rearm = true) {
1804
+ const s = get(), m = s.marks
1805
+ if (!m) { if (!PUBLISHED) for (const k of keys) lookedEarly.add(k); return }
1806
+ // the revision a node (or the stage) shows of its frame: -1 while it does not show the frame's last
1807
+ // edit (stale, loading, an older document) - a look counts up to it, never past it
1808
+ const upTo = (k: string, f: string): number => {
1809
+ const doc = m.doc[f] ?? 0
1810
+ if (k === 'stage') {
1811
+ const st = s.stageShown
1812
+ if (!s.play || s.playUpdateRevision || !st) return -1
1813
+ const [e, r] = st.shown.split(':')
1814
+ return e === m.epoch && Number(r) >= doc ? Number(r) : -1
1815
+ }
1816
+ const n = s.nodes.find((x) => x.key === k)
1817
+ if (!n || n.status !== 'ready' || n.stale) return -1
1818
+ const r = shownRev(n, m)
1819
+ return r >= doc ? r : -1
1820
+ }
1821
+ const now = Date.now(), seen: Record<string, number> = {}
1822
+ for (const k of keys) {
1823
+ const f = k === 'stage' ? s.stageShown?.at : s.nodes.find((n) => n.key === k)?.frame
1824
+ const a = armed.get(k)
1825
+ // a remembered look holds for its own frame, on its own board, for ARMED_MS
1826
+ if (a && (a.until <= now || a.board !== s.board || a.frame !== f)) armed.delete(k)
1827
+ if (!rearm && !armed.has(k)) continue
1828
+ if (!f) { armed.delete(k); continue }
1829
+ const r = upTo(k, f)
1830
+ // what you saw: the last change as the page knows it - or the revision on screen when the document
1831
+ // already shows one the page has not heard of yet (everything up to it is there)
1832
+ const saw = Math.max(m.changed[f] ?? 0, r)
1833
+ if (saw <= (m.seen[f] ?? 0)) { armed.delete(k); continue }
1834
+ if (r < 0) { if (rearm) armed.set(k, { until: now + ARMED_MS, board: s.board, frame: f }); continue } // not up yet: the look waits for it
1835
+ armed.delete(k)
1836
+ seen[f] = Math.max(seen[f] ?? 0, saw)
1837
+ }
1838
+ ack(seen)
1642
1839
  },
1643
1840
  async syncWorking() {
1644
1841
  if (PUBLISHED) return
@@ -1678,6 +1875,26 @@ export const useStore = create<State>((set, get) => {
1678
1875
  return node
1679
1876
  },
1680
1877
 
1878
+ syncUnplaced(ids) {
1879
+ const s = get()
1880
+ if (s.board !== UNPLACED || !s.manifest) return
1881
+ const want = new Set(ids)
1882
+ const keep = s.nodes.filter((n) => want.has(n.frame))
1883
+ const add = ids.filter((id) => !keep.some((n) => n.frame === id))
1884
+ if (keep.length === s.nodes.length && !add.length) return
1885
+ for (const n of s.nodes) if (!want.has(n.frame)) letGo(n.key, false)
1886
+ const joined: Node[] = add.flatMap((id) => {
1887
+ const f = s.manifest!.frames.find((x) => x.id === id)
1888
+ if (!f) return []
1889
+ const d = defaultSize(f)
1890
+ return [{ key: nodeKey(), frame: f.id, x: 0, y: 0, w: d.w, h: d.h, theme: resolveTheme(f), status: 'loading' as const, ...(f.contentWidth ? { sizeMode: 'auto' as const } : {}) }]
1891
+ })
1892
+ const nodes = [...keep, ...joined]
1893
+ const scenes = [...new Set(nodes.map((n) => s.manifest!.frames.find((f) => f.id === n.frame)?.scene).filter((x): x is string => !!x))]
1894
+ set({ nodes, selection: s.selection.filter((k) => nodes.some((n) => n.key === k)), layout: scenes.length ? { rows: [scenes] } : null })
1895
+ get().runTidy() // one band of its scenes again; the view is never saved
1896
+ },
1897
+
1681
1898
  save() {
1682
1899
  // a rename is moving this board's file - defer every save so nothing writes to the OLD
1683
1900
  // name mid-move (renameBoard reschedules once the move commits under the new name)
@@ -1693,6 +1910,8 @@ export const useStore = create<State>((set, get) => {
1693
1910
  set({ dirty: false })
1694
1911
  return Promise.resolve(true)
1695
1912
  }
1913
+ // the Not on a board view is never saved: what is moved there lasts the visit
1914
+ if (get().board === UNPLACED) { set({ dirty: false }); return Promise.resolve(true) }
1696
1915
  const p = saveChain.then(async () => {
1697
1916
  // recheck INSIDE the serialized chain: a save queued behind an in-flight PUT
1698
1917
  // may only execute after a resize gesture began - the entry guard above ran
@@ -1766,11 +1985,12 @@ export const useStore = create<State>((set, get) => {
1766
1985
  }
1767
1986
  })
1768
1987
 
1769
- // a frame opened in focus or play is looked at (spec 25); selecting one is handled in select()
1988
+ // a frame shown in focus or play is looked at (spec 25): the stage reports each frame it commits,
1989
+ // with the revision it shows (Play.tsx sets stageShown) - selecting one is handled in select()
1770
1990
  useStore.subscribe((s, prev) => {
1771
- // a frame opened in focus or play is in front of you too - stepping within play while an edit is
1772
- // held behind Update shows the old version, so that waits for the dwell after Update
1773
- if (s.play?.at && s.play.at !== prev.play?.at && (!prev.play || !s.playUpdateRevision)) { const f = s.nodes.find((n) => n.key === s.play!.at)?.frame ?? s.play.at; s.markSeen([f], true) }
1991
+ if (s.stageShown && s.stageShown !== prev.stageShown) { reconcile(); s.look(['stage']) } // a late commit of an older stage offers Update
1992
+ // the canvas is in view again; an Update the closed stage held goes with it (the next one is served fresh)
1993
+ if (!s.play && prev.play) { useStore.setState({ stageShown: null, playUpdateRevision: null }); pumpUpdates() }
1774
1994
  })
1775
1995
 
1776
1996
  // dev-only inspection hook for tests/debugging (never installed in published builds)