@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,21 @@
1
+ /**
2
+ * `window.marverApp` - there only when this page is a verified local canvas in the Mac app (spec 28 A2.9; the app's
3
+ * canvas preload exposes it). Everywhere else - Chrome, Safari, a published canvas, `marver shot` - it is null, and
4
+ * nothing that reads it does anything. Kept apart from app-bridge.ts, so the canvas can read `reopen` without
5
+ * importing the bridge.
6
+ */
7
+ import type { MarverAppV1 } from '../../shared/app-api.ts'
8
+
9
+ /** The app's bridge, when it speaks this version of the contract and has every method this shell calls. */
10
+ export const APP: MarverAppV1 | null = (() => {
11
+ try {
12
+ const a = (globalThis as { marverApp?: Partial<MarverAppV1> }).marverApp
13
+ if (!a || a.v !== 1) return null
14
+ const calls = ['hello', 'theme', 'busy', 'menu', 'onAppState', 'onMenuClick'] as const
15
+ return calls.every((k) => typeof a[k] === 'function') ? a as MarverAppV1 : null
16
+ } catch { return null }
17
+ })()
18
+
19
+ /** The app reloaded this tab after a crash: the canvas opens on its saved camera, even when the link names a
20
+ * selection (A2.14 #9). */
21
+ export const APP_REOPEN = APP?.reopen === true
@@ -106,7 +106,9 @@ export function notesCramped(
106
106
 
107
107
  // ---- per-viewer visibility -------------------------------------------------------------
108
108
 
109
- const STORAGE = 'mv-notes'
109
+ /** The viewer's choice is kept per canvas (spec 28 A1.6): the shell names the key at boot (store.ts),
110
+ * so this module stays importable without the plugin's virtual modules (test/notes.test.ts). */
111
+ let STORAGE = 'mv-notes'
110
112
  interface NotesState {
111
113
  /** the N toggle: false hides every note on the canvas */
112
114
  all: boolean
@@ -143,6 +145,11 @@ export const useNotes = create<NotesState>((set, get) => ({
143
145
  set(next); save(next)
144
146
  },
145
147
  }))
148
+ /** Keep the notes' visibility under this canvas's key (`mv-notes:<workspace>`), read from it now. */
149
+ export function scopeNotes(key: string) {
150
+ STORAGE = key
151
+ useNotes.setState(load())
152
+ }
146
153
  /** Every note id currently on the canvas - read from the DOM, the one place that knows. */
147
154
  const allIds = (): string[] => (typeof document === 'undefined' ? [] : [...document.querySelectorAll('[data-note]')].map((el) => el.getAttribute('data-note')!))
148
155
 
@@ -0,0 +1,34 @@
1
+ /**
2
+ * A headless perf run's probe (spec 28 A3.8 #17): what its driver reads and asks, through CDP - nothing without
3
+ * ?mvperfrun. Canvas code (the camera, the gestures, the sleeps): main.tsx reaches it through App.tsx, so an
4
+ * all-boards-locked bundle, which the build gives LockedApp.tsx in App.tsx's place, carries none of it - a run's page
5
+ * is always a dev canvas, never a locked one.
6
+ */
7
+ import { currentLoad, flush } from './recorder.ts'
8
+ import { installPerfRunProbe, PERF_RUN, postersSkipped, refusedInPage } from './perf-run.ts'
9
+ import { bakeIdle, bakeWork } from './canvas/sleep.ts'
10
+ import { canvasCtl } from './canvas/ctl.ts'
11
+ import { gestureRunning, gesturesEnded } from './perf.ts'
12
+
13
+ /** main.tsx, after startAppPerf(): the probe, installed only on a run's page. */
14
+ export function startPerfRunProbe(): void {
15
+ if (!PERF_RUN) return
16
+ const run = PERF_RUN
17
+ const moving = () => gestureRunning() || canvasCtl.cameraBusy()
18
+ const wait = (ms: number) => new Promise((r) => setTimeout(r, ms))
19
+ installPerfRunProbe({
20
+ status: () => ({ run: run.id, warm: run.warm, load: currentLoad(), bakeIdle: bakeIdle(), bake: bakeWork(), moving: moving(), gestures: gesturesEnded(), postersSkipped: postersSkipped(), refused: refusedInPage() }),
21
+ // the whole board, then the camera still (two looks 50 ms apart), 3 s at most
22
+ async fit() {
23
+ canvasCtl.fitAll()
24
+ const by = performance.now() + 3000
25
+ for (let still = 0; performance.now() < by; await wait(50)) if (moving()) still = 0; else if (++still >= 2) return true
26
+ return false
27
+ },
28
+ centre() {
29
+ const r = document.querySelector('.sh-canvas')?.getBoundingClientRect()
30
+ return r ? { x: Math.round(r.left + r.width / 2), y: Math.round(r.top + r.height / 2) } : { x: Math.round(innerWidth / 2), y: Math.round(innerHeight / 2) }
31
+ },
32
+ flush,
33
+ })
34
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Perf mode, the page's half of a headless run (spec 28 A3.4, A3.8 #17): `?mvperfrun=<16 hex>[&warm=1]` sets
3
+ * `PERF_RUN` at module load, before boot, in dev only. Owner: the headless stream; the contract is
4
+ * src/shared/perf-run.ts, which the server reads too.
5
+ *
6
+ * - The barrier sits in `mvFetch` (api.ts), before any `fetch`: GET and HEAD pass, and under `${ROUTE}/api/` only
7
+ * `POST perf/page` and `POST bakes`; anything else gets a synthetic 403, counted as `refused`, and never reaches
8
+ * `lost()`. Every request carries `x-mv-perfrun`; `withWs()` adds `mvperfrun` to frame URLs, the play stage and
9
+ * Jam pictures.
10
+ * - Warm mode: the recorder runs (the driver reads `settled` from it) and posts nothing; `flush()` sends until the
11
+ * outbox is empty and answers whether every batch landed.
12
+ * - In perf mode `beforeunload` never refuses, and the Video primitive never asks for a poster
13
+ * (`data-mv-poster-skipped`).
14
+ * - `window.__mvPerfRun` (`PerfRunProbe`): status(), fit(), centre(), flush().
15
+ *
16
+ * FROZEN (A3.8 #53): `PERF_RUN`, `runApiPath`, `perfRunGate` and `installPerfRunProbe`'s signature.
17
+ */
18
+ import { ROUTE } from '../const.ts'
19
+ import { allowedInRun, RUN_HEADER, RUN_ID, RUN_PARAM, WARM_PARAM, type PerfRunProbe } from '../../shared/perf-run.ts'
20
+
21
+ export * from '../../shared/perf-run.ts'
22
+
23
+ /**
24
+ * This page's run, or null: a published canvas (a production build), or no `mvperfrun`. Read with no import of
25
+ * api.ts, which calls `perfRunGate` (a cycle would read this before it exists).
26
+ */
27
+ export const PERF_RUN: { id: string; warm: boolean } | null = (() => {
28
+ if (!import.meta.env.DEV) return null
29
+ try {
30
+ const q = new URLSearchParams(location.search)
31
+ const id = q.get(RUN_PARAM)
32
+ return id && RUN_ID.test(id) ? { id, warm: q.get(WARM_PARAM) === '1' } : null
33
+ } catch { return null }
34
+ })()
35
+
36
+ /** The path under `${ROUTE}/api/` a URL names (no query), or null for any other path. */
37
+ export function runApiPath(url: string): string | null {
38
+ let p: string
39
+ try { p = new URL(url, location.href).pathname } catch { return null }
40
+ const base = `${ROUTE}/api/`
41
+ return p.startsWith(base) ? p.slice(base.length) : null
42
+ }
43
+
44
+ let refused = 0
45
+ /** Requests refused before sending, so far. */
46
+ export const refusedInPage = (): number => refused
47
+
48
+ /**
49
+ * The barrier, called first by `mvFetch` in perf mode: null lets the request go (it then carries `x-mv-perfrun`);
50
+ * a Response is the synthetic refusal, never sent.
51
+ */
52
+ export function perfRunGate(url: string, init: RequestInit = {}): Response | null {
53
+ if (!PERF_RUN) return null
54
+ if (allowedInRun(init.method ?? 'GET', runApiPath(url))) return null
55
+ refused += 1
56
+ return new Response('{"error":"a perf run is read-only"}', { status: 403, headers: { 'content-type': 'application/json', [RUN_HEADER]: 'refused' } })
57
+ }
58
+
59
+ /** Same-origin frames whose document skipped a missing poster (the Video primitive's `data-mv-poster-skipped`). */
60
+ export function postersSkipped(): number {
61
+ let n = 0
62
+ for (const f of document.querySelectorAll('iframe')) { try { if (f.contentDocument?.documentElement.hasAttribute('data-mv-poster-skipped')) n++ } catch { /* another origin */ } }
63
+ return n
64
+ }
65
+
66
+ /** main.tsx in perf mode: `window.__mvPerfRun`. */
67
+ export function installPerfRunProbe(probe: PerfRunProbe): void {
68
+ if (!PERF_RUN) return
69
+ ;(window as unknown as { __mvPerfRun?: PerfRunProbe }).__mvPerfRun = probe
70
+ }
@@ -1,34 +1,25 @@
1
1
  /**
2
- * B0.4: canvas performance instrumentation. Zero cost unless explicitly enabled.
2
+ * Gesture timing (B0.4; spec 28 A1.7). Frame intervals are sampled ONLY while a gesture runs - a canvas pan or zoom
3
+ * (`sh-camera` on #sh-world) or a layout animation (`sh-preset`) - and no frame is scheduled at rest: the camera
4
+ * observer (canvas/camera-broadcast.ts) says when one starts and stops, and the rAF loop runs between the two. Each
5
+ * gesture ends in one `gesture` record for the recorder (recorder.ts, dev only): the intervals as they are - p50,
6
+ * p95, max, and the counts over 17 ms and over 33 ms - and the long animation frames that started inside it
7
+ * (`longtask` entries where the browser has no long-animation-frame). No median-relative "missed" count: it would call
8
+ * a steady half-rate gesture smooth.
3
9
  *
4
- * Enabled in dev, or in ANY build (incl. packed/published - the gate is dev AND
5
- * publish) via `?mvperf` in the URL or `localStorage.mvPerf==='1'`. So publish-side gate
6
- * measurement is possible without shipping an always-on probe.
7
- *
8
- * Two honest signals, sampled ONLY while a gesture is active (the `#sh-world.sh-gesturing`
9
- * class every gesture path already sets):
10
- * - frame INTERVALS (rAF deltas). A healthy 60Hz frame is ~16.7ms, so the interval is NOT
11
- * "main-thread work" - we report its p50/p95/max and, as the jank signal, `dropped` =
12
- * intervals over 32ms (a missed refresh).
13
- * - long-task durations (PerformanceObserver 'longtask', >50ms by spec) landing during a
14
- * gesture: actual main-thread work that blew the budget. 0 long-tasks = smooth.
15
- *
16
- * Read it live: __mvPerf.report() / __mvPerf.reset()
17
- * perfMark(name) + counters are the plug points Stages 2-3 use (blank-frame / warm-latency).
10
+ * Sampled in dev, or in ANY build (a published one too) with `?mvperf` in the URL or `localStorage.mvPerf==='1'` - read
11
+ * it live: __mvPerf.report() / __mvPerf.reset()
12
+ * perfMark(name) + counters are the plug points later stages use (blank-frame / warm-latency).
18
13
  */
14
+ import { onMotion, type Motion } from './canvas/camera-broadcast.ts'
15
+ import { gestureOff, gestureOn } from './app-perf.ts'
16
+ import { recorder } from './recorder.ts'
17
+ import { gestureStats } from './recorder-core.ts'
19
18
 
20
- // "in motion" = a pan/zoom/drag gesture OR a device-sweep/tidy preset animation - both are the
21
- // windows where jank matters and the perf gate is measured.
22
- const GESTURING = () => {
23
- const w = document.getElementById('sh-world')
24
- return !!w && (w.classList.contains('sh-camera') || w.classList.contains('sh-preset'))
25
- }
26
-
27
- const frames: number[] = [] // inter-frame intervals (ms) during gestures
28
- const tasks: number[] = [] // long-task durations (ms) during gestures
19
+ const LOAF = typeof PerformanceObserver !== 'undefined' && (PerformanceObserver.supportedEntryTypes ?? []).includes('long-animation-frame')
20
+ const frames: number[] = [] // inter-frame intervals (ms) across gestures, for report()
21
+ const longs: number[] = [] // the long frames (or long tasks) that started inside a gesture, their durations (ms), for report()
29
22
  const MAX = 1200
30
- let last = 0
31
- let raf = 0
32
23
 
33
24
  const counters: Record<string, number> = { blankFrames: 0 }
34
25
  const marks: { name: string; t: number }[] = []
@@ -41,52 +32,83 @@ const enabled = (): boolean => {
41
32
  } catch { return false }
42
33
  }
43
34
 
44
- const tick = (t: number) => {
45
- if (last && GESTURING()) { const dt = t - last; frames.push(dt); if (frames.length > MAX) frames.shift() }
46
- last = t
47
- raf = requestAnimationFrame(tick)
35
+ interface Run { t0: number; last: number; dts: number[]; pan: boolean; zoom: boolean; layout: boolean; longs: number[]; obs?: PerformanceObserver; raf: number }
36
+ /** the gesture running now */
37
+ let g: Run | null = null
38
+ /** gestures ended so far, every one (a headless perf run waits for each of its three, spec 28 A3.8 #20) */
39
+ let ended = 0
40
+ /** How many gestures have ended since the page loaded. */
41
+ export const gesturesEnded = (): number => ended
42
+ /** Is a gesture (a pan, a zoom, a layout animation) running now? */
43
+ export const gestureRunning = (): boolean => g !== null
44
+
45
+ function note(m: Motion) {
46
+ if (!g) return
47
+ if (m.camera) { if (document.body.classList.contains('sh-panning')) g.pan = true; else g.zoom = true }
48
+ if (m.preset) g.layout = true
49
+ }
50
+
51
+ function begin(m: Motion) {
52
+ const run: Run = { t0: performance.now(), last: 0, dts: [], pan: false, zoom: false, layout: false, longs: [], raf: 0 }
53
+ g = run
54
+ note(m)
55
+ // the Mac app's recorder hears it start (the white-out detector's window, spec 28 A3.8 #15); nothing elsewhere
56
+ gestureOn(run.pan ? 'pan' : run.zoom ? 'zoom' : run.layout ? 'layout' : undefined)
57
+ try {
58
+ run.obs = new PerformanceObserver((l) => { for (const e of l.getEntries()) if (e.startTime >= run.t0) run.longs.push(e.duration) })
59
+ run.obs.observe({ type: LOAF ? 'long-animation-frame' : 'longtask', buffered: false })
60
+ } catch { /* neither entry type (Safari): the intervals still sample */ }
61
+ // this gesture's own loop: a frame of an earlier one that is still queued finds another run and stops
62
+ const tick = (t: number) => {
63
+ if (g !== run) return
64
+ if (run.last) run.dts.push(t - run.last)
65
+ run.last = t
66
+ run.raf = requestAnimationFrame(tick)
67
+ }
68
+ run.raf = requestAnimationFrame(tick)
48
69
  }
49
70
 
50
- const pct = (sorted: number[], p: number): number => {
51
- if (!sorted.length) return 0
52
- const i = Math.min(sorted.length - 1, Math.floor((p / 100) * sorted.length))
53
- return Math.round(sorted[i] * 100) / 100
71
+ function end() {
72
+ const run = g!
73
+ g = null
74
+ ended++
75
+ cancelAnimationFrame(run.raf)
76
+ const t1 = performance.now()
77
+ for (const e of run.obs?.takeRecords() ?? []) if (e.startTime >= run.t0 && e.startTime <= t1) run.longs.push(e.duration)
78
+ run.obs?.disconnect()
79
+ gestureOff()
80
+ for (const d of run.dts) { frames.push(d); if (frames.length > MAX) frames.shift() }
81
+ for (const d of run.longs) { longs.push(d); if (longs.length > MAX) longs.shift() }
82
+ if (run.dts.length < 2) return // a press that never moved the camera
83
+ recorder.gesture({ type: run.pan ? 'pan' : run.zoom ? 'zoom' : 'layout', ms: Math.round(t1 - run.t0), ...gestureStats(run.dts, run.longs.length) })
54
84
  }
55
- const top = (sorted: number[]): number => (sorted.length ? Math.round(sorted[sorted.length - 1] * 100) / 100 : 0)
56
- const frac = (n: number, d: number): number => (d ? Math.round((n / d) * 1000) / 1000 : 0)
57
85
 
58
86
  /** One-shot event later stages record (e.g. a blank frame, or warm-promotion latency). */
59
87
  export const perfMark = (name: string): void => {
60
88
  counters[name] = (counters[name] ?? 0) + 1
61
- marks.push({ name, t: last })
89
+ marks.push({ name, t: performance.now() })
62
90
  if (marks.length > 400) marks.shift()
63
91
  }
64
92
 
65
- /** Start the sampler. Idempotent; a no-op unless enabled() (dev, ?mvperf, or localStorage). */
93
+ let started = false
94
+ /** Watch for gestures. Idempotent; a no-op unless enabled() (dev, ?mvperf, or localStorage). */
66
95
  export function startPerf(): void {
67
- if (raf || !enabled()) return
68
- raf = requestAnimationFrame(tick)
69
- try {
70
- const obs = new PerformanceObserver((list) => {
71
- for (const e of list.getEntries()) if (GESTURING()) { tasks.push(e.duration); if (tasks.length > MAX) tasks.shift() }
72
- })
73
- obs.observe({ type: 'longtask', buffered: false })
74
- } catch { /* longtask entry type unsupported (e.g. Safari) - frame intervals still sample */ }
96
+ if (started || !enabled()) return
97
+ started = true
98
+ onMotion((m) => {
99
+ const moving = m.camera || m.preset
100
+ if (moving && !g) begin(m)
101
+ else if (!moving && g) end()
102
+ else note(m)
103
+ })
75
104
  ;(window as unknown as { __mvPerf: unknown }).__mvPerf = {
105
+ // the intervals as they are, and the main thread's own work: long frames (> 50 ms) that started in a gesture,
106
+ // how many, their p95 and the longest (the same nearest-rank rule)
76
107
  report() {
77
- const fi = [...frames].sort((a, b) => a - b)
78
- const tw = [...tasks].sort((a, b) => a - b)
79
- const dropped = fi.filter((d) => d > 32).length
80
- return {
81
- gestureFrames: fi.length,
82
- frameP50: pct(fi, 50), frameP95: pct(fi, 95), frameMax: top(fi),
83
- dropped, droppedFrac: frac(dropped, fi.length),
84
- // actual main-thread work during gestures (long tasks >50ms). 0 = smooth.
85
- longTasks: tw.length, longTaskP95: pct(tw, 95), longTaskMax: top(tw),
86
- counters: { ...counters },
87
- }
108
+ const s = gestureStats(frames, longs.length), l = gestureStats(longs, 0)
109
+ return { gestureFrames: s.frames, frameP50: s.p50, frameP95: s.p95, frameMax: s.max, over17ms: s.over17ms, over33ms: s.over33ms, longFrames: s.longFrames, longFrameP95: l.p95, longFrameMax: l.max, counters: { ...counters } }
88
110
  },
89
- reset() { frames.length = 0; tasks.length = 0; marks.length = 0; for (const k in counters) counters[k] = 0 },
111
+ reset() { frames.length = 0; longs.length = 0; marks.length = 0; for (const k in counters) counters[k] = 0 },
90
112
  marks: () => [...marks],
91
113
  }
92
114
  }
@@ -0,0 +1,183 @@
1
+ /**
2
+ * The recorder's pure parts (spec 28 A1.7), kept apart from the browser-coupled store so they can be unit-tested
3
+ * (the ready-watch.ts precedent): the bounded outbox, sizes in UTF-8 bytes, what fits a page's last keepalive send, a
4
+ * gesture's numbers, and a node's outcome from what its live document said.
5
+ */
6
+
7
+ export const KINDS = ['load', 'commit', 'visible', 'frame', 'move', 'quiet', 'settled', 'cut', 'gesture', 'error', 'dropped'] as const
8
+ export type Kind = typeof KINDS[number]
9
+ /** Every record: the workspace, this page, the load that owns the geometry ('-' before the first commit), its place
10
+ * in this page's order, and when it happened. */
11
+ export interface Envelope { v: 1; ws: string; page: string; load: string; seq: number; ts: number; kind: Kind }
12
+ export type PerfRecord = Envelope & Record<string, unknown>
13
+
14
+ /** The queue's bounds: past either, the oldest go and are counted. */
15
+ export const QUEUE_MAX = 2_000, QUEUE_BYTES = 256 * 1024
16
+ /** A page that is going sends at most this much with keepalive: the rest of the 64 KB allowance is the captures'. */
17
+ export const KEEPALIVE_BYTES = 16 * 1024
18
+ /** Records wait this long for company before a send; a failed send waits this long before it tries again. */
19
+ export const SEND_MS = 2_000
20
+ /** A board is quiet after this long without a move. */
21
+ export const QUIET_MS = 1_000
22
+ /** A load not settled by then is cut. */
23
+ export const LOAD_MAX_MS = 120_000
24
+
25
+ const enc = new TextEncoder()
26
+ /** Size in UTF-8 bytes, as the request body will carry it - not `.length`, which counts UTF-16 units. */
27
+ export const bytesOf = (x: unknown): number => enc.encode(typeof x === 'string' ? x : JSON.stringify(x)).length
28
+
29
+ /** Records waiting to be sent, oldest first. Past `max` records or `maxBytes` the oldest go, counted in `dropped`
30
+ * (the recorder sends that count in a `dropped` record and zeroes it). */
31
+ export class Outbox {
32
+ private items: { rec: PerfRecord; bytes: number }[] = []
33
+ private waiting = new Set<PerfRecord>()
34
+ bytes = 0
35
+ dropped = 0
36
+ constructor(private max = QUEUE_MAX, private maxBytes = QUEUE_BYTES) {}
37
+ get size(): number { return this.items.length }
38
+ push(rec: PerfRecord): void {
39
+ const bytes = bytesOf(rec)
40
+ this.items.push({ rec, bytes })
41
+ this.waiting.add(rec)
42
+ this.bytes += bytes
43
+ this.trim()
44
+ }
45
+ /** A waiting record changed in place (a coalesced move): its size again. */
46
+ touch(rec: PerfRecord): void {
47
+ for (let i = this.items.length - 1; i >= 0; i--) {
48
+ const it = this.items[i]
49
+ if (it.rec !== rec) continue
50
+ const bytes = bytesOf(rec)
51
+ this.bytes += bytes - it.bytes
52
+ it.bytes = bytes
53
+ this.trim()
54
+ return
55
+ }
56
+ }
57
+ /** Still waiting (not sent, not dropped)? */
58
+ has(rec: PerfRecord): boolean { return this.waiting.has(rec) }
59
+ /** Everything waiting, oldest first; the outbox is empty after. */
60
+ takeAll(): PerfRecord[] {
61
+ const out = this.items.map((it) => it.rec)
62
+ this.items = []
63
+ this.waiting.clear()
64
+ this.bytes = 0
65
+ return out
66
+ }
67
+ private trim(): void {
68
+ while (this.items.length && (this.items.length > this.max || this.bytes > this.maxBytes)) {
69
+ const it = this.items.shift()!
70
+ this.waiting.delete(it.rec)
71
+ this.bytes -= it.bytes
72
+ // a `dropped` record that goes takes what it counted with it
73
+ this.dropped += it.rec.kind === 'dropped' && typeof it.rec.n === 'number' ? it.rec.n : 1
74
+ }
75
+ }
76
+ }
77
+
78
+ /** For a page that is going: as many of `first` (the cuts) as fit, in their order, then the oldest of `rest`, while
79
+ * the whole body `{"records":[…]}` stays within `maxBytes` with `reserve` left for a `dropped` record - the limit
80
+ * holds for the cuts too, however many a stalled send left waiting. The others, cuts included, are `lost`. */
81
+ export function fitWithin(first: readonly PerfRecord[], rest: readonly PerfRecord[], maxBytes = KEEPALIVE_BYTES, reserve = 160): { fit: PerfRecord[]; lost: number } {
82
+ const fit: PerfRecord[] = []
83
+ let size = bytesOf({ records: [] }) + reserve
84
+ const take = (r: PerfRecord) => {
85
+ const add = bytesOf(r) + (fit.length ? 1 : 0)
86
+ if (size + add > maxBytes) return false
87
+ size += add
88
+ fit.push(r)
89
+ return true
90
+ }
91
+ let lost = 0
92
+ for (const r of first) if (!take(r)) lost++
93
+ for (let i = 0; i < rest.length; i++) if (!take(rest[i])) { lost += rest.length - i; break }
94
+ return { fit, lost }
95
+ }
96
+
97
+ /** A gesture's frame intervals as they are: nearest-rank percentiles (cli/perf.ts `spread`'s rule), one decimal; the
98
+ * counts over 17 ms and over 33 ms; `longFrames` as given. */
99
+ export function gestureStats(dts: readonly number[], longFrames: number): { frames: number; p50: number; p95: number; max: number; over17ms: number; over33ms: number; longFrames: number } {
100
+ const v = [...dts].sort((a, b) => a - b)
101
+ const at = (q: number) => (v.length ? v[Math.min(v.length - 1, Math.ceil(q * v.length) - 1)] : 0)
102
+ const r = (x: number) => Math.round(x * 10) / 10
103
+ return {
104
+ frames: v.length, p50: r(at(0.5)), p95: r(at(0.95)), max: r(v[v.length - 1] ?? 0),
105
+ over17ms: v.filter((d) => d > 17).length, over33ms: v.filter((d) => d > 33).length, longFrames,
106
+ }
107
+ }
108
+
109
+ /** What a node of a load waits for: a settled measure at its width, its ready, or nothing (missing). */
110
+ export type Rule = 'measure' | 'ready' | 'missing'
111
+ export type Outcome = 'settled' | 'ready' | 'missing' | 'error' | 'never-ready'
112
+ /** One node's story, as its live document told it (page-level, by node key: a reload of the same board keeps the
113
+ * documents, and their facts carry over). Times are performance.now(). */
114
+ export interface Track {
115
+ frame: string
116
+ /** the document these facts belong to */
117
+ boot?: string
118
+ /** that document's URL revision (its own `r`), and the node's navigation when it was adopted */
119
+ gen?: string
120
+ nav?: number
121
+ /** when the node's mount was admitted - not per document (a reload keeps its slot) */
122
+ admittedAt?: number
123
+ readyAt?: number
124
+ firstMeasureAt?: number
125
+ /** a settled report the store took at this width */
126
+ settled?: { at: number; w: number }
127
+ errorAt?: number
128
+ /** the watchdog's second silence, for this navigation */
129
+ neverReady?: { at: number; nav: number }
130
+ }
131
+
132
+ /** A message from document `boot`: kept only when that document is the one there now. A new live document starts
133
+ * the node's story over - noting its own URL revision (`gen`, from the message) and the node's navigation (`nav`) -
134
+ * and a message from a live document supersedes the watchdog's verdict. */
135
+ export function adopt(t: Track, boot: unknown, live: string | undefined, doc?: { gen?: unknown; nav?: number }): boolean {
136
+ if (typeof boot !== 'string' || !boot || boot !== live) return false
137
+ if (t.boot !== boot) {
138
+ t.boot = boot
139
+ delete t.gen; delete t.nav; delete t.readyAt; delete t.firstMeasureAt; delete t.settled; delete t.errorAt
140
+ if (doc) t.nav = doc.nav ?? 0
141
+ }
142
+ if (typeof doc?.gen === 'string') t.gen = doc.gen
143
+ delete t.neverReady
144
+ return true
145
+ }
146
+
147
+ /** The node's outcome now, or null (pending). An outcome a document reported counts only while that document is the
148
+ * live one, on the navigation the shell asked for last - a document since replaced, one still booting (no live boot
149
+ * yet), or one a reload is replacing (the node's `nav` moved on, or its iframe was sent to another revision `gen`,
150
+ * while the old document is still there until the new one commits) sends it back to pending.
151
+ * `missing` and `never-ready` have no document and are exempt: missing while the frame is absent from the manifest,
152
+ * never-ready for the navigation the watchdog gave up on, until a new navigation or a live message replaces it. */
153
+ export function outcomeOf(rule: Rule, t: Track | undefined, live: string | undefined, node: { w: number; nav?: number; gen?: string }): Outcome | null {
154
+ if (rule === 'missing') return 'missing'
155
+ if (!t) return null
156
+ const current = !!live && t.boot === live
157
+ && (t.nav === undefined || t.nav === (node.nav ?? 0))
158
+ && (t.gen === undefined || node.gen === undefined || t.gen === node.gen)
159
+ if (current && t.errorAt !== undefined) return 'error'
160
+ if (current && rule === 'ready' && t.readyAt !== undefined) return 'ready'
161
+ if (current && rule === 'measure' && t.settled && t.settled.w === Math.round(node.w)) return 'settled'
162
+ if (t.neverReady && t.neverReady.nav === (node.nav ?? 0)) return 'never-ready'
163
+ return null
164
+ }
165
+
166
+ /** The first three stack lines of an error - Chrome's " at …", else Safari's and Firefox's "fn@url:line:col" -
167
+ * each 200 characters at most. */
168
+ export function stackLines(stack: unknown): string[] | undefined {
169
+ if (typeof stack !== 'string' || !stack) return undefined
170
+ const lines = stack.split('\n')
171
+ const chrome = lines.filter((l) => /^\s*at /.test(l))
172
+ const picked = chrome.length ? chrome : lines.filter((l) => /@.*:\d+(:\d+)?$/.test(l.trim()))
173
+ const out = picked.slice(0, 3).map((l) => l.trim().slice(0, 200)).filter(Boolean)
174
+ return out.length ? out : undefined
175
+ }
176
+
177
+ /** A string bounded to `n` characters, or undefined. */
178
+ export const bound = (v: unknown, n = 200): string | undefined => (typeof v === 'string' && v ? v.slice(0, n) : undefined)
179
+
180
+ /** 12 hex characters: a page, a load or a document id. */
181
+ export function newId(): string {
182
+ return Array.from(crypto.getRandomValues(new Uint8Array(6)), (b) => b.toString(16).padStart(2, '0')).join('')
183
+ }