@marver-design/marver 0.26.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/CHANGELOG.md +158 -0
  2. package/README.md +10 -5
  3. package/dist/{anchor-check-Dg5xpNnU.mjs → anchor-check-ChdDqL5z.mjs} +1 -1
  4. package/dist/{audio-CmSRYFEs.mjs → audio-Dw1lfMdb.mjs} +14 -0
  5. package/dist/{bake-DtVlm0_F.mjs → bake-DM_uWgAA.mjs} +1 -1
  6. package/dist/{boards-DYG22tOe.mjs → boards-DlTcpF47.mjs} +1 -1
  7. package/dist/{build-C_gUgcdC.mjs → build-DZnFysGU.mjs} +4 -4
  8. package/dist/{capture-CrqvU_jh.mjs → capture-vadKjuCo.mjs} +2 -1
  9. package/dist/cli.mjs +28 -16
  10. package/dist/{comments-BqXua-XL.mjs → comments-DxOkCSNE.mjs} +4 -4
  11. package/dist/{daemon-DZo6o3rU.mjs → daemon-BSA0lV8d.mjs} +400 -274
  12. package/dist/detect-C0wpaePX.mjs +125 -0
  13. package/dist/dev-eQJhWsqg.mjs +1273 -0
  14. package/dist/dev-lock-C_FC70Mu.mjs +65 -0
  15. package/dist/exclusive-B1RtpeeP.mjs +150 -0
  16. package/dist/{init-D8DtrK_F.mjs → init-COD0x48i.mjs} +5 -3
  17. package/dist/{link-BNzLvdhI.mjs → link-DDXZVGtv.mjs} +20 -8
  18. package/dist/ls-D7O1G505.mjs +38 -0
  19. package/dist/{marks-NQi0wZJ4.mjs → marks-CWM3WJjc.mjs} +1 -1
  20. package/dist/perf-BWzQwZqj.mjs +369 -0
  21. package/dist/perf-BoDSkbEb.mjs +429 -0
  22. package/dist/perf-jam-D55U3FZK.mjs +242 -0
  23. package/dist/{plugin-CTD0rydA.mjs → plugin-C-E7omsh.mjs} +425 -66
  24. package/dist/{poster-ChjXGTS5.mjs → poster-Bx83ZYVK.mjs} +2 -1
  25. package/dist/{profile-WU9qcbIo.mjs → profile-Bh5Y5zpW.mjs} +1 -1
  26. package/dist/{publish-bakes-CEP_2NRc.mjs → publish-bakes-aljgm45S.mjs} +2 -2
  27. package/dist/{queue-BuiCKSX1.mjs → queue-CAM_vNmX.mjs} +3 -3
  28. package/dist/recover-t9Pno3u9.mjs +66 -0
  29. package/dist/{session-qZWKt_VA.mjs → session-BAaJsK5c.mjs} +1 -1
  30. package/dist/{share--oFJ1bCI.mjs → share-W5H3BNvP.mjs} +1 -1
  31. package/dist/shot-DoHLl6ig.mjs +139 -0
  32. package/dist/{shot-DqcxJibP.mjs → shot-LFhC-WYD.mjs} +343 -19
  33. package/dist/slots-DCDo3N0x.mjs +471 -0
  34. package/dist/speech-worker.mjs +40 -5
  35. package/dist/{sync-DKk-yT1V.mjs → sync-BQVlHZpx.mjs} +4 -3
  36. package/dist/{work-F5u-twpJ.mjs → work-Bp1p39kq.mjs} +4 -2
  37. package/dist/{work-VvX_JIgl.mjs → work-BroFwnup.mjs} +4 -2
  38. package/docs/boards-and-folders.md +3 -1
  39. package/docs/jam-session.md +78 -7
  40. package/docs/live-jam.md +8 -0
  41. package/docs/performance.md +262 -0
  42. package/package.json +2 -2
  43. package/src/client/content/index.tsx +3 -0
  44. package/src/client/content/video.tsx +6 -2
  45. package/src/client/frame-host/bridge.js +22 -6
  46. package/src/client/frame-host/inspect.js +8 -3
  47. package/src/client/frame-host/keys.js +6 -2
  48. package/src/client/frame-host/main.tsx +17 -5
  49. package/src/client/shell/App.tsx +188 -29
  50. package/src/client/shell/BoardList.tsx +5 -5
  51. package/src/client/shell/Comments.tsx +3 -2
  52. package/src/client/shell/JamSurface.tsx +13 -5
  53. package/src/client/shell/LockedApp.tsx +5 -5
  54. package/src/client/shell/Play.tsx +27 -15
  55. package/src/client/shell/Toolbar.tsx +17 -5
  56. package/src/client/shell/api.ts +206 -0
  57. package/src/client/shell/canvas/Canvas.tsx +30 -3
  58. package/src/client/shell/canvas/FrameNode.tsx +15 -5
  59. package/src/client/shell/canvas/admission.ts +8 -1
  60. package/src/client/shell/canvas/camera-broadcast.ts +15 -5
  61. package/src/client/shell/canvas/ctl.ts +2 -0
  62. package/src/client/shell/canvas/frame-registry.ts +28 -2
  63. package/src/client/shell/canvas/sleep.ts +4 -1
  64. package/src/client/shell/comments-store.ts +12 -4
  65. package/src/client/shell/goto.ts +22 -10
  66. package/src/client/shell/icons.tsx +2 -0
  67. package/src/client/shell/jam-capture.ts +96 -16
  68. package/src/client/shell/jam-keys.ts +51 -18
  69. package/src/client/shell/jam-lane.tsx +46 -5
  70. package/src/client/shell/jam-panel.tsx +66 -13
  71. package/src/client/shell/jam-queue.ts +3 -3
  72. package/src/client/shell/jam-session.tsx +14 -8
  73. package/src/client/shell/jam-state.ts +48 -6
  74. package/src/client/shell/jam-surface-parts.tsx +10 -6
  75. package/src/client/shell/jam-voice.ts +7 -5
  76. package/src/client/shell/legacy-links.ts +2 -2
  77. package/src/client/shell/main.tsx +4 -0
  78. package/src/client/shell/notes.ts +8 -1
  79. package/src/client/shell/perf.ts +69 -58
  80. package/src/client/shell/recorder-core.ts +183 -0
  81. package/src/client/shell/recorder.ts +565 -0
  82. package/src/client/shell/store.ts +268 -103
  83. package/src/client/shell/styles.css +54 -9
  84. package/src/client/stage/main.tsx +2 -0
  85. package/templates/AGENTS-embedded.md +22 -4
  86. package/templates/AGENTS-studio.md +22 -4
  87. package/templates/demo/dark.tsx +1 -1
  88. package/templates/demo/welcome.tsx +1 -1
  89. package/templates/instructions/jam.md +5 -3
  90. package/templates/instructions/welcome.md +6 -3
  91. package/dist/config-Cf7EjAMf.mjs +0 -292
  92. package/dist/dev-_Nlsc6v9.mjs +0 -742
  93. package/dist/dev-lock-DWSpa6nj.mjs +0 -179
  94. package/dist/perf-D6VmmJ2q.mjs +0 -68
  95. package/dist/perf-DPbLGhhO.mjs +0 -49
  96. package/dist/shot-CNbHoZ6H.mjs +0 -86
