@marver-design/marver 0.33.0 → 0.35.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 (39) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +1 -1
  3. package/dist/{anchor-check-KCe6WeRA.mjs → anchor-check-DREwCQiE.mjs} +1 -1
  4. package/dist/{build-4-k2XhhX.mjs → build-3AH123fe.mjs} +3 -3
  5. package/dist/cli.mjs +5 -8
  6. package/dist/{comments-C2SN1QdM.mjs → comments-C7NjFGgl.mjs} +14 -7
  7. package/dist/{daemon-CCDgagw2.mjs → daemon-BE-t9iU-.mjs} +2 -4
  8. package/dist/{dev-CJf5upVK.mjs → dev-Dw6mcoP8.mjs} +7 -7
  9. package/dist/{notes-CRAX4wgk.mjs → notes-CmfQ9604.mjs} +13 -4
  10. package/dist/{pdf-GGya_nI6.mjs → pdf-CkE4Ir2P.mjs} +3 -3
  11. package/dist/{plugin-Cm74UDfp.mjs → plugin-C6jEpbCx.mjs} +43 -34
  12. package/dist/{poster-BnuT9UyW.mjs → poster-d10h73z0.mjs} +1 -1
  13. package/dist/{publish-bakes-zHmPEOB5.mjs → publish-bakes-weNQnNqE.mjs} +2 -2
  14. package/dist/{recover-BpRQxBA7.mjs → recover-Dekpav7b.mjs} +1 -1
  15. package/dist/{shot-HZtclbOT.mjs → shot-Ct2FiEbu.mjs} +2 -2
  16. package/docs/boards-and-folders.md +1 -1
  17. package/docs/performance.md +4 -0
  18. package/docs/slides.md +8 -0
  19. package/package.json +1 -1
  20. package/src/client/const.ts +5 -0
  21. package/src/client/content/img-lod.ts +3 -1
  22. package/src/client/frame-host/inplace.ts +43 -0
  23. package/src/client/frame-host/main.tsx +10 -1
  24. package/src/client/shell/App.tsx +26 -18
  25. package/src/client/shell/LockedApp.tsx +6 -5
  26. package/src/client/shell/canvas/Canvas.tsx +50 -16
  27. package/src/client/shell/canvas/FrameNode.tsx +40 -7
  28. package/src/client/shell/canvas/admission.ts +138 -5
  29. package/src/client/shell/canvas/sleep.ts +258 -26
  30. package/src/client/shell/hash.ts +24 -0
  31. package/src/client/shell/jam-capture.ts +3 -2
  32. package/src/client/shell/notes.ts +11 -4
  33. package/src/client/shell/recorder.ts +1 -1
  34. package/src/client/shell/store.ts +63 -11
  35. package/templates/AGENTS-embedded.md +3 -3
  36. package/templates/AGENTS-studio.md +3 -3
  37. package/templates/instructions/iterate.md +1 -1
  38. package/templates/instructions/reference/deck-replicate.md +44 -0
  39. package/templates/instructions/slides.md +8 -0
@@ -15,7 +15,24 @@
15
15
  * nearest the centre of the canvas first) on where each frame will be once the camera lands
16
16
  * (canvasCtl.landing) - it need not wait out the fit's ~320 ms flight. With no aim it waits SETTLE, as
17
17
  * long as that flight. A freed slot pumps on the next microtask, ranking again by the view of that moment.
