@marver-design/marver 0.26.1 → 0.27.2

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