@@ -0,0 +1,565 @@
1
+ /**
2
+ * The recorder's page half (spec 28 A1.7): what each board load did, from the page - when it was asked for and
3
+ * committed, when each frame reached its outcome, every move of a node and why, the first quiet second and settled -
4
+ * plus gestures and errors. Records go to the dev server (POST /__mv/api/perf/page) and land in
5
+ * design/.local/perf/page.jsonl; `npx marver perf --loads` reads them back.
6
+ *
7
+ * Dev only - off on a published canvas - and nothing at rest: no timer or frame of its own while no load is in flight
8
+ * and nothing waits to be sent. The store tells it about loads and moves through its hooks (store.ts recorderHooks,
9
+ * withCause); a frame's outcome counts only from the document its iframe shows now (`__mvBoot`, set by the frame
10
+ * bridge). It reaches the canvas only through its dependency-free modules (ctl, admission, the frame registry), never
11
+ * Canvas.tsx or FrameNode.tsx: a locked bundle (no canvas) imports it through the stage.
12
+ */
13
+ import { api, isStopped } from './api.ts'
14
+ import { CONFIG, PUBLISHED, geometryCause, knownHeight, recorderHooks, reflowIdle, settleRule, useStore, type LoadCause, type Manifest, type MeasureResult, type Node, type RequestCut } from './store.ts'
15
+ import { admissionIdle, onAdmissionIdle } from './canvas/admission.ts'
16
+ import { canvasCtl } from './canvas/ctl.ts'
17
+ import { bootOf, iframeOf } from './canvas/frame-registry.ts'
18
+ import { adopt, bound, fitWithin, KEEPALIVE_BYTES, LOAD_MAX_MS, newId, Outbox, outcomeOf, QUIET_MS, SEND_MS, stackLines, type Kind, type Outcome, type PerfRecord, type Track } from './recorder-core.ts'
19
+
20
+ /** This document, in every record (and, in the app, in its hello: the app's records about this tab carry it). */
21
+ export const PAGE_ID = newId()
22
+
23
+ type State = ReturnType<typeof useStore.getState>
24
+ type View = { x: number; y: number; w: number; h: number }
25
+ type Gesture = { type: 'pan' | 'zoom' | 'layout'; ms: number; frames: number; p50: number; p95: number; max: number; over17ms: number; over33ms: number; longFrames: number }
26
+
27
+ interface Load {
28
+ id: string; board: string; cause: LoadCause; t0: number
29
+ committedAt?: number
30
+ /** the last move of this load (the commit counts as one): quiet is a second after it */
31
+ lastMoveAt: number
32
+ /** the last move itself, never the commit - none while nothing moved: the settled or cut record's `lastMove` */
33
+ movedAt?: number
34
+ quietSent: boolean
35
+ /** the visible cohort: the nodes the first camera placement after the commit showed */
36
+ cohort?: Set<string>
37
+ /** store changes that moved a node (before drags are merged), their distance, by cause */
38
+ moves: number; distance: number; causes: Record<string, number>
39
+ errors: number; errAt: Map<string, number>
40
+ /** node key -> `${outcome}:${boot}` its last frame record said */
41
+ reported: Map<string, string>
42
+ done?: 'settled' | 'cut'
43
+ quietTimer?: ReturnType<typeof setTimeout>; timeout?: ReturnType<typeof setTimeout>; retry?: ReturnType<typeof setTimeout>
44
+ }
45
+
46
+ let on = false
47
+ let ws = ''
48
+ let seq = 0
49
+ let capturesPending = (): boolean => false
50
+ let sealCaptures = (): void => {}
51
+ /** requested, not committed (or cut) yet */
52
+ const pending = new Map<string, Load>()
53
+ /** requests cut before they committed that may mount all the same (their deadline passed, the page hid or went): a
54
+ * few, newest last - one that mounts says so (a `commit`, `late`, its cut kept) and owns the geometry from then, its
55
+ * moves late */
56
+ const lapsed = new Map<string, Load>()
57
+ /** the load that owns the geometry: the last one committed */
58
+ let owner: Load | null = null
59
+ /** node key -> what its live document said (page-level: a reload of the same board keeps its documents) */
60
+ const tracks = new Map<string, Track>()
61
+ /** each node's geometry as last seen - numbers, not the node objects (applyManifest edits nodes in place) */
62
+ let baseline = new Map<string, { x: number; y: number; w: number; h: number }>()
63
+ const outbox = new Outbox()
64
+ /** a drag's or a resize's move record per node while it waits to be sent: the next pointermove adds to it */
65
+ const open = new Map<string, PerfRecord>()
66
+ let inFlight: PerfRecord[] = []
67
+ let sendTimer: ReturnType<typeof setTimeout> | undefined
68
+ let sending = false
69
+ /** what only the canvas knows (Canvas.tsx attaches it): is a pan, zoom or layout animation running; frames asleep */
70
+ let motion = { camera: false, preset: false }
71
+ let sleeping = (): number => 0
72
+ /** errors before any load committed, and their last time by kind (as a load's) */
73
+ const unowned = { errors: 0, errAt: new Map<string, number>() }
74
+
75
+ const env = (kind: Kind, load: string, body: Record<string, unknown>): PerfRecord =>
76
+ ({ ...Object.fromEntries(Object.entries(body).filter(([, x]) => x !== undefined)), v: 1, ws, page: PAGE_ID, load, seq: seq++, ts: Date.now(), kind })
77
+ function rec(kind: Kind, load: string, body: Record<string, unknown>): PerfRecord {
78
+ if (kind !== 'move') open.clear() // a merged drag ends at the next record of another kind
79
+ const r = env(kind, load, body)
80
+ outbox.push(r)
81
+ armSend()
82
+ return r
83
+ }
84
+ const ownerId = () => owner?.id ?? '-'
85
+ /** ms from the load's request; undefined for a moment before it (a document kept from an earlier load) */
86
+ const rel = (L: Load, at?: number) => (at === undefined || at < L.t0 ? undefined : Math.round(at - L.t0))
87
+ const node = (key: string) => useStore.getState().nodes.find((n) => n.key === key)
88
+ /** The document a node's iframe shows now, by the id its bridge set - absent while a new document has not run its
89
+ * bridge yet, or when the frame was navigated off this origin (the read throws). */
90
+ const liveBoot = (key: string): string | undefined => bootOf(iframeOf(key))
91
+ /** the URL revision the node's iframe was given */
92
+ const genOf = (key: string) => iframeOf(key)?.src.match(/[?&]r=(\d+)/)?.[1]
93
+ function trackOf(n: Node): Track {
94
+ let t = tracks.get(n.key)
95
+ if (!t || t.frame !== n.frame) { t = { frame: n.frame }; tracks.set(n.key, t) }
96
+ return t
97
+ }
98
+ const cameraMoving = () => motion.camera || motion.preset || canvasCtl.cameraBusy() || useStore.getState().gesture
99
+ /** Every method: off - nothing; and the recorder never stands in the way of the canvas. */
100
+ const guard = <A extends unknown[]>(fn: (...a: A) => void) => (...a: A): void => { if (!on) return; try { fn(...a) } catch { /* never in the way */ } }
101
+
102
+ /** Start recording, once, before the first board loads (shell/main.tsx). A published canvas: nothing at all. */
103
+ export function startRecorder(opts: { capturesPending: () => boolean; sealCaptures: () => void }): void {
104
+ const w = window as { __mvRecorderOn?: boolean }
105
+ if (on || PUBLISHED || !CONFIG.workspace || w.__mvRecorderOn) return // a hot-replaced module never records twice
106
+ w.__mvRecorderOn = true
107
+ on = true
108
+ ws = CONFIG.workspace
109
+ capturesPending = opts.capturesPending
110
+ sealCaptures = opts.sealCaptures
111
+ recorderHooks.request = (board, cause) => { try { return request(board, cause) } catch { return '' } }
112
+ recorderHooks.handover = guard(handover)
113
+ recorderHooks.commit = guard(commit)
114
+ recorderHooks.cut = guard(cutRequest)
115
+ recorderHooks.reflowIdle = settleSoon
116
+ onAdmissionIdle(settleSoon)
117
+ useStore.subscribe(guard(onNodes))
118
+ // the error's own message (not the event's "Uncaught …"), so a render error the boundary also reports is one error
119
+ addEventListener('error', (e) => { if (e instanceof ErrorEvent) recorder.error({ source: 'shell', message: (e.error instanceof Error && e.error.message) || e.message || String(e.error), stack: (e.error as Error | undefined)?.stack }) })
120
+ addEventListener('unhandledrejection', (e) => recorder.error({ source: 'shell', message: `unhandled rejection: ${(e.reason as Error | undefined)?.message ?? String(e.reason)}`, stack: (e.reason as Error | undefined)?.stack }))
121
+ document.addEventListener('visibilitychange', guard(() => {
122
+ if (document.visibilityState !== 'hidden') return
123
+ if (owner && !owner.done) cut(owner, 'hidden')
124
+ cutPending('hidden')
125
+ if (!capturesPending()) void send() // a capture still to send has the way out first
126
+ }))
127
+ addEventListener('pagehide', guard(leave))
128
+ if (import.meta.env.DEV) (window as unknown as { __mvRecorder: unknown }).__mvRecorder = { page: PAGE_ID, ws, state, send }
129
+ }
130
+
131
+ /** What only the canvas knows, from Canvas.tsx when it mounts: when the camera or a layout animation starts and stops
132
+ * (camera-broadcast.ts's observer), and how many frames sleep. Returns the detach. */
133
+ export function attachCanvas(c: { onMotion: (fn: (m: { camera: boolean; preset: boolean }) => void) => () => void; sleeping: () => number }): () => void {
134
+ sleeping = c.sleeping
135
+ const off = c.onMotion((m) => { motion = { camera: m.camera, preset: m.preset }; if (on && !m.camera && !m.preset) settleSoon() })
136
+ return () => { off(); sleeping = () => 0; motion = { camera: false, preset: false } }
137
+ }
138
+
139
+ // ---- loads ------------------------------------------------------------------------------------------------------
140
+
141
+ function request(board: string, cause: LoadCause): string {
142
+ if (!on) return ''
143
+ const t0 = performance.now()
144
+ const L: Load = { id: newId(), board, cause, t0, lastMoveAt: t0, quietSent: false, moves: 0, distance: 0, causes: {}, errors: 0, errAt: new Map(), reported: new Map() }
145
+ pending.set(L.id, L)
146
+ // `load`, its uncommitted `cut` and its `commit` carry the request's own id (the load's, once it commits)
147
+ rec('load', L.id, { board, cause, request: L.id, ...(cause === 'boot' ? { sinceNav: Math.round(t0) } : {}) })
148
+ // the deadline runs from the request: a load not settled 120 s after it was asked for is cut, committed or not - a
149
+ // board fetch that never answers included
150
+ L.timeout = setTimeout(guard(() => expire(L)), LOAD_MAX_MS)
151
+ return L.id
152
+ }
153
+
154
+ function expire(L: Load): void {
155
+ L.timeout = undefined
156
+ if (pending.has(L.id)) cutRequest(L.id, 'timeout')
157
+ else if (L === owner && !L.done) cut(L, 'timeout')
158
+ }
159
+
160
+ /** A request ends before it commits: superseded, failed, edited or unsaved (the store says), or its deadline passed,
161
+ * the page hid or went (the recorder knows). */
162
+ function cutRequest(id: string, reason: RequestCut | 'timeout' | 'hidden'): void {
163
+ const L = pending.get(id)
164
+ if (!L) return
165
+ pending.delete(id)
166
+ clearTimeout(L.timeout)
167
+ L.timeout = undefined
168
+ L.done = 'cut'
169
+ rec('cut', id, { reason, request: id, ms: Math.round(performance.now() - L.t0) })
170
+ // its fetch may still answer and mount it
171
+ if (reason === 'timeout' || reason === 'hidden') {
172
+ lapsed.set(id, L)
173
+ if (lapsed.size > 8) lapsed.delete(lapsed.keys().next().value!)
174
+ }
175
+ }
176
+ /** Every request still waiting, cut: the page hid or went. */
177
+ const cutPending = (reason: 'hidden') => { for (const id of [...pending.keys()]) cutRequest(id, reason) }
178
+
179
+ /** A request is about to commit: the load that was up ends here, its board's nodes still in the store - and before the
180
+ * incoming load's sizes are installed, so by its own: a Doc it waits on to settle stays one that measures, even when
181
+ * the incoming load read that it no longer does. */
182
+ function handover(id: string): void {
183
+ const L = pending.get(id) ?? lapsed.get(id)
184
+ if (L && owner && owner !== L && !owner.done) cut(owner, owner.board === L.board ? 'reload' : 'switch')
185
+ }
186
+
187
+ function commit(id: string, nodes: readonly Node[], manifest: Manifest): void {
188
+ const L = pending.get(id) ?? lapsed.get(id)
189
+ if (!L) return
190
+ const late = !pending.has(id)
191
+ handover(id) // ended already, at the handover (store.ts) - the incoming sizes are installed by now
192
+ pending.delete(id)
193
+ lapsed.delete(id)
194
+ owner = L
195
+ L.committedAt = L.lastMoveAt = performance.now()
196
+ // mounting is never a move: the baseline is the nodes about to mount
197
+ baseline = new Map(nodes.map((n) => [n.key, { x: n.x, y: n.y, w: n.w, h: n.h }]))
198
+ const keys = new Set(nodes.map((n) => n.key))
199
+ for (const k of [...tracks.keys()]) if (!keys.has(k)) tracks.delete(k)
200
+ // a request already cut (its deadline passed, the page hid) mounts all the same: said, its cut kept - its board's
201
+ // geometry is its own from here, every move late
202
+ rec('commit', id, { request: id, ms: Math.round(L.committedAt - L.t0), ...facts(nodes, manifest), ...(late ? { late: true } : {}) })
203
+ if (late) return
204
+ L.quietTimer = setTimeout(guard(() => quiet(L)), QUIET_MS)
205
+ // a page hidden already: cut once the set that mounts this load has run - its nodes, not the board it replaces
206
+ if (document.visibilityState === 'hidden') queueMicrotask(guard(() => { if (L === owner) cut(L, 'hidden') }))
207
+ }
208
+
209
+ /** What a load mounts: its frames by kind (Marver has no image frame kind), how many measure, and how many of those
210
+ * open at a height already known. */
211
+ function facts(nodes: readonly Node[], m: Manifest) {
212
+ const byKind = { hifi: 0, content: 0, html: 0 }
213
+ let measuring = 0, savedHeights = 0
214
+ for (const n of nodes) {
215
+ const f = n.missing ? undefined : m.frames.find((x) => x.id === n.frame)
216
+ if (!f) continue
217
+ if (f.kind === 'html') byKind.html++
218
+ else if (f.contentWidth) byKind.content++
219
+ else byKind.hifi++
220
+ if (settleRule(n, m) === 'measure') { measuring++; if (knownHeight(f.id, n.w)) savedHeights++ }
221
+ }
222
+ return { frames: nodes.length, byKind, measuring, savedHeights }
223
+ }
224
+
225
+ // ---- moves ------------------------------------------------------------------------------------------------------
226
+
227
+ /** The store changed: one reference check, and only when the nodes changed, their numbers against the baseline. A
228
+ * node new to it joins (a manifest's newcomer, a spawn) - never a move; one gone leaves. */
229
+ function onNodes(s: State, prev: State): void {
230
+ if (s.nodes === prev.nodes) return
231
+ const L = owner
232
+ if (!L) return
233
+ const cause = geometryCause() ?? 'unknown'
234
+ for (const n of s.nodes) {
235
+ const b = baseline.get(n.key)
236
+ if (!b) { baseline.set(n.key, { x: n.x, y: n.y, w: n.w, h: n.h }); continue }
237
+ const dx = n.x - b.x, dy = n.y - b.y, dw = n.w - b.w, dh = n.h - b.h
238
+ if (Math.abs(dx) < 0.5 && Math.abs(dy) < 0.5 && Math.abs(dw) < 0.5 && Math.abs(dh) < 0.5) continue
239
+ b.x = n.x; b.y = n.y; b.w = n.w; b.h = n.h
240
+ move(L, n.key, dx, dy, dw, dh, cause)
241
+ }
242
+ if (baseline.size > s.nodes.length + 32) { const keys = new Set(s.nodes.map((n) => n.key)); for (const k of [...baseline.keys()]) if (!keys.has(k)) baseline.delete(k) }
243
+ // a node gone, or now missing, may be what the load waited for
244
+ if (!L.done) settleSoon()
245
+ }
246
+
247
+ function move(L: Load, key: string, dx: number, dy: number, dw: number, dh: number, cause: string): void {
248
+ const late = !!L.done
249
+ if (!late) {
250
+ L.moves++
251
+ L.distance += Math.hypot(dx, dy) + Math.abs(dw) + Math.abs(dh)
252
+ L.causes[cause] = (L.causes[cause] ?? 0) + 1
253
+ L.lastMoveAt = L.movedAt = performance.now()
254
+ clearTimeout(L.quietTimer)
255
+ L.quietTimer = setTimeout(guard(() => quiet(L)), QUIET_MS)
256
+ }
257
+ // a drag is one store change per pointermove: while its record waits to be sent, the next one adds to it
258
+ const merges = cause === 'drag' || cause === 'resize'
259
+ const m = merges ? open.get(key) : undefined
260
+ if (m && m.cause === cause && m.load === L.id && outbox.has(m)) {
261
+ m.dx = Math.round((m.dx as number) + dx); m.dy = Math.round((m.dy as number) + dy)
262
+ m.dw = Math.round((m.dw as number) + dw); m.dh = Math.round((m.dh as number) + dh)
263
+ outbox.touch(m)
264
+ return
265
+ }
266
+ const r = rec('move', L.id, { node: key, dx: Math.round(dx), dy: Math.round(dy), dw: Math.round(dw), dh: Math.round(dh), cause, ...(late ? { late: true } : {}) })
267
+ if (merges) open.set(key, r)
268
+ }
269
+
270
+ // ---- outcomes, quiet, settled, cut ----------------------------------------------------------------------------
271
+
272
+ function outcomeNow(n: Node, m: Manifest | null): Outcome | null {
273
+ const rule = settleRule(n, m)
274
+ const t = tracks.get(n.key)
275
+ return outcomeOf(rule, t?.frame === n.frame ? t : undefined, rule === 'missing' ? undefined : liveBoot(n.key), { w: n.w, nav: n.nav, gen: genOf(n.key) })
276
+ }
277
+ /** What a message says of its document, for its track: its URL revision, and the navigation it arrived under. */
278
+ const docOf = (n: Node, data: { gen?: unknown }) => ({ gen: data.gen, nav: n.nav })
279
+ const said = (n: Node, o: Outcome | 'cut') => `${o}:${tracks.get(n.key)?.boot ?? ''}`
280
+
281
+ /** A node of the load in flight may have reached its outcome: its frame record, once per outcome and document. */
282
+ function progress(n: Node): void {
283
+ const L = owner
284
+ if (L && !L.done && L.committedAt !== undefined) {
285
+ const o = outcomeNow(n, useStore.getState().manifest)
286
+ if (o && L.reported.get(n.key) !== said(n, o)) frameRecord(L, n, o)
287
+ }
288
+ settleSoon()
289
+ }
290
+
291
+ function frameRecord(L: Load, n: Node, outcome: Outcome | 'cut'): void {
292
+ const t = tracks.get(n.key)
293
+ const times = [t?.admittedAt, t?.readyAt, t?.firstMeasureAt, t?.settled?.at]
294
+ rec('frame', L.id, {
295
+ node: n.key, frame: n.frame, gen: genOf(n.key), boot: t?.boot,
296
+ admitted: rel(L, t?.admittedAt), ready: rel(L, t?.readyAt), firstMeasure: rel(L, t?.firstMeasureAt), settled: rel(L, t?.settled?.at),
297
+ outcome,
298
+ // its document is older than the load: a reload of the same board kept it
299
+ ...(times.some((x) => x !== undefined && x < L.t0) ? { kept: true } : {}),
300
+ })
301
+ L.reported.set(n.key, said(n, outcome))
302
+ }
303
+
304
+ function quiet(L: Load): void {
305
+ L.quietTimer = undefined
306
+ if (L !== owner || L.done) return
307
+ if (!L.quietSent) { L.quietSent = true; rec('quiet', L.id, { ms: Math.round(L.lastMoveAt - L.t0) }) }
308
+ trySettle()
309
+ }
310
+
311
+ let soon = false
312
+ /** Check after what notified us is done (a hook may run inside a store change). */
313
+ function settleSoon(): void {
314
+ if (!on || soon || !owner || owner.done) return
315
+ soon = true
316
+ queueMicrotask(() => { soon = false; try { trySettle() } catch { /* never in the way */ } })
317
+ }
318
+
319
+ /** Settled: every node at its outcome from its live document, no reflow pending or held, admission idle, the camera
320
+ * still, and a second with no move. Each gate that is not open comes back on its own: the quiet timer, the reflow
321
+ * and admission notifications, a frame's message - the camera alone is asked again shortly. */
322
+ function trySettle(): void {
323
+ const L = owner
324
+ if (!L || L.done || L.committedAt === undefined) return
325
+ if (performance.now() - L.lastMoveAt < QUIET_MS) return
326
+ if (!reflowIdle() || !admissionIdle()) return
327
+ if (cameraMoving()) { L.retry ??= setTimeout(guard(() => { L.retry = undefined; trySettle() }), 150); return }
328
+ const s = useStore.getState()
329
+ const outs = s.nodes.map((n) => outcomeNow(n, s.manifest))
330
+ if (outs.some((o) => !o)) return
331
+ settle(L, s, outs as Outcome[])
332
+ }
333
+
334
+ function settle(L: Load, s: State, outs: Outcome[]): void {
335
+ ensureVisible(L)
336
+ s.nodes.forEach((n, i) => { if (L.reported.get(n.key) !== said(n, outs[i])) frameRecord(L, n, outs[i]) })
337
+ const lastReady = (ns: readonly Node[]) => {
338
+ const xs = ns.map((n) => tracks.get(n.key)?.readyAt).filter((x): x is number => x !== undefined)
339
+ return xs.length ? Math.max(0, Math.round(Math.max(...xs) - L.t0)) : undefined
340
+ }
341
+ if (!L.quietSent) { L.quietSent = true; rec('quiet', L.id, { ms: Math.round(L.lastMoveAt - L.t0) }) }
342
+ rec('settled', L.id, {
343
+ ms: Math.round(performance.now() - L.t0), moves: L.moves, distance: Math.round(L.distance), causes: L.causes, lastMove: rel(L, L.movedAt),
344
+ visibleReadyMs: lastReady(s.nodes.filter((n) => L.cohort?.has(n.key))), allReadyMs: lastReady(s.nodes),
345
+ missing: outs.filter((o) => o === 'missing').length, neverReady: outs.filter((o) => o === 'never-ready').length, errors: outs.filter((o) => o === 'error').length,
346
+ weight: weight(),
347
+ })
348
+ finish(L, 'settled')
349
+ }
350
+
351
+ /** The load ended before it settled: another board, a reload of this one, the page hidden, or 120 s. What its nodes
352
+ * had reached goes with it; the others are `cut`. The cut says how many frames the board had then and how many of
353
+ * those were ready - one count of one set: frames added while it loaded are in it, frames removed are not. */
354
+ function cut(L: Load, reason: 'switch' | 'reload' | 'hidden' | 'timeout'): void {
355
+ if (L.done) return
356
+ const s = useStore.getState()
357
+ ensureVisible(L)
358
+ let ready = 0
359
+ for (const n of s.nodes) {
360
+ const o = outcomeNow(n, s.manifest)
361
+ if (o === 'settled' || o === 'ready') ready++
362
+ if (!o) frameRecord(L, n, 'cut')
363
+ else if (L.reported.get(n.key) !== said(n, o)) frameRecord(L, n, o)
364
+ }
365
+ rec('cut', L.id, { reason, ms: Math.round(performance.now() - L.t0), lastMove: rel(L, L.movedAt), frames: s.nodes.length, ready })
366
+ finish(L, 'cut')
367
+ }
368
+
369
+ function finish(L: Load, how: 'settled' | 'cut'): void {
370
+ L.done = how
371
+ clearTimeout(L.quietTimer); clearTimeout(L.timeout); clearTimeout(L.retry)
372
+ L.quietTimer = L.timeout = L.retry = undefined
373
+ }
374
+
375
+ /** A settled load's weight: elements in the shell and its frames, iframes awake and asleep, the heap (Chrome). */
376
+ function weight() {
377
+ let domNodes = document.getElementsByTagName('*').length
378
+ const frames = [...document.querySelectorAll<HTMLIFrameElement>('iframe.sh-live[src]')]
379
+ for (const f of frames) { try { domNodes += f.contentDocument?.getElementsByTagName('*').length ?? 0 } catch { /* another origin */ } }
380
+ const asleep = sleeping()
381
+ const mem = (performance as { memory?: { usedJSHeapSize: number } }).memory
382
+ return { domNodes, iframes: frames.length, awake: Math.max(0, frames.length - asleep), asleep, ...(mem ? { heapMB: Math.round((mem.usedJSHeapSize / 1_048_576) * 10) / 10 } : {}) }
383
+ }
384
+
385
+ // ---- the visible cohort -----------------------------------------------------------------------------------------
386
+
387
+ const HEADER = 28 // a node's title bar, part of its box (FrameNode)
388
+ const cohortIn = (v: View) => new Set(useStore.getState().nodes
389
+ .filter((n) => n.x < v.x + v.w && n.x + n.w > v.x && n.y < v.y + v.h && n.y + n.h + HEADER > v.y).map((n) => n.key))
390
+ /** No fit landed before the load ended (a reload of the board in view): the cohort is what the camera shows. */
391
+ function ensureVisible(L: Load): void {
392
+ if (L.cohort || L.committedAt === undefined) return
393
+ const v = canvasCtl.view()
394
+ L.cohort = v ? cohortIn(v) : new Set()
395
+ rec('visible', L.id, { nodes: L.cohort.size, ms: Math.round(performance.now() - L.t0), assumed: true })
396
+ }
397
+
398
+ // ---- errors -----------------------------------------------------------------------------------------------------
399
+
400
+ let inError = false
401
+ /** the errors past a load's 50, counted in one `dropped` record while it waits to be sent (the next one adds to it) */
402
+ let over: PerfRecord | null = null
403
+ /** ≤ 50 per load (those past it counted), the same one at most once a second; messages and stack lines cut to 200
404
+ * characters. An error after the load settled or was cut is `late` - the load owns the geometry for as long as its
405
+ * board stays open. */
406
+ function logError(e: { source: 'shell' | 'frame' | 'stage'; frame?: string; component?: string; message: unknown; stack?: unknown }): void {
407
+ if (inError) return
408
+ inError = true
409
+ try {
410
+ const message = bound(typeof e.message === 'string' ? e.message : String(e.message ?? ''))
411
+ if (!message) return
412
+ const L = owner, mine = L ?? unowned
413
+ const key = `${e.source}|${e.frame ?? ''}|${message}`, now = performance.now()
414
+ if (now - (mine.errAt.get(key) ?? -Infinity) < 1000) return
415
+ if (mine.errors >= 50) {
416
+ if (over && over.load === ownerId() && outbox.has(over)) { over.n = (over.n as number) + 1; outbox.touch(over) }
417
+ else over = rec('dropped', ownerId(), { n: 1, reason: 'errors' })
418
+ return
419
+ }
420
+ mine.errors++
421
+ mine.errAt.set(key, now)
422
+ const stack = Array.isArray(e.stack) ? e.stack.slice(0, 3).map((l) => bound(l)).filter((l): l is string => !!l) : stackLines(e.stack)
423
+ rec('error', ownerId(), { source: e.source, frame: bound(e.frame), component: bound(e.component), message, ...(stack?.length ? { stack } : {}), ...(L?.done ? { late: true } : {}) })
424
+ } finally { inError = false }
425
+ }
426
+
427
+ // ---- sending ----------------------------------------------------------------------------------------------------
428
+
429
+ const armSend = () => { if (!sending && sendTimer === undefined && outbox.size) sendTimer = setTimeout(() => { sendTimer = undefined; void send() }, SEND_MS) }
430
+ const csrf = () => /(?:^|;\s*)mv_c=([\w-]+)/.exec(document.cookie)?.[1] ?? ''
431
+ const post = (records: PerfRecord[], keepalive = false) => api('perf/page', {
432
+ method: 'POST',
433
+ headers: { 'content-type': 'application/json', 'x-mv-c': csrf() },
434
+ body: JSON.stringify({ records }),
435
+ ...(keepalive ? { keepalive: true } : {}),
436
+ })
437
+ const wait = (ms: number) => new Promise<void>((r) => setTimeout(r, ms))
438
+ /** The `dropped` record that says how many went, when any did (the count starts over). */
439
+ const droppedNow = (more = 0): PerfRecord[] => {
440
+ const n = outbox.dropped + more
441
+ outbox.dropped = 0
442
+ return n ? [env('dropped', ownerId(), { n })] : []
443
+ }
444
+
445
+ /** Everything waiting, in one request (the queue is bounded under what the server takes); one at a time. A network
446
+ * failure or a server error is tried twice more, 2 s apart; a 403 primes the request cookie once (a page's first
447
+ * request may go before it exists, as logReload's); any other refusal is final. What never lands is counted. */
448
+ async function send(): Promise<void> {
449
+ clearTimeout(sendTimer)
450
+ sendTimer = undefined
451
+ if (!on || sending || !outbox.size) return
452
+ sending = true
453
+ let batch: PerfRecord[] = []
454
+ let ok = false
455
+ try {
456
+ batch = [...droppedNow(), ...outbox.takeAll()]
457
+ open.clear()
458
+ inFlight = batch
459
+ for (let attempt = 0; attempt < 3 && !ok; attempt++) {
460
+ if (attempt) await wait(SEND_MS)
461
+ try {
462
+ let r = await post(batch)
463
+ if (r.status === 403) { await api('work').catch(() => {}); r = await post(batch) }
464
+ if (r.ok) ok = true
465
+ else if (r.status < 500 || isStopped(r)) break // refused (a bad batch), or this canvas stopped: trying again cannot help
466
+ } catch { /* the network: again */ }
467
+ }
468
+ } catch { /* never in the way: what it held is counted below */ }
469
+ if (!ok) outbox.dropped += batch.filter((r) => r.kind !== 'dropped').length + batch.filter((r) => r.kind === 'dropped').reduce((n, r) => n + (r.n as number), 0)
470
+ inFlight = []
471
+ sending = false
472
+ armSend()
473
+ }
474
+
475
+ /** The page is going. The load in flight is cut; captures go first - a capture still open is sealed here (whichever
476
+ * pagehide listener runs first), and while one waits to be sent or is on its way the keepalive allowance is its:
477
+ * the recorder sends nothing. Else its last records with keepalive, 16 KB at most, the cuts first; the rest counted. */
478
+ function leave(): void {
479
+ if (owner && !owner.done) cut(owner, 'hidden')
480
+ cutPending('hidden')
481
+ clearTimeout(sendTimer)
482
+ sendTimer = undefined
483
+ sealCaptures()
484
+ if (capturesPending()) return
485
+ // a send on its way may not outlive the page: its records again (the report drops a duplicate by its seq)
486
+ const all = [...inFlight, ...outbox.takeAll()]
487
+ if (!all.length) return
488
+ // the cuts first, newest first: the load this page leaves in flight ends in the last of them
489
+ const { fit, lost } = fitWithin(all.filter((r) => r.kind === 'cut').reverse(), all.filter((r) => r.kind !== 'cut'), KEEPALIVE_BYTES)
490
+ try { void post([...fit, ...droppedNow(lost)], true).catch(() => {}) } catch { /* going anyway */ }
491
+ }
492
+
493
+ // ---- for tests --------------------------------------------------------------------------------------------------
494
+
495
+ function state() {
496
+ const s = useStore.getState()
497
+ return {
498
+ owner: owner && { id: owner.id, board: owner.board, cause: owner.cause, committed: owner.committedAt !== undefined, done: owner.done ?? null, cohort: owner.cohort ? [...owner.cohort] : null },
499
+ pending: [...pending.keys()], queued: outbox.size, sending, motion, admissionIdle: admissionIdle(),
500
+ nodes: Object.fromEntries(s.nodes.map((n) => [n.key, outcomeNow(n, s.manifest)])),
501
+ }
502
+ }
503
+
504
+ // ---- what the shell tells it ------------------------------------------------------------------------------------
505
+
506
+ export const recorder = {
507
+ /** A node's mount got its boot slot (FrameNode). */
508
+ admitted: guard((key: string) => { const n = node(key); if (n) trackOf(n).admittedAt = performance.now() }),
509
+ /** A frame document started (sh:boot): its node's story starts over - before its `load`, without polling. */
510
+ booted: guard((key: string, data: { boot?: unknown; gen?: unknown }) => { const n = node(key); if (n) adopt(trackOf(n), data.boot, liveBoot(key), docOf(n, data)) }),
511
+ /** sh:ready, after the shell's own generation check. */
512
+ ready: guard((key: string, data: { boot?: unknown; gen?: unknown }) => {
513
+ const n = node(key)
514
+ if (!n) return
515
+ const t = trackOf(n)
516
+ if (!adopt(t, data.boot, liveBoot(key), docOf(n, data))) return // a document since replaced never counts
517
+ t.readyAt ??= performance.now()
518
+ progress(n)
519
+ }),
520
+ /** sh:measure, with what the store took: only a settled report taken at the node's width settles it. */
521
+ measured: guard((key: string, data: { boot?: unknown; gen?: unknown; settled?: unknown }, took: MeasureResult) => {
522
+ const n = node(key)
523
+ if (!n) return
524
+ const t = trackOf(n)
525
+ if (!adopt(t, data.boot, liveBoot(key), docOf(n, data))) return
526
+ t.firstMeasureAt ??= performance.now()
527
+ // the first settled report at a width is when the node settled there
528
+ if (data.settled === true && took.took === 'fit' && took.w !== undefined && t.settled?.w !== took.w) t.settled = { at: performance.now(), w: took.w }
529
+ else if (took.took === 'width') delete t.settled // its width changed: the next report is the one
530
+ progress(n)
531
+ }),
532
+ /** sh:error, after the shell's generation check: recorded, and the node's outcome when it is its live document's. */
533
+ frameError: guard((key: string, data: { id?: unknown; boot?: unknown; gen?: unknown; message?: unknown; stack?: unknown }) => {
534
+ // an error from a document since replaced is no error of this page's (the shell drops it before here too)
535
+ if (typeof data.boot !== 'string' || data.boot !== liveBoot(key)) return
536
+ const n = node(key)
537
+ logError({ source: 'frame', frame: bound(data.id) ?? n?.frame, message: data.message, stack: data.stack })
538
+ if (!n) return
539
+ const t = trackOf(n)
540
+ if (adopt(t, data.boot, liveBoot(key), docOf(n, data))) { t.errorAt ??= performance.now(); progress(n) }
541
+ }),
542
+ /** The ready watchdog's second silence (FrameNode): never-ready for this navigation. The frame stays loading. */
543
+ neverReady: guard((key: string) => {
544
+ const n = node(key)
545
+ if (!n) return
546
+ trackOf(n).neverReady = { at: performance.now(), nav: n.nav ?? 0 }
547
+ progress(n)
548
+ }),
549
+ /** The iframe's load event: one more moment to check - it never resets an outcome. */
550
+ loaded: guard((_key: string) => settleSoon()),
551
+ /** Where a fit sends the camera, in world px (Canvas.tsx): the first one after a commit is the visible cohort. */
552
+ placed: guard((view: View) => {
553
+ const L = owner
554
+ if (!L || L.committedAt === undefined || L.cohort) return
555
+ L.cohort = cohortIn(view)
556
+ rec('visible', L.id, { nodes: L.cohort.size, ms: Math.round(performance.now() - L.t0) })
557
+ }),
558
+ /** A pan, zoom or layout animation ended (perf.ts). */
559
+ gesture: guard((g: Gesture) => { rec('gesture', ownerId(), g); settleSoon() }),
560
+ /** An error the shell saw: its own (window, ShellBoundary) or the play stage's. A shell error goes out at once. */
561
+ error: guard((e: { source: 'shell' | 'stage'; message: unknown; stack?: unknown; component?: string }) => {
562
+ logError(e)
563
+ if (e.source === 'shell' && !capturesPending()) void send()
564
+ }),
565
+ }