18
+ *
19
+ * The gate is no absolute ceiling: a board with hundreds of frames all readable in view at once still boots them, as on
20
+ * the parent - it holds back only what the person cannot be looking at.
21
+ *
22
+ * Under the heap's line, with or without a gesture, admission is the parent's exactly: a person's pan or zoom stops
23
+ * nothing (holding boots through a gesture was measured and set aside as a candidate for the owner - it trades frames
24
+ * in view arriving about half the pan's length later for a smoother pan: perf/loop/candidates/i10-gesture-hold).
25
+ *
26
+ * Nothing unloads, so a board too heavy for the renderer's heap would boot itself into a crash. Past HEAP_SAFE of the
27
+ * browser's own heap limit (performance.memory, where the browser has it), a frame that is not near the view (its
28
+ * `near`) waits: it boots when the camera comes near it - a gesture's end, an aim, a layout or window change, or at
29
+ * the latest the next look TICK_MS later - like any frame still loading. The gate opens again under HEAP_RESUME. While it
30
+ * is shut and frames wait, it is asked again every TICK_MS whatever else happens (one memory read and one pass over the
31
+ * waiting frames' `near`); the events only make that sooner. A board that stays under the line boots every frame, as
32
+ * before. The boards that change are those whose full load would sit between the gate's lines and the crash line.
18
33
  */
34
+ import { LOD_MIN_PX, ZOOM_MAX } from '../../const.ts'
35
+
19
36
  export const SLOTS = 4
20
37
  /** A new batch's head start: one frame alone until it is done, or until this long - one stalled
21
38
  * first frame must not hold the whole board. */
@@ -25,7 +42,61 @@ let gen = 0 // the batch: a pump scheduled for an earlier one is void
25
42
  let timer: ReturnType<typeof setTimeout> | undefined
26
43
  let settling: ReturnType<typeof setTimeout> | undefined // a pump waiting for the view to settle (SETTLE): aimed() runs it now
27
44
 
28
- export interface Admission { key: string; rank: () => number; start: () => void }
45
+ /**
46
+ * The heap gate's lines, fractions of the browser's own limit (jsHeapSizeLimit), measured in headless Chrome (limit
47
+ * 4,192 MB). The crash: a 733-frame board killed the renderer at 97% of it, its boots halving their pace past ~93% (a
48
+ * page that only allocates died at 87%). A load's own transient: the heaviest board that fits (272 frames) peaks at 69%
49
+ * while it loads and settles at 50% - 19 points of garbage on top of its live heap. Shut at 0.75, reopened under 0.60,
50
+ * the parked 733-frame board comes to rest at 61-65%, and each approach to its parked frames (2-9 near frames) adds
51
+ * ~1-2 points live, up to ~5 transient: room for one load-sized transient on top of the rest, and some 30 approaches
52
+ * before the 97% line. Narrower lines (0.79/0.77) left that board at 81% and six approaches took it to 88% - less room
53
+ * than one transient; a crash is the worst outcome, a board that stops short and boots the rest on approach the mild one.
54
+ *
55
+ * Changed, against the parent: a board whose live heap after loading would exceed ~60% of the limit (~2.5 GB here,
56
+ * ~1.2 GB at a 2 GB limit) stops there and boots the rest as the camera approaches. One that only spikes past 0.75 while
57
+ * it loads and settles under 0.60 finishes on its own: the next look (TICK_MS) after a collection reopens the gate. One
58
+ * that plateaus between the lines stays parked: its far frames boot on approach. Under 0.75, nothing changes.
59
+ */
60
+ export const HEAP_SAFE = 0.75
61
+ export const HEAP_RESUME = 0.6
62
+ /** While the gate is shut and frames wait: how often it is asked again, whatever else happens. One look reads every
63
+ * waiting frame's iframe as drawn (getBoundingClientRect, one canvas rect per pass): 6.0-6.9 ms on the parked 733-frame
64
+ * archive (~460 waiting), about 11 ms per 5 s - and only on a board the gate has parked. */
65
+ export const TICK_MS = 3000
66
+ /** Two changes of the reading known to lie within this window prove it precise (see heapGated). */
67
+ const PRECISE_MS = 60_000
68
+ let gated = false // past HEAP_SAFE: only near frames start, until a reading under HEAP_RESUME
69
+ let precise = false // the page's reading has been seen to move twice within PRECISE_MS: it is exact
70
+ let memLast: number | undefined // the last usedJSHeapSize read
71
+ let readAt = -Infinity // when admission last read it
72
+ let changeFrom = -Infinity // the earliest the last change seen can have happened: the read before it
73
+ let tick: ReturnType<typeof setTimeout> | undefined
74
+ let epoch = 0 // resetAdmission's: a collection's callback from before it does nothing
75
+ let watching = false // a collection will pump the queue (sooner than the tick)
76
+ const collected = typeof FinalizationRegistry === 'function'
77
+ ? new FinalizationRegistry<number>((e) => { if (e !== epoch) return; watching = false; if (gated && waiting.size) schedule(0) })
78
+ : null
79
+
80
+ /** A readable frame's smaller side on screen, device px: 16 CSS px at a 2x display - about one line of text; a strip
81
+ * thinner than that shows nothing to read whatever its length. */
82
+ const STRIP_MIN_PX = 32
83
+ /** Past the heap's line, may a frame boot? Its iframe on screen where the camera lands (r), against the canvas (c): in
84
+ * view or within half a screen of it (updates.ts's margin), and large enough to be read on both sides - the larger at
85
+ * least image-LOD's smallest decode width (LOD_MIN_PX device px), the smaller at least STRIP_MIN_PX - each bar capped at
86
+ * what the ordinary camera can make of that side (its world size, `world`, at ZOOM_MAX), so every frame stays reachable
87
+ * by moving the camera to it. A thumbnail on a zoomed-out board waits until the camera comes closer. */
88
+ export function readable(r: Box, c: Box, dpr: number, world: { width: number; height: number }): boolean {
89
+ const k = Math.min(dpr || 1, 2), mx = c.width / 2, my = c.height / 2
90
+ const big = Math.max(r.width, r.height) * k, small = Math.min(r.width, r.height) * k
91
+ const reach = (side: number) => side * ZOOM_MAX * k - 0.5
92
+ return big >= Math.min(LOD_MIN_PX - 0.5, reach(Math.max(world.width, world.height)))
93
+ && small >= Math.min(STRIP_MIN_PX - 0.5, reach(Math.min(world.width, world.height)))
94
+ && r.right > c.left - mx && r.left < c.right + mx && r.bottom > c.top - my && r.top < c.bottom + my
95
+ }
96
+ type Box = { left: number; right: number; top: number; bottom: number; width: number; height: number }
97
+
98
+ /** `near`: in view or close to it, where the camera will land - a frame that may boot whatever the heap. Absent: always. */
99
+ export interface Admission { key: string; rank: () => number; start: () => void; near?: () => boolean }
29
100
 
30
101
  const waiting = new Map<string, Admission>()
31
102
  const active = new Set<string>()
@@ -36,7 +107,7 @@ let scheduled = false
36
107
  export function admit(a: Admission): void {
37
108
  if (active.has(a.key)) return
38
109
  if (!waiting.size && !active.size) { // a new batch
39
- primed = false; gen++; scheduled = false; clearTimeout(timer); clearTimeout(settling); settling = undefined
110
+ primed = false; gen++; scheduled = false; gated = false; clearTimeout(timer); clearTimeout(settling); settling = undefined
40
111
  timer = setTimeout(() => { primed = true; schedule(0) }, HEAD_MS)
41
112
  }
42
113
  waiting.set(a.key, a)
@@ -50,11 +121,16 @@ const SETTLE = 350
50
121
  * restored (Canvas.tsx). A pump waiting for the view to settle runs now: its ranks read where each frame will be once
51
122
  * the camera lands (canvasCtl.landing), so the first pick is the one SETTLE would have made, a flight earlier. */
52
123
  export function aimed(): void {
53
- if (settling === undefined) return
124
+ if (settling === undefined) { if (gated && waiting.size) schedule(0); return }
54
125
  clearTimeout(settling); settling = undefined; scheduled = false
55
126
  schedule(0)
56
127
  }
57
128
 
129
+ /** What a frame is near may have changed - the camera came to rest, a layout animation ended, the window was resized, the
130
+ * page was shown again: while the heap gate is shut, the queue is looked at again (a frame it keeps may be near now).
131
+ * Under the line it does nothing - admission there is the parent's. */
132
+ export function reconsider(): void { if (gated && waiting.size) schedule(0) }
133
+
58
134
  /** The frame is done booting (ready, error, gone, or its watchdog took over): free the slot, or
59
135
  * leave the queue if it never started. */
60
136
  export function release(key: string): void {
@@ -76,11 +152,47 @@ function schedule(ms: number): void {
76
152
  if (ms) settling = setTimeout(() => { settling = undefined; run() }, ms); else queueMicrotask(run)
77
153
  }
78
154
 
155
+ /**
156
+ * Is the heap gate shut? Only on a reading it can trust. Chromium gives performance.memory exact only to a process locked
157
+ * to one site (cached 50 ms); elsewhere it is bucketed and refreshed at most once every twenty minutes (blink's
158
+ * memory_info.cc). Precision is the process's, so it is proven once: two changes of the reading within PRECISE_MS - a
159
+ * load moves an exact counter at every boot; a bucketed one changes once per twenty minutes, never twice in a minute.
160
+ * Until then - and for good where the reading is bucketed - the gate stays open and the queue runs as it always did. A
161
+ * proven reading is trusted even when it holds still (nothing allocated). Never where the browser does not say (Safari,
162
+ * Firefox).
163
+ */
164
+ function heapGated(): boolean {
165
+ const m = (performance as { memory?: { usedJSHeapSize: number; jsHeapSizeLimit: number } }).memory
166
+ if (!m || !(m.jsHeapSizeLimit > 0)) return (gated = false)
167
+ const now = performance.now(), used = m.usedJSHeapSize
168
+ // a change seen now happened after the read before it: two changes prove a fast counter only if both lie, for sure,
169
+ // inside PRECISE_MS - from the earlier one's lower bound to now. A gap in admission's own reads (the queue empty while
170
+ // another reader, or time, refreshed Chromium's shared sample) proves nothing.
171
+ if (memLast !== undefined && used !== memLast) { if (now - changeFrom < PRECISE_MS) precise = true; changeFrom = readAt }
172
+ memLast = used; readAt = now
173
+ if (!precise) return (gated = false)
174
+ if (used > HEAP_SAFE * m.jsHeapSizeLimit) gated = true
175
+ else if (used < HEAP_RESUME * m.jsHeapSizeLimit) gated = false
176
+ return gated
177
+ }
178
+
79
179
  function pump(): void {
80
180
  scheduled = false
181
+ clearTimeout(tick); tick = undefined
182
+ if (!waiting.size) return
183
+ const high = heapGated() // every pump reads it: an exact counter proves itself within a load's first boots
81
184
  while (active.size < (primed ? SLOTS : 1) && waiting.size) {
82
185
  let best: Admission | undefined, bestRank = Infinity
83
- for (const a of waiting.values()) { const r = a.rank(); if (r < bestRank || !best) { best = a; bestRank = r } }
186
+ for (const a of waiting.values()) {
187
+ if (high && a.near && !a.near()) continue
188
+ const r = a.rank(); if (r < bestRank || !best) { best = a; bestRank = r }
189
+ }
190
+ if (!best) { // parked: asked again at the next tick at the latest, sooner on a collection
191
+ const g = gen
192
+ tick = setTimeout(() => { tick = undefined; if (g === gen) pump() }, TICK_MS)
193
+ if (collected && !watching) { watching = true; collected.register({}, epoch) }
194
+ return
195
+ }
84
196
  waiting.delete(best!.key)
85
197
  active.add(best!.key)
86
198
  ;(globalThis as { __mvAdmitted?: string[] }).__mvAdmitted?.push(best!.key) // diagnostic: the order, when a probe asks for it
@@ -89,4 +201,25 @@ function pump(): void {
89
201
  }
90
202
 
91
203
  /** For tests: nothing queued, nothing active. */
92
- export function resetAdmission(): void { waiting.clear(); active.clear(); primed = false; scheduled = false; gen++; clearTimeout(timer); clearTimeout(settling); settling = undefined }
204
+ export function resetAdmission(): void { waiting.clear(); active.clear(); primed = false; scheduled = false; gen++; clearTimeout(timer); clearTimeout(settling); settling = undefined; clearTimeout(tick); tick = undefined; gated = false; precise = false; memLast = undefined; readAt = -Infinity; changeFrom = -Infinity; watching = false; epoch++ }
205
+
206
+ /** A hot-replaced module leaves nothing of its own behind: no timer, and no pump already queued (its batch is void). */
207
+ export function disposeAdmission(): void {
208
+ clearTimeout(timer); clearTimeout(settling); settling = undefined; clearTimeout(tick); tick = undefined
209
+ gen++; scheduled = false; epoch++
210
+ }
211
+ if (import.meta.hot) import.meta.hot.dispose(disposeAdmission)
212
+
213
+ /** Canvas.tsx's wiring, in one place (tested): what a frame is near changing - the camera at rest, a layout animation's
214
+ * end, a resize, the page shown again (a hidden page's timers run once a minute) - looks again. Returns the unwiring. */
215
+ export function wireAdmission(
216
+ onMotion: (fn: (m: { camera: boolean; preset: boolean }) => void) => () => void,
217
+ win: Pick<EventTarget, 'addEventListener' | 'removeEventListener'>,
218
+ doc: Pick<EventTarget, 'addEventListener' | 'removeEventListener'> & { visibilityState: string },
219
+ ): () => void {
220
+ const off = onMotion((m) => { if (!m.camera && !m.preset) reconsider() })
221
+ const shown = () => { if (doc.visibilityState === 'visible') reconsider() }
222
+ win.addEventListener('resize', reconsider)
223
+ doc.addEventListener('visibilitychange', shown)
224
+ return () => { off(); win.removeEventListener('resize', reconsider); doc.removeEventListener('visibilitychange', shown) }
225
+ }
@@ -35,7 +35,8 @@ import type { BakeWork } from '../../../shared/perf-run.ts'
35
35
  /** `doc`: the revision the document shows (spec 26) - the compiler refuses a document behind its frame */
36
36
  export interface SleepKey { frame: string; theme: string; w: number; h: number; doc?: string }
37
37
  interface Target { sel: string; rect: { x: number; y: number; w: number; h: number }; filter: string; level: number; texture: string; verified: boolean }
38
- type Answer = { ok: true; targets: Target[] } | { ok: false; error: string }
38
+ /** `gen`: the server's source generation the answer holds for (a dev canvas); `kept`: a refusal the server keeps for it */
39
+ type Answer = ({ ok: true; targets: Target[] } | { ok: false; error: string; kept?: boolean }) & { gen?: number }
39
40
 
40
41
  const STYLE_ID = 'mv-sleep'
41
42
  /** How far (CSS px) any EDGE of an element's border box may sit from the one the compiler measured.
@@ -79,8 +80,9 @@ export function scheduleSleep(fn: () => void, ms: number): () => void {
79
80
  const pending = new Map<string, number>()
80
81
  let seq = 0
81
82
  /** Nodes with a retry of a failed compile in flight - or, in a headless perf run, spent: a run's frame retries once
82
- * until it wakes, so the run can reach bake-idle; every other canvas retries every 4 s for as long as the frame
83
- * rests, as before 0.27.2, so a frame recovers when the server does. */
83
+ * until it wakes, so the run can reach bake-idle; every other canvas retries a failure that may pass (not a settled
84
+ * answer: `parked` below) every 4 s for as long as the frame rests, as before 0.27.2, so a frame recovers when the
85
+ * server does. */
84
86
  const retried = new Set<string>()
85
87
  const RETRY_MS = 4000
86
88
  /** The server's answer for a compile still running (src/server/bake.ts COMPILING), and how many times a
@@ -90,6 +92,106 @@ const COMPILING_TRIES = 15
90
92
  /** Looks so far, per node, for the sleep key they were for: a new key (an edit, a theme, a size)
91
93
  * or a wake starts the count again. */
92
94
  const compiling = new Map<string, { key: string; n: number }>()
95
+ /**
96
+ * Nodes resting on a SETTLED answer - one the server gives again, word for word, while it retains it: a refusal it keeps
97
+ * for the source generation (`kept`: the frame loops, never stops changing, has too many effects...) or a compile none
98
+ * of whose textures certified (its disk cache). Asking again every 4 s, forever, changed nothing but cost a POST, a
99
+ * computed-style walk, a style rewrite and a forced layout per frame. A parked node asks again through the normal sleep:
100
+ * - when it learns of a generation DIFFERENT from its answer's - a push (`sh:bake-gen`, every source change), or any
101
+ * bake answer over HTTP (the shell's own socket may stay closed: api.ts). Equality only: a replacement server may
102
+ * count from anywhere, so no generation is "newer";
103
+ * - when the server would now answer otherwise with the generation unchanged (its retained answer evicted, deleted,
104
+ * replaced): the BACKSTOP, one batched ask for every parked node each `backstopMs` (30 s: 2 POSTs a minute for
105
+ * the whole board where the retries made 76), which touches no document - only a node whose answer changed goes
106
+ * back through the sleep;
107
+ * - on a reconnect (perhaps a new server), and when it wakes (a new document, theme or size: a new key).
108
+ * No sleep timer, so a parked node is bake-idle; a headless perf run has no backstop (it goes idle and stays so).
109
+ */
110
+ interface Parked { key: SleepKey; gen: number | undefined; sig: string; retry: () => void }
111
+ const parked = new Map<string, Parked>()
112
+ /** What an answer says, for "did it change": the kind, the refusal word for word, whether any texture certifies. */
113
+ const sigOf = (a: Answer): string => (a.ok ? `ok:${a.targets.some((t) => t.verified && t.texture) ? 1 : 0}` : `${a.kept ? 'kept' : 'no'}:${a.error}`)
114
+ /** Every generation heard - a push, any bake answer, a reconnect (`undefined`: perhaps a new server) - numbered, the
115
+ * last HEARD_KEPT of them kept: an ask that one of them overtook asks once more. */
116
+ let heardSeq = 0
117
+ const HEARD_KEPT = 64
118
+ const heardLog: { seq: number; gen: number | undefined }[] = []
119
+ /** Was a generation other than `gen` heard after `since`? (Forgotten ones count as other: one re-ask too many at worst.) */
120
+ function heardOther(since: number, gen: number | undefined): boolean {
121
+ if (heardSeq - since > HEARD_KEPT) return true
122
+ return heardLog.some((e) => e.seq > since && (e.gen === undefined || e.gen !== gen))
123
+ }
124
+ /** When each node last asked (its bake POST went out), on the monotonic clock. Every release of a parked node asks
125
+ * again at max(now + 250 ms, its last ask + RETRY_MS): never more than once per 4 s and never later than 4 s after
126
+ * its previous ask - the old retry's own cadence, at worst - and at once after a long rest. */
127
+ const lastAsk = new Map<string, number>()
128
+ function release(nodeKey: string): void {
129
+ const p = parked.get(nodeKey)
130
+ if (!p) return
131
+ parked.delete(nodeKey)
132
+ const was = lastAsk.get(nodeKey)
133
+ // every node released in the same moment shares one batch
134
+ scheduleSleep(p.retry, was === undefined ? 250 : Math.max(250, was + RETRY_MS - performance.now()))
135
+ }
136
+ /** A generation heard of: every node parked under a DIFFERENT one asks again. `undefined`: perhaps a new server - all do. */
137
+ function heard(gen: number | undefined): void {
138
+ heardLog.push({ seq: ++heardSeq, gen })
139
+ if (heardLog.length > HEARD_KEPT) heardLog.shift()
140
+ for (const [nodeKey, p] of [...parked]) if (gen === undefined || (p.gen !== undefined && p.gen !== gen)) release(nodeKey)
141
+ }
142
+ const pushed = (gen: number | undefined): void => heard(gen)
143
+ function park(nodeKey: string, key: SleepKey, answer: Answer, heardAtAsk: number, retry: () => void): void {
144
+ parked.set(nodeKey, { key, gen: answer.gen, sig: sigOf(answer), retry })
145
+ // another generation was heard while the ask was out (a push, another request's answer): once more, under the
146
+ // cadence (one re-ask per generation heard - never a loop)
147
+ if (heardOther(heardAtAsk, answer.gen)) release(nodeKey)
148
+ backstopSoon()
149
+ }
150
+ /** The backstop's period: 30 s (a test sets another through the dev hook below). */
151
+ let backstopMs = 30_000
152
+ let backstop: ReturnType<typeof setTimeout> | undefined, looking = false
153
+ function backstopSoon(): void {
154
+ if (backstop !== undefined || looking || !parked.size || PERF_RUN || PUBLISHED) return
155
+ backstop = setTimeout(() => { backstop = undefined; looking = true; void lookAgain().finally(() => { looking = false; backstopSoon() }) }, backstopMs)
156
+ }
157
+ /** The backstop: what would the server answer every parked node now? Over HTTP, no document touched. */
158
+ async function lookAgain(): Promise<void> {
159
+ // each key once in the whole look, whatever the chunk: the nodes parked on it ride with it
160
+ const byKey = new Map<string, { key: SleepKey; nodes: [string, Parked][] }>()
161
+ for (const [nodeKey, p] of parked) { const k = keyOf(p.key), e = byKey.get(k); if (e) e.nodes.push([nodeKey, p]); else byKey.set(k, { key: p.key, nodes: [[nodeKey, p]] }) }
162
+ const all = [...byKey.values()]
163
+ for (let i = 0; i < all.length; i += ASKS_MAX) {
164
+ // only nodes still parked on this very answer (a board switch during an earlier chunk sends nothing for them)
165
+ const chunk = all.slice(i, i + ASKS_MAX).map((e) => ({ key: e.key, nodes: e.nodes.filter(([nodeKey, p]) => parked.get(nodeKey) === p) })).filter((e) => e.nodes.length)
166
+ if (!chunk.length) continue
167
+ const part = chunk.flatMap((e) => e.nodes)
168
+ inflight++
169
+ try {
170
+ const data = await post(chunk.map((e) => e.key))
171
+ if (!data) continue // no answer (the server is away): nothing learned, the next look asks again
172
+ const gen = typeof data.gen === 'number' ? data.gen : undefined
173
+ if (gen !== undefined) heard(gen)
174
+ for (const [nodeKey, p] of part) {
175
+ if (parked.get(nodeKey) !== p) continue // woke, released or parked anew meanwhile
176
+ const a = toAnswer(data.answers?.find((x) => keyOf(x) === keyOf(p.key)), gen)
177
+ if (a.ok === false && a.error === 'no answer') continue
178
+ if (sigOf(a) !== p.sig) release(nodeKey)
179
+ }
180
+ } finally { inflight-- }
181
+ }
182
+ }
183
+ if (import.meta.hot) {
184
+ import.meta.hot.on('sh:bake-gen', (m: { gen?: unknown }) => pushed(typeof m?.gen === 'number' ? m.gen : undefined))
185
+ import.meta.hot.on('vite:ws:connect', () => heard(undefined))
186
+ }
187
+ // dev-only inspection hook for tests (never in a published build): what a node is parked on, and a push as the socket
188
+ // would deliver it
189
+ if (import.meta.env.DEV) (window as unknown as { __mvSleep: unknown }).__mvSleep = {
190
+ parkedOn: (k: string) => { const p = parked.get(k); return p ? { gen: p.gen, sig: p.sig } : null },
191
+ pushed,
192
+ bakeWork: () => bakeWork(),
193
+ backstopEvery: (ms: number) => { backstopMs = ms; clearTimeout(backstop); backstop = undefined; backstopSoon() },
194
+ }
93
195
 
94
196
  /** Does this document have anything to compile? Cheap: one computed style per element. */
95
197
  export function hasEffects(doc: Document): boolean {
@@ -108,39 +210,64 @@ const staticAnswers = () => (published ??= (BAKES ? fetch(`${ROUTE}/bakes/${BAKE
108
210
  .then((j: { gen?: number; answers?: Record<string, Answer> }) => (j.gen === BAKES && j.answers) || {}).catch((): Record<string, Answer> => ({})))
109
211
 
110
212
  // ---- one batch per tick: every frame that decides to sleep in the same moment shares a browser
111
- const queue: { key: SleepKey; resolve: (a: Answer) => void }[] = []
213
+ /** A waiter: the node asking, its answer, and whether it still wants one (its sleep's `current()`). */
214
+ interface Waiter { node: string; resolve: (a: Answer) => void; live: () => boolean }
215
+ const queue: { key: SleepKey; w: Waiter }[] = []
112
216
  let flush: ReturnType<typeof setTimeout> | undefined
113
- function ask(key: SleepKey): Promise<Answer> {
217
+ function ask(key: SleepKey, node: string, live: () => boolean): Promise<Answer> {
114
218
  return new Promise((resolve) => {
115
- queue.push({ key, resolve })
219
+ queue.push({ key, w: { node, resolve, live } })
116
220
  clearTimeout(flush)
117
221
  flush = setTimeout(async () => {
118
222
  const batch = queue.splice(0)
119
223
  // one ask per key; every waiter for that key gets the same answer
120
- const byKey = new Map<string, { key: SleepKey; waiters: ((a: Answer) => void)[] }>()
121
- for (const q of batch) { const kk = keyOf(q.key); const e = byKey.get(kk); if (e) e.waiters.push(q.resolve); else byKey.set(kk, { key: q.key, waiters: [q.resolve] }) }
122
- const asks = [...byKey.values()].map((e) => ({ frame: e.key.frame, theme: e.key.theme, w: Math.round(e.key.w), h: Math.round(e.key.h), ...(e.key.doc ? { doc: e.key.doc } : {}) }))
123
- let data: { answers?: (Answer & SleepKey)[] } | null = null
224
+ const byKey = new Map<string, { key: SleepKey; waiters: Waiter[] }>()
225
+ for (const q of batch) { const kk = keyOf(q.key); const e = byKey.get(kk); if (e) e.waiters.push(q.w); else byKey.set(kk, { key: q.key, waiters: [q.w] }) }
124
226
  inflight++
125
227
  try {
126
228
  const index = PUBLISHED ? await staticAnswers() : null
127
- if (!index) {
128
- try {
129
- const r = await api('bakes', { method: 'POST', headers: { 'content-type': 'application/json', 'x-mv-c': csrf() }, body: JSON.stringify({ asks }) })
130
- data = r.ok ? await r.json() : null
131
- } catch { data = null }
229
+ if (index) answerAll(byKey, index, null)
230
+ else {
231
+ // the server takes at most ASKS_MAX a request: a bigger batch (a generation releasing hundreds of parked
232
+ // frames at once) goes in several, sent together (none waits behind another's answer), each answering its own
233
+ // waiters - and as they go, a waiter that no longer wants its answer (woken, its board left) is answered
234
+ // "no answer" and a key with none left is not sent
235
+ const parts: Map<string, { key: SleepKey; waiters: Waiter[] }>[] = []
236
+ for (const e of byKey.values()) {
237
+ const live = e.waiters.filter((w) => w.live())
238
+ for (const w of e.waiters) if (!live.includes(w)) w.resolve({ ok: false, error: 'no answer' })
239
+ if (!live.length) continue
240
+ if (!parts.length || parts[parts.length - 1].size >= ASKS_MAX) parts.push(new Map())
241
+ parts[parts.length - 1].set(keyOf(e.key), { key: e.key, waiters: live })
242
+ }
243
+ const now = performance.now()
244
+ for (const part of parts) for (const e of part.values()) for (const w of e.waiters) lastAsk.set(w.node, now)
245
+ await Promise.all(parts.map(async (part) => answerAll(part, null, await post([...part.values()].map((e) => e.key)))))
132
246
  }
133
- answerAll(byKey, index, data)
134
247
  } finally { inflight-- }
135
248
  }, 40)
136
249
  })
137
250
  }
251
+ type Answers = { gen?: number; answers?: (Answer & SleepKey)[] }
252
+ /** The server's asks limit (api.ts: 1-200 a request). */
253
+ const ASKS_MAX = 200
254
+ /** One POST of the bake asks; null when there is no answer (a network failure, a refusal of the request). */
255
+ async function post(keys: SleepKey[]): Promise<Answers | null> {
256
+ const asks = keys.map((k) => ({ frame: k.frame, theme: k.theme, w: Math.round(k.w), h: Math.round(k.h), ...(k.doc ? { doc: k.doc } : {}) }))
257
+ try {
258
+ const r = await api('bakes', { method: 'POST', headers: { 'content-type': 'application/json', 'x-mv-c': csrf() }, body: JSON.stringify({ asks }) })
259
+ return r.ok ? await r.json() : null
260
+ } catch { return null }
261
+ }
262
+ const toAnswer = (a: (Answer & SleepKey) | Answer | undefined, gen: number | undefined): Answer =>
263
+ a ? (a.ok ? { ok: true, targets: a.targets, gen } : { ok: false, error: a.error, ...(a.kept === true ? { kept: true } : {}), gen }) : { ok: false, error: 'no answer' }
138
264
  /** Every waiter of a batch, its key's answer - before the POST stops counting, so the page is never idle between. */
139
- function answerAll(byKey: Map<string, { key: SleepKey; waiters: ((a: Answer) => void)[] }>, index: Record<string, Answer> | null, data: { answers?: (Answer & SleepKey)[] } | null): void {
265
+ function answerAll(byKey: Map<string, { key: SleepKey; waiters: Waiter[] }>, index: Record<string, Answer> | null, data: Answers | null): void {
266
+ const gen = typeof data?.gen === 'number' ? data.gen : undefined
267
+ if (gen !== undefined) heard(gen)
140
268
  for (const e of byKey.values()) {
141
- const a = index ? index[keyOf(e.key)] : data?.answers?.find((x) => keyOf(x) === keyOf(e.key))
142
- const answer: Answer = a ? (a.ok ? { ok: true, targets: a.targets } : { ok: false, error: a.error }) : { ok: false, error: 'no answer' }
143
- for (const w of e.waiters) w(answer)
269
+ const answer = toAnswer(index ? index[keyOf(e.key)] : data?.answers?.find((x) => keyOf(x) === keyOf(e.key)), gen)
270
+ for (const w of e.waiters) w.resolve(answer)
144
271
  }
145
272
  }
146
273
 
@@ -171,7 +298,8 @@ async function sleepNow(nodeKey: string, iframe: HTMLIFrameElement, key: SleepKe
171
298
  asleep.set(nodeKey, { key: k, doc })
172
299
  return 'asleep'
173
300
  }
174
- const answer = await ask(key)
301
+ const heardAtAsk = heardSeq
302
+ const answer = await ask(key, nodeKey, current)
175
303
  if (!current()) return 'live'
176
304
  // still compiling (issue #23): the server answered in seconds and carries on by itself. The frame
177
305
  // stays LIVE meanwhile - pausing now would freeze a finite animation midway, under a texture of its
@@ -189,17 +317,20 @@ async function sleepNow(nodeKey: string, iframe: HTMLIFrameElement, key: SleepKe
189
317
  // fails to decode (pruned, missing, corrupt) leaves the glass live
190
318
  const decoded = await Promise.all(targets.map((t) => { const im = new Image(); im.src = t.texture; return im.decode().then(() => true, () => false) }))
191
319
  if (!current()) return 'live'
192
- if (decoded.some((ok) => !ok)) targets = []
320
+ const undecoded = decoded.some((ok) => !ok)
321
+ if (undecoded) targets = []
193
322
  // a published document names the generation it was built with: textures dress that build only
194
323
  if (PUBLISHED && targets.length && doc.querySelector('meta[name="mv-bakes"]')?.getAttribute('content') !== String(BAKES)) targets = []
195
324
  if (!install(doc, targets)) return 'live'
196
325
  // a certified sleep is remembered; the pause-only fallback is not, so the next lifecycle event
197
- // asks again (a compile the source outran, a server hiccup), and a retry is scheduled now. A canvas retries
198
- // every 4 s while the frame rests: the retry clears its own mark, so a failure after a failure asks again and
199
- // the glass sleeps once the server recovers. A headless perf run's retry keeps its mark until the node wakes -
200
- // one retry, then nothing more, or a frame the compiler refuses would keep the run from ever being bake-idle
326
+ // asks again. A SETTLED answer (a kept refusal, a compile none of whose textures certified) parks the node
327
+ // until the source generation moves (`park`). Anything else - a compile the source outran, a server hiccup, a
328
+ // texture that did not decode - schedules a retry now. A canvas retries every 4 s while the frame rests: the
329
+ // retry clears its own mark, so a failure after a failure asks again and the glass sleeps once the server
330
+ // recovers. A headless perf run's retry keeps its mark until the node wakes - one retry, then nothing more
201
331
  if (targets.length) { asleep.set(nodeKey, { key: k, doc }); compiling.delete(nodeKey); retried.delete(nodeKey) }
202
332
  else if (answer.ok === false && answer.error === COMPILING) { /* out of looks: the pause alone, final */ }
333
+ else if (!PUBLISHED && !undecoded && (answer.ok || answer.kept)) park(nodeKey, key, answer, heardAtAsk, () => { if (current()) void sleep(nodeKey, iframe, key) }) // settled until the generation moves
203
334
  else if (!PUBLISHED && !retried.has(nodeKey)) { retried.add(nodeKey); scheduleSleep(() => { if (!PERF_RUN) retried.delete(nodeKey); if (current()) void sleep(nodeKey, iframe, key) }, RETRY_MS) } // a static miss is final
204
335
  return 'asleep'
205
336
  }
@@ -210,7 +341,10 @@ export function wake(nodeKey: string, iframe: HTMLIFrameElement | null): void {
210
341
  asleep.delete(nodeKey)
211
342
  compiling.delete(nodeKey)
212
343
  retried.delete(nodeKey)
344
+ parked.delete(nodeKey)
345
+ lastAsk.delete(nodeKey)
213
346
  const doc = iframe?.contentDocument
347
+ if (doc) resumeSmil(doc)
214
348
  const st = doc?.getElementById(STYLE_ID)
215
349
  if (!doc || !st) return
216
350
  const els = [...doc.querySelectorAll<HTMLElement>('[data-mv-sleep]')]
@@ -254,5 +388,103 @@ function install(doc: Document, targets: Target[]): boolean {
254
388
  // one paint, and no authored transition (`transition: all` is common on a pill) may animate the
255
389
  // effect out or the texture in
256
390
  still(doc, els, () => { els.forEach((el, i) => el.setAttribute('data-mv-sleep', String(i))); style.textContent = rules.join('\n') })
391
+ pauseSmil(doc)
257
392
  return true
258
393
  }
394
+
395
+ /** The SVG time containers this sleep holds, per sleeping document. */
396
+ const smilHeld = new WeakMap<Document, Set<SVGSVGElement>>()
397
+ const SMIL = 'animate,animateTransform,animateMotion,set'
398
+ const SVG_NS = 'http://www.w3.org/2000/svg'
399
+ const SHADOWED = ['pauseAnimations', 'unpauseAnimations', 'animationsPaused'] as const
400
+ /** The native timeline methods, taken once from the shell's own realm: a platform method works on an element of any
401
+ * realm, so a hold is undone whatever document the element is in by then, with or without a window. */
402
+ const NATIVE = typeof SVGSVGElement === 'function'
403
+ ? { pause: SVGSVGElement.prototype.pauseAnimations, unpause: SVGSVGElement.prototype.unpauseAnimations, paused: SVGSVGElement.prototype.animationsPaused }
404
+ : null
405
+ /** A held <svg>: what its author last asked for, and the own properties it had under our shadows (restored at wake). */
406
+ interface Hold { paused: boolean; saved: (readonly [string, PropertyDescriptor | undefined])[] }
407
+ const holds = new WeakMap<SVGSVGElement, Hold>()
408
+ /** The shadows, one of each for every held <svg>: they honour `this` - a call on an element not held (another <svg>,
409
+ * or this one after its wake) goes to the native method. */
410
+ const SHADOWS: Record<(typeof SHADOWED)[number], (this: SVGSVGElement) => unknown> = {
411
+ pauseAnimations() { const h = holds.get(this); if (h) h.paused = true; else NATIVE!.pause.call(this) },
412
+ unpauseAnimations() { const h = holds.get(this); if (h) h.paused = false; else NATIVE!.unpause.call(this) },
413
+ animationsPaused() { const h = holds.get(this); return h ? h.paused : NATIVE!.paused.call(this) },
414
+ }
415
+ /**
416
+ * SVG's own animations (SMIL: `<animate>`, `<animateTransform>`, ...) are no CSS animation: `animation-play-state` never
417
+ * reaches them, and one running in any document - a rotating gradient - repaints and commits the WHOLE page every
418
+ * frame. They pause with the CSS ones, by their time container (the outermost <svg>; every <svg> on the way is held
419
+ * too, whichever one an engine keys the timeline on). While asleep the timeline holds still whatever the author calls
420
+ * - as the CSS pause is !important: on each held <svg>, own `pauseAnimations`/`unpauseAnimations` only record what
421
+ * they ask, and `animationsPaused()` answers it (their code sees the state it asked for, as if awake). Wake restores
422
+ * the element's own properties as they were and runs the timeline only if the author's last word is "running" -
423
+ * paused before the sleep and never unpaused, or paused during it, it stays paused. A paused timeline resumes where it
424
+ * stood: nothing jumps, a finished animation does not restart.
425
+ *
426
+ * A hold is all or nothing: an <svg> whose own properties cannot be shadowed (an authored non-configurable one, a
427
+ * non-extensible element) is left unheld - it animates on, as before sleep paused SMIL at all - and sleep never fails
428
+ * for an SVG. Idempotent: a sleep installed again holds nothing twice.
429
+ *
430
+ * Accepted, not handled - each needs code written against the sleep itself; content that drives its SVG the ordinary
431
+ * way (declarative SMIL, or direct method calls on the element) behaves as without sleep:
432
+ * - code that captured the native method before the sleep (a bound `svg.pauseAnimations`, or
433
+ * `SVGSVGElement.prototype.pauseAnimations.call(svg)`) bypasses the record: its pause during a sleep is undone at wake;
434
+ * - an <svg> on which the author installed their OWN pauseAnimations/unpauseAnimations/animationsPaused (a wrapper or
435
+ * accessor with side effects - a player updating its controls): while the frame sleeps a call records the intent
436
+ * but does not run the author's wrapper; the wrapper is back at wake;
437
+ * - an <svg> adopted into another document while its own frame sleeps stays held until that frame wakes - and after
438
+ * the frame's document is replaced, wake() works on the new document and does not resume a hold left on the old
439
+ * one (the old document is gone from the frame);
440
+ * - Gecko's nested <svg> query differs while held: an inner svg's `animationsPaused()` answers its own recorded
441
+ * intent, not its outer container's;
442
+ * - an <svg> mounted after the frame fell asleep is not held (it animates).
443
+ */
444
+ function hold(s: SVGSVGElement): boolean {
445
+ const saved = SHADOWED.map((k) => [k, Object.getOwnPropertyDescriptor(s, k)] as const)
446
+ if (saved.some(([, d]) => d && !d.configurable)) return false
447
+ const h: Hold = { paused: NATIVE!.paused.call(s), saved }
448
+ holds.set(s, h)
449
+ try {
450
+ for (const k of SHADOWED) Object.defineProperty(s, k, { configurable: true, writable: true, value: SHADOWS[k] })
451
+ } catch {
452
+ holds.delete(s)
453
+ unshadow(s, h)
454
+ return false
455
+ }
456
+ if (!h.paused) NATIVE!.pause.call(s) // last: nothing above can leave it paused unrecorded
457
+ return true
458
+ }
459
+ /** The element's own properties back as they were before the hold. */
460
+ function unshadow(s: SVGSVGElement, h: Hold): void {
461
+ for (const [k, d] of h.saved) {
462
+ try { if (d) Object.defineProperty(s, k, d); else delete (s as unknown as Record<string, unknown>)[k] } catch { /* as it is */ }
463
+ }
464
+ }
465
+ function pauseSmil(doc: Document): void {
466
+ if (!NATIVE) return
467
+ const anims = doc.querySelectorAll(SMIL)
468
+ if (!anims.length) return
469
+ let held = smilHeld.get(doc)
470
+ for (const a of anims) {
471
+ if (a.namespaceURI !== SVG_NS) continue
472
+ for (let s = (a as SVGElement).ownerSVGElement; s; s = s.ownerSVGElement) {
473
+ if (holds.has(s) || !hold(s)) continue
474
+ if (!held) smilHeld.set(doc, held = new Set())
475
+ held.add(s)
476
+ }
477
+ }
478
+ }
479
+ function resumeSmil(doc: Document): void {
480
+ const held = smilHeld.get(doc)
481
+ if (!held || !NATIVE) return
482
+ smilHeld.delete(doc)
483
+ for (const s of held) {
484
+ const h = holds.get(s)
485
+ if (!h) continue
486
+ holds.delete(s)
487
+ unshadow(s, h)
488
+ if (!h.paused) NATIVE.unpause.call(s)
489
+ }
490
+ }
@@ -113,12 +113,36 @@ export function buildHash(s: HashState): string {
113
113
  return `#/b/${s.board}${q ? `?${decodeURIComponent(q)}` : ''}`
114
114
  }
115
115
 
116
+ /** The hashes popstates routed whose hashchange is still to come: a navigation that changes the hash fires popstate
117
+ * (synchronously under `location.hash =`, in its own task for back/forward) and queues a hashchange - other tasks,
118
+ * and the next navigation's popstate, can run before it. `seen`: the hash as the router or the projection left it.
119
+ * Never cut by count - a mark dropped while its hashchange can still come would route that navigation again over
120
+ * the newer ones (nine `location.hash =` in one task: nine popstates, then nine hashchanges): each mark goes when its
121
+ * own hashchange comes, with any older one before it, so the list holds the navigations still owed a hashchange. */
122
+ const owed: string[] = []
123
+ let seen = typeof location === 'undefined' ? '' : location.hash
124
+ /** The hash a history event asks the router to apply - or null: the hashchange of a navigation its popstate already
125
+ * routed, the same navigation, never routed again (whatever came since - a goto, a click, the next link - is newer;
126
+ * and by then location.hash may hold the projection, written by a store update rendered in between). A hashchange
127
+ * with no popstate before it is routed from the URL it carries; a synthetic one carrying none, from location.hash. */
128
+ export function routedHash(e: Event): string | null {
129
+ if (e.type === 'popstate') {
130
+ if (location.hash !== seen) owed.push(location.hash) // a same-hash entry has no hashchange to come
131
+ return seen = location.hash
132
+ }
133
+ const h = e instanceof HashChangeEvent && e.newURL ? new URL(e.newURL).hash : null
134
+ const i = h === null ? -1 : owed.indexOf(h)
135
+ if (i >= 0) { owed.splice(0, i + 1); return null }
136
+ return seen = h ?? location.hash
137
+ }
138
+
116
139
  /** Write the hash; identical URLs are skipped so restore paths never loop. */
117
140
  export function writeHash(s: HashState, push = false) {
118
141
  const h = buildHash(s)
119
142
  if (h === location.hash || (h === '#/' && !location.hash)) return
120
143
  if (push) history.pushState(null, '', h)
121
144
  else history.replaceState(null, '', h)
145
+ seen = h
122
146
  }
123
147
 
124
148
  /** The hash as it stood when the app loaded - boot intent, captured once; re-aimed only when an old
@@ -16,7 +16,7 @@
16
16
  import { onScreen, usable } from './inset.ts'
17
17
  import { create } from 'zustand'
18
18
  import { slideSize } from '../const.ts'
19
- import { CONFIG, SLIDE_INTRINSIC, stoppedFor, useStore, type Node } from './store.ts'
19
+ import { CONFIG, SLIDE_INTRINSIC, geometryCause, stoppedFor, useStore, type Node } from './store.ts'
20
20
  import { UNPLACED } from './hash.ts'
21
21
  import type { Bundle, CaptureRecord, Step, View } from '../../server/jam/types.ts'
22
22
  import { forgetHeard, RATE, setWordsListener, voiceBegin, voiceDrop, voiceEnd } from './jam-voice.ts'
@@ -292,7 +292,8 @@ function watchUi() {
292
292
  if (s.selection.join() !== p.selection.join() && s.selection.length) {
293
293
  addStep(id, { at, event: 'select', frames: [...new Set(s.selection.map((k) => frameIdOf(k)).filter((f): f is string => !!f))] }, s.selection, performance.now() - playLeftAt < 200)
294
294
  }
295
- for (const n of s.nodes) {
295
+ // what a person did to a node, never what the manifest did (a frame file's theme edited mid-capture is no step)
296
+ if (geometryCause() !== 'manifest') for (const n of s.nodes) {
296
297
  const o = p.nodes.find((x) => x.key === n.key)
297
298
  if (!o) continue
298
299
  // a device change: the node took a preset's size (its width names the viewport)