@marver-design/marver 0.27.0 → 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 (82) hide show
  1. package/CHANGELOG.md +94 -0
  2. package/README.md +5 -2
  3. package/dist/{anchor-check-ChdDqL5z.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-DlTcpF47.mjs → boards-BqUqKNW8.mjs} +4 -4
  7. package/dist/{build-DZnFysGU.mjs → build-VgNg4rr8.mjs} +7 -22
  8. package/dist/cli.mjs +32 -18
  9. package/dist/{collab-Dxg2trOK.mjs → collab-BEAcXrBb.mjs} +1 -1
  10. package/dist/{comments-DxOkCSNE.mjs → comments-YEU1Zhv9.mjs} +4 -4
  11. package/dist/{context-HQ4Giw58.mjs → context-Ccjrhr1J.mjs} +3 -3
  12. package/dist/{daemon-BSA0lV8d.mjs → daemon-Dc9AH0M3.mjs} +4 -4
  13. package/dist/{dev-eQJhWsqg.mjs → dev-ri6nAlRp.mjs} +11 -11
  14. package/dist/{init-COD0x48i.mjs → init-W0nxR1OY.mjs} +3 -3
  15. package/dist/{link-DDXZVGtv.mjs → link-CdTgn94Y.mjs} +4 -4
  16. package/dist/{ls-D7O1G505.mjs → ls-BZ5TAtd5.mjs} +1 -1
  17. package/dist/{manifest-Nl3KSVOk.mjs → manifest-aFyDmL8C.mjs} +2 -2
  18. package/dist/{marks-CWM3WJjc.mjs → marks-BF9pNEgH.mjs} +2 -2
  19. package/dist/{marks-CKgzucHZ.mjs → marks-CnCCfAbD.mjs} +3 -3
  20. package/dist/{marver-id-gate-BjF6v4bT.mjs → marver-id-gate-D-R0hSt_.mjs} +1 -1
  21. package/dist/perf-DkAUFT6W.mjs +1319 -0
  22. package/dist/perf-jam-BaH3Lg0m.mjs +635 -0
  23. package/dist/{plugin-C-E7omsh.mjs → plugin-B8UghYuF.mjs} +2592 -112
  24. package/dist/{poster-Bx83ZYVK.mjs → poster-BNgafWMK.mjs} +1 -1
  25. package/dist/{profile-Bh5Y5zpW.mjs → profile-jIS6BcAs.mjs} +1 -1
  26. package/dist/{publish-bakes-aljgm45S.mjs → publish-bakes-38Nja78p.mjs} +3 -3
  27. package/dist/{recover-t9Pno3u9.mjs → recover-B8AiI29B.mjs} +2 -2
  28. package/dist/{serve-C8rVheYk.mjs → serve-Dp3nHstu.mjs} +3 -3
  29. package/dist/{share-W5H3BNvP.mjs → share-Ce4tP7ji.mjs} +1 -1
  30. package/dist/{shot-DoHLl6ig.mjs → shot-CMQgMVZm.mjs} +1 -1
  31. package/dist/{shot-LFhC-WYD.mjs → shot-Ch24tiMO.mjs} +30 -5
  32. package/dist/{slots-DCDo3N0x.mjs → slots-CFNnegCc.mjs} +8 -1
  33. package/dist/{sync-BQVlHZpx.mjs → sync-CQdGARJ9.mjs} +1 -1
  34. package/dist/{work-BroFwnup.mjs → work-Bxz-ObF3.mjs} +3 -3
  35. package/dist/{work-Bp1p39kq.mjs → work-CNhFF9pU.mjs} +1 -1
  36. package/docs/jam-session.md +2 -1
  37. package/docs/performance.md +197 -35
  38. package/package.json +1 -1
  39. package/src/client/content/video.tsx +10 -2
  40. package/src/client/shell/App.tsx +10 -3
  41. package/src/client/shell/Comments.tsx +5 -3
  42. package/src/client/shell/ContextMenu.tsx +5 -3
  43. package/src/client/shell/LockedApp.tsx +3 -0
  44. package/src/client/shell/Play.tsx +4 -2
  45. package/src/client/shell/Tip.tsx +3 -1
  46. package/src/client/shell/api.ts +47 -20
  47. package/src/client/shell/app-bridge.ts +254 -0
  48. package/src/client/shell/app-perf.ts +92 -0
  49. package/src/client/shell/canvas/Canvas.tsx +115 -22
  50. package/src/client/shell/canvas/FrameNode.tsx +10 -6
  51. package/src/client/shell/canvas/admission.ts +23 -8
  52. package/src/client/shell/canvas/ctl.ts +6 -0
  53. package/src/client/shell/canvas/sleep.ts +57 -17
  54. package/src/client/shell/canvas/updates.ts +2 -1
  55. package/src/client/shell/inset.ts +44 -0
  56. package/src/client/shell/jam-capture.ts +19 -14
  57. package/src/client/shell/jam-keys.ts +8 -3
  58. package/src/client/shell/jam-panel.tsx +6 -3
  59. package/src/client/shell/jam-voice.ts +48 -10
  60. package/src/client/shell/main.tsx +14 -1
  61. package/src/client/shell/marks-ui.tsx +5 -3
  62. package/src/client/shell/marver-app.ts +21 -0
  63. package/src/client/shell/perf-run-probe.ts +34 -0
  64. package/src/client/shell/perf-run.ts +70 -0
  65. package/src/client/shell/perf.ts +11 -0
  66. package/src/client/shell/recorder.ts +45 -3
  67. package/src/client/shell/store.ts +52 -24
  68. package/src/client/shell/styles.css +47 -15
  69. package/src/client/shell/unsaved.ts +81 -0
  70. package/src/client/shell/whiteout-probes.ts +141 -0
  71. package/src/shared/app-api.ts +205 -0
  72. package/src/shared/app-perf.ts +308 -0
  73. package/src/shared/logo-sniff.ts +86 -0
  74. package/src/shared/machine.ts +132 -0
  75. package/src/shared/perf-run.ts +177 -0
  76. package/templates/AGENTS-embedded.md +3 -0
  77. package/templates/AGENTS-studio.md +3 -0
  78. package/templates/instructions/boards.md +3 -1
  79. package/dist/bake-DM_uWgAA.mjs +0 -786
  80. package/dist/perf-BWzQwZqj.mjs +0 -369
  81. package/dist/perf-BoDSkbEb.mjs +0 -429
  82. package/dist/perf-jam-D55U3FZK.mjs +0 -242
@@ -0,0 +1,141 @@
1
+ /**
2
+ * The white-out detector's probes, the shell's half (spec 28 A3.3, A3.8 #16): up to 16 points of empty canvas
3
+ * background, picked geometrically before main captures and checked again after. Owner: the flash stream.
4
+ *
5
+ * During a gesture frames take no pointer events (styles.css ~169), so hit-testing alone would take a white frame
6
+ * for ground: `pick(tick)` takes grid points inside `usable()` below `VISIBLE_TOP` (inset.ts), each at least 48 px
7
+ * from every `.sh-node`'s screen rect, with the canvas surface under it; `verify(tick)` says which are still valid -
8
+ * moved on screen by less than their clearance between the two answers. A frame white on purpose is excluded by its
9
+ * rect. Main treats fewer than 4 valid probes, a changed document, bounds or active tab, or an answer later than
10
+ * 150 ms as inconclusive, never white.
11
+ *
12
+ * FROZEN signatures (A3.8 #53). The geometry: a 12 x 8 grid of cell centres over the usable rectangle, below the
13
+ * scroll edge; a point's clearance is its distance to the nearest node's rect (`getBoundingClientRect`: transforms and
14
+ * animation included); the 16 with the most clearance that have the canvas surface under them are kept, with the
15
+ * camera (`canvasCtl.transform()`) for the bracket. **The camera at every animation frame of the bracket**: from
16
+ * `pick` to `verify` the shell records the camera once a frame (the frames a capture can have read), since a pan
17
+ * that turns back - the recorder's own pan is 60 wheel events one way and 60 the other, and main's bracket can last
18
+ * some 800 ms (150 + 500 + 150) - can sweep a node over a probe and back with the two ends the same (review of
19
+ * a3-native, minor #16). `verify` maps each point through the pick's camera and each recorded one, both ways: the
20
+ * world point under it at pick, drawn at that frame, and the world point under it at that frame, drawn as the camera
21
+ * was at pick. The second is the one that matters under a zoom - if the world point under the probe at a frame was,
22
+ * at the pick's camera, closer than the clearance, no node (each at least the clearance away then) covered it at that
23
+ * frame; under a zoom out a node's edge moves further than the probe's own world point, so the first alone does not
24
+ * say that. A point is valid when every frame's moves are under its clearance, it is still `VERIFY_MARGIN` (8 px)
25
+ * clear of every node now, and the surface is still under it. With no camera (no canvas) every point is invalid: the
26
+ * sample is inconclusive. A main thread stalled for the whole bracket records no frame between, and draws none
27
+ * either: the camera is the shell's. Nodes that move on the board themselves (a drag, a layout animation) are not the
28
+ * camera's and not covered by this.
29
+ */
30
+ import { PERF_BOUNDS, type PerfCam, type PerfMsg } from '../../shared/app-api.ts'
31
+ import { canvasCtl } from './canvas/ctl.ts'
32
+ import { VISIBLE_TOP } from './inset.ts'
33
+
34
+ /** At most this many probes a tick (the bridge refuses more than PERF_BOUNDS.points). */
35
+ export const MAX_PROBES = Math.min(16, PERF_BOUNDS.points)
36
+ /** Each probe's clearance from every node's screen rect, px. */
37
+ export const PROBE_CLEARANCE = 48
38
+ /** The candidate grid over the usable rectangle. */
39
+ export const PROBE_GRID: readonly [number, number] = [12, 8]
40
+ /** At `verify`, each kept point still this far from every node's rect, px (the design's margin). */
41
+ export const VERIFY_MARGIN = 8
42
+
43
+ const view = () => ({ w: innerWidth, h: innerHeight })
44
+ type Rect = { left: number; top: number; right: number; bottom: number }
45
+
46
+ /** The canvas surface itself: the zoom wrapper, its content or the world - never a frame, a caption, the chrome. */
47
+ export function isSurface(el: Element | null): boolean {
48
+ if (!el) return false
49
+ return el.id === 'sh-world' || el.classList.contains('sh-canvas') || el.classList.contains('sh-content')
50
+ }
51
+
52
+ /** A point's distance to the nearest rect (0 inside one); Infinity with none. */
53
+ export function clearance(x: number, y: number, rects: readonly Rect[]): number {
54
+ let d = Infinity
55
+ for (const r of rects) {
56
+ const dx = Math.max(r.left - x, 0, x - r.right)
57
+ const dy = Math.max(r.top - y, 0, y - r.bottom)
58
+ d = Math.min(d, Math.hypot(dx, dy))
59
+ if (d === 0) return 0
60
+ }
61
+ return d
62
+ }
63
+
64
+ /** Where the world point under (x, y) at camera a is drawn at camera b, `o` the canvas wrapper's client origin. */
65
+ export function moved(x: number, y: number, a: PerfCam, b: PerfCam, o: { x: number; y: number }): number {
66
+ const wx = (x - o.x - a.x) / a.s
67
+ const wy = (y - o.y - a.y) / a.s
68
+ return Math.hypot(o.x + b.x + wx * b.s - x, o.y + b.y + wy * b.s - y)
69
+ }
70
+
71
+ const nodeRects = (): Rect[] => [...document.querySelectorAll('.sh-node')].map((e) => e.getBoundingClientRect())
72
+ const origin = () => { const r = document.querySelector('.sh-canvas')?.getBoundingClientRect(); return { x: r?.left ?? 0, y: r?.top ?? 0 } }
73
+
74
+ /** The points a tick picked, its clearances, its camera and the camera at each frame since, for its `verify` (the last four ticks kept). */
75
+ const kept = new Map<number, { pts: [number, number][]; clear: number[]; cam: PerfCam | null; path: PerfCam[]; stop(): void }>()
76
+ /** The longest bracket recorded, in frames (5 s at 120 Hz): past it a verify finds the path cut, and says invalid. */
77
+ export const PATH_FRAMES = 600
78
+
79
+ /** The camera at each animation frame from now until `stop()`, or until it holds PATH_FRAMES (then the path is cut). */
80
+ function cameraPath(): { path: PerfCam[]; stop(): void } {
81
+ const path: PerfCam[] = []
82
+ let on = true
83
+ const step = () => {
84
+ if (!on) return
85
+ const c = canvasCtl.transform()
86
+ if (c) path.push({ ...c })
87
+ if (path.length >= PATH_FRAMES) { on = false; return }
88
+ requestAnimationFrame(step)
89
+ }
90
+ requestAnimationFrame(step)
91
+ return { path, stop: () => { on = false } }
92
+ }
93
+
94
+ /** The `before` answer for `tick`: the points chosen now, the camera and the viewport. */
95
+ export function pick(tick: number): Extract<PerfMsg, { kind: 'probes'; at: 'before' }> {
96
+ const top = VISIBLE_TOP
97
+ const w = innerWidth, h = Math.max(0, innerHeight - top)
98
+ const rects = nodeRects()
99
+ const [cols, rows] = PROBE_GRID
100
+ const cands: { p: [number, number]; c: number }[] = []
101
+ for (let j = 0; j < rows; j++) {
102
+ for (let i = 0; i < cols; i++) {
103
+ const x = Math.round((i + 0.5) * w / cols)
104
+ const y = Math.round(top + (j + 0.5) * h / rows)
105
+ const c = clearance(x, y, rects)
106
+ if (c < PROBE_CLEARANCE) continue
107
+ if (!isSurface(document.elementFromPoint(x, y))) continue
108
+ cands.push({ p: [x, y], c })
109
+ }
110
+ }
111
+ cands.sort((a, b) => b.c - a.c)
112
+ const chosen = cands.slice(0, MAX_PROBES)
113
+ const cam = canvasCtl.transform()
114
+ const run = cameraPath()
115
+ kept.get(tick)?.stop()
116
+ kept.set(tick, { pts: chosen.map((x) => x.p), clear: chosen.map((x) => Math.min(x.c, 1e6)), cam, path: run.path, stop: run.stop })
117
+ for (const k of [...kept.keys()]) if (kept.size > 4 && k !== tick) { kept.get(k)!.stop(); kept.delete(k) }
118
+ return { kind: 'probes', tick, at: 'before', points: chosen.map((x) => x.p), cam, view: view() }
119
+ }
120
+
121
+ /** The `after` answer for `tick`: one flag per point `pick(tick)` gave. */
122
+ export function verify(tick: number): Extract<PerfMsg, { kind: 'probes'; at: 'after' }> {
123
+ const k = kept.get(tick)
124
+ const cam = canvasCtl.transform()
125
+ if (!k) return { kind: 'probes', tick, at: 'after', valid: [], cam, view: view() }
126
+ kept.delete(tick)
127
+ const cut = k.path.length >= PATH_FRAMES
128
+ k.stop()
129
+ const rects = nodeRects()
130
+ const o = origin()
131
+ // every camera the bracket's frames showed, and the one now
132
+ const cams = cam ? [...k.path, cam] : []
133
+ const valid = k.pts.map(([x, y], i) => {
134
+ if (!k.cam || !cam || cut) return false
135
+ const c = k.clear[i]!
136
+ for (const at of cams) if (moved(x, y, k.cam, at, o) >= c || moved(x, y, at, k.cam, o) >= c) return false
137
+ if (clearance(x, y, rects) < VERIFY_MARGIN) return false
138
+ return isSurface(document.elementFromPoint(x, y))
139
+ })
140
+ return { kind: 'probes', tick, at: 'after', valid, cam, view: view() }
141
+ }
@@ -0,0 +1,205 @@
1
+ /**
2
+ * The contract between a canvas's shell and the Mac app (spec 28 A2.9, A2.14 #9, #18, #19, v1.12 r1 #1):
3
+ * the one place both sides read. The shell feature-detects `window.marverApp`; the app's canvas preload
4
+ * exposes it and its `bridge.ts` checks every payload against these bounds. Types and constants only - no
5
+ * imports - so the app's main bundle and the shell both take it as it is.
6
+ *
7
+ * Frozen before the streams split (A2.14 #32; A3's additions by A3.8 #53). The admission (v1.12 r1 #1) is the
8
+ * preload's and the bridge's alone: the shell never sees `doc` - `window.marverApp` is the same before and after
9
+ * admission, and A2.9's order (hello first, then theme, busy and menu) is all the shell owes.
10
+ *
11
+ * A3 (app 0.2, marver 0.27.2) adds, all feature-detected and `v` still 1 (A3.8 #10, #26, #27): `mv:doc` answers
12
+ * the document's `inset`; `mv:hello` says the inset the shell applied; `mv:present` / `mv:presented`, the
13
+ * presentation epochs of the one ground; `mv:perf` / `mv:perf-ask`, the recorder's traffic. Every new method of
14
+ * `MarverAppV1` is optional: a 0.27.2 shell inside app 0.1 still sees `marverApp` (marver-app.ts requires only the
15
+ * six 0.1 methods), and a shell trusts the inset only with the whole presentation contract (inset.ts).
16
+ */
17
+
18
+ export const APP_API_VERSION = 1
19
+
20
+ /** Reasons a page is busy (A2.14 #18). The first five are unsaved work; the last three are busy, not unsaved. */
21
+ export const UNSAVED_WHY = ['capture-recording', 'capture-unsent', 'board-unsaved', 'heights', 'typing'] as const
22
+ export const BUSY_ONLY_WHY = ['jam-session', 'microphone', 'agent'] as const
23
+ export type Why = (typeof UNSAVED_WHY)[number] | (typeof BUSY_ONLY_WHY)[number]
24
+ export const WHY: readonly Why[] = [...UNSAVED_WHY, ...BUSY_ONLY_WHY]
25
+
26
+ /** The strip's height: the top inset a shell applies under the Mac app's transparent strip (A2.9, A3.8 #31). */
27
+ export const TOP_INSET = 44
28
+ /** The scroll edge fades out over this many px below the inset (A2.9 v1.8 #8): `VISIBLE_TOP = TOP + EDGE_FADE`. */
29
+ export const EDGE_FADE = 16
30
+ /** What a document may apply: 44 only when main placed it full height (A3.8 #26). */
31
+ export type Inset = 0 | 44
32
+
33
+ /**
34
+ * `mv:hello` - sent first. `page` the shell's PAGE_ID, `version` from sh-config. `inset` (0.27.2): what the shell
35
+ * applied, 0 or 44; any other value refuses the message; absent (a 0.27.1 shell) reads 0 (A3.8 #26).
36
+ */
37
+ export interface Hello { version: string; board: string | null; page: string; inset?: Inset }
38
+ /** `mv:busy` - `busy` is any reason, `unsaved` any of UNSAVED_WHY; main refuses a message where they disagree. */
39
+ export interface Busy { busy: boolean; unsaved: boolean; why: Why[] }
40
+ /** `mv:theme` - the shell's `play || slides || viewTheme === 'dark'` (A2.14 #26). */
41
+ export interface Theme { dark: boolean }
42
+ /** `mv:menu` - at most 40, no separators in 0.1 (A2.7). */
43
+ export interface MenuItem { id: string; group: 'view' | 'jam'; label: string; hint?: string; checked?: boolean }
44
+ /** `mv:app-state` (main to canvas). `untrusted`: stop every microphone track (A2.14 #13). `open-next` is A4's. */
45
+ export type AppState = 'shown' | 'hidden' | 'untrusted'
46
+ /**
47
+ * `mv:doc` - the preload's one synchronous call at document start, answered at once on every path while untrusted,
48
+ * granting and moving nothing (A2.14 #9). `reopen`: the crash reload's, and an unloaded tab's reopen (A3.8 #43).
49
+ * `inset` (app 0.2, A3.8 #26): 44 when the document now committing is placed `full` (its pending layout, else the
50
+ * committed one), else 0; app 0.1 answers none, read as 0. There is no `mv:inset`.
51
+ */
52
+ export interface DocAnswer { reopen: boolean; inset?: Inset }
53
+ /** `mv:admit` (main to canvas) - the document admitted at its trusted commit (v1.12 r1 #1). */
54
+ export interface Admit { doc: string }
55
+ /** `mv:menu-click` (main to canvas). */
56
+ export interface MenuClick { id: string }
57
+ /**
58
+ * The ids main sends of its own, never in the page's `mv:menu`: the tab's right-click Mark All as Seen (A2.4's
59
+ * channels table: "Mark all as seen sends `mv:menu-click mark-all-seen` to the canvas"). A shell that does not know
60
+ * one does nothing with it.
61
+ */
62
+ export const APP_MENU_IDS = ['mark-all-seen'] as const
63
+
64
+ /**
65
+ * `mv:present` (main to canvas; on the wire `{ doc, ...Present }`, stamped by main like `mv:app-state`): show the
66
+ * latest state, then say so (A3.8 #27). `w`, `h`: the view's size in CSS px this request is about; `frames`: the
67
+ * animation frames to wait once the viewport has that size (main's tunable, 1-8, 2 to start). The shell waits until
68
+ * its viewport is `w x h` (500 ms at most), then `frames` animation frames, and answers; a newer request cancels an
69
+ * older wait, which is never answered.
70
+ */
71
+ export interface Present { epoch: number; w: number; h: number; frames: number }
72
+ /** `mv:presented` (canvas to main, stamped by the preload, never held): the request answered, at this viewport. */
73
+ export interface Presented { epoch: number; w: number; h: number }
74
+
75
+ /** A camera as the shell's probes read it: world offset and scale (canvasCtl.transform()). */
76
+ export interface PerfCam { x: number; y: number; s: number }
77
+ /** A viewport in CSS px. */
78
+ export interface PerfSize { w: number; h: number }
79
+
80
+ /**
81
+ * `mv:perf` (canvas to main; on the wire `{ doc, p }`, stamped by the preload with the admitted `doc`, never held
82
+ * or replayed: they are about now - A3.8 #10). `mem` and `shown` come from the preload by itself, so 0.27.0 and
83
+ * 0.27.1 canvases answer too; `gesture`, `probes` and `board` from a 0.27.2 shell.
84
+ * - `gesture`: perf.ts's begin and end (`on`), numbered (`seq`) - the white-out detector's window (A3.8 #15);
85
+ * - `probes`: the shell's answer to a probes ask (A3.8 #16): `before` lists up to 32 points in client px, `after`
86
+ * says which of them are still valid (moved by less than their clearance between the two answers);
87
+ * - `mem`: `process.getProcessMemoryInfo().private` and `getHeapStatistics()`, all in KB (A3.8 #5);
88
+ * - `shown`: the second animation-frame callback after a `shown` ask (A3.8 #9: a frame produced, not presented);
89
+ * - `board`: the board's frame count and how many sleep, at each commit (Copy Details, A3.8 #9).
90
+ */
91
+ export type PerfMsg =
92
+ | { kind: 'gesture'; on: boolean; seq: number; type?: 'pan' | 'zoom' | 'layout' }
93
+ | { kind: 'probes'; tick: number; at: 'before'; points: [number, number][]; cam: PerfCam | null; view: PerfSize }
94
+ | { kind: 'probes'; tick: number; at: 'after'; valid: boolean[]; cam: PerfCam | null; view: PerfSize }
95
+ | { kind: 'mem'; tick: number; privateKB: number; heapUsedKB: number; heapTotalKB: number }
96
+ | { kind: 'shown'; tick: number }
97
+ | { kind: 'board'; frames: number; asleep: number }
98
+
99
+ /**
100
+ * `mv:perf-ask` (main to canvas; on the wire `{ doc, ...PerfAsk }`). The preload answers `mem` and `shown` itself,
101
+ * keeps `display`'s rate for `perfInfo()`, and hands `probes` to the shell's `onPerfAsk` listeners (only the shell
102
+ * can answer them). An ask for another document is dropped.
103
+ */
104
+ export type PerfAsk =
105
+ | { kind: 'mem'; tick: number }
106
+ | { kind: 'shown'; tick: number }
107
+ | { kind: 'probes'; tick: number; at: 'before' | 'after' }
108
+ | { kind: 'display'; hz: number }
109
+ /** What reaches the shell's `onPerfAsk`. */
110
+ export type PerfProbeAsk = Extract<PerfAsk, { kind: 'probes' }>
111
+
112
+ /** The canvas channels. `mv:inset` is gone (A3.8 #26: `mv:doc` answers it); needs-you and capture are A4's. */
113
+ export const CANVAS_CHANNELS = {
114
+ doc: 'mv:doc',
115
+ admit: 'mv:admit',
116
+ hello: 'mv:hello',
117
+ theme: 'mv:theme',
118
+ busy: 'mv:busy',
119
+ menu: 'mv:menu',
120
+ appState: 'mv:app-state',
121
+ menuClick: 'mv:menu-click',
122
+ /** A3: the one ground's presentation epochs (A3.8 #27) */
123
+ present: 'mv:present',
124
+ presented: 'mv:presented',
125
+ /** A3: the recorder (A3.8 #10) */
126
+ perf: 'mv:perf',
127
+ perfAsk: 'mv:perf-ask',
128
+ } as const
129
+
130
+ /** Bounds main checks again (A2.14 #19): unknown fields are stripped, a known one of the wrong type or past its bound refuses the message. */
131
+ export const BOUNDS = {
132
+ version: 32,
133
+ versionChars: /^[0-9A-Za-z.+-]+$/,
134
+ board: 128,
135
+ page: /^[A-Za-z0-9_-]{8,64}$/,
136
+ doc: /^[A-Za-z0-9_-]{16,64}$/,
137
+ menuItems: 40,
138
+ menuId: /^[a-z][a-z0-9-]{0,31}$/,
139
+ label: 48,
140
+ hint: 8,
141
+ /** A3.8 #27: an epoch is an integer 0..epoch; a presentation viewport's sides are 0..viewport CSS px; `frames` 1..frames */
142
+ epoch: 2 ** 31 - 1,
143
+ viewport: 20_000,
144
+ frames: 8,
145
+ } as const
146
+
147
+ /**
148
+ * `mv:perf`'s bounds, checked by the bridge (A3.8 #10): unknown fields are stripped and a value past its bound
149
+ * refuses the message; past `perSecond` a second per webContents (a token bucket holding `burst`) a message is
150
+ * dropped and counted. Main's asks keep the same bounds.
151
+ */
152
+ export const PERF_BOUNDS = {
153
+ /** tick and seq: integers 0..counter */
154
+ counter: 2 ** 31 - 1,
155
+ points: 32,
156
+ coord: 20_000,
157
+ kb: 1e9,
158
+ frames: 1_000_000,
159
+ hz: { min: 1, max: 1000 },
160
+ perSecond: 30,
161
+ burst: 64,
162
+ } as const
163
+
164
+ /**
165
+ * `window.marverApp`, exposed by the canvas preload to verified local canvases. Typed methods only: a page never
166
+ * names a channel. The six methods of 0.1 are required (marver-app.ts checks them); every A3 one is optional.
167
+ */
168
+ export interface MarverAppV1 {
169
+ readonly v: 1
170
+ /**
171
+ * 0 in app 0.1; 0 or 44 from app 0.2: the inset this document must apply, for its whole life (`mv:doc`'s
172
+ * answer). A shell applies 44 only when `onPresent` and `presented` exist too (inset.ts, A3.8 #31).
173
+ */
174
+ readonly topInset: Inset
175
+ /** the app reloaded this tab after a crash, or reopens it after an unload: restore the saved camera even when the link names a selection (A2.9, A3.8 #43) */
176
+ readonly reopen: boolean
177
+ hello(p: Hello): void
178
+ theme(p: Theme): void
179
+ busy(p: Busy): void
180
+ menu(items: MenuItem[]): void
181
+ onAppState(fn: (s: AppState) => void): () => void
182
+ onMenuClick(fn: (p: MenuClick) => void): () => void
183
+ /** A3 (app 0.2): main's presentation requests for this document */
184
+ onPresent?(fn: (r: Present) => void): () => void
185
+ /** A3 (app 0.2): the answer to a presentation request, sent at once */
186
+ presented?(p: Presented): void
187
+ /** A3 (app 0.2): a recorder message (gesture, probes, board); the preload sends mem and shown itself */
188
+ perf?(p: PerfMsg): void
189
+ /** A3 (app 0.2): main's probe asks (the white-out detector, A3.8 #16) */
190
+ onPerfAsk?(fn: (a: PerfProbeAsk) => void): () => void
191
+ /** A3 (app 0.2): the display's refresh rate from main's `display` ask, null until one came; the shell puts it on its gesture records */
192
+ perfInfo?(): { hz: number | null }
193
+ }
194
+
195
+ /** Main's words for a reason (the hang sheet, the unsaved pill); `heights` is never named (A2.14 #18). */
196
+ export const WHY_WORDS: Record<Why, string | null> = {
197
+ 'capture-recording': 'a capture being recorded',
198
+ 'capture-unsent': 'a capture not yet sent',
199
+ 'board-unsaved': 'edits not yet saved',
200
+ heights: null,
201
+ typing: 'words not yet sent',
202
+ 'jam-session': 'a Jam session',
203
+ microphone: 'the microphone',
204
+ agent: 'an agent at work',
205
+ }
@@ -0,0 +1,308 @@
1
+ /**
2
+ * The app half of the recorder, on disk and in memory (spec 28 A3.1, A3.8 #4-#9, #13, #16, #45, #48, #49): the
3
+ * one schema the Mac app writes into `~/.marver/perf/app.jsonl` (Marver Dev: `app-dev.jsonl`) and the CLI reads
4
+ * (`marver perf --crashes`, `--flashes`, `--machine`), and the sampler's shapes `memory.ts` and the budgets read.
5
+ * Types, constants and one pure reader only - no imports - so the app's main bundle, the CLI and the test harness
6
+ * all take it as it is.
7
+ *
8
+ * FROZEN before the A3 streams split (A3.8 #53). Owners: the recorder stream writes the envelope and most kinds;
9
+ * the unloading stream writes `pressure`, `unload`, `unload-skip`, `unload-effect` and `reopen` through
10
+ * `recorder.event`; the one-ground stream writes `cover`; the flash stream writes `flash` and
11
+ * `whiteout-candidate`. A kind's body grows only by optional fields; a field's meaning never changes.
12
+ *
13
+ * Units, said once: every `...MB` is MiB (KB / 1024 once per process, A3.8 #4); `cpu` is cores (Δ
14
+ * `cumulativeCPUUsage` / Δ monotonic seconds, never `percentCPUUsage`); times are epoch ms (`ts`, `at`) or
15
+ * monotonic ms (`mono`); a process is `(pid, born)`, `born` its `creationTime` - a reused pid is a new process.
16
+ * `gpuProcessRssMB` is the GPU process's working set, never "GPU memory" (Codex r1 #19); the app never reads a
17
+ * footprint about itself (A3.8 #2) - the budgets read footprint from outside.
18
+ */
19
+
20
+ // ---- the line --------------------------------------------------------------------------------------------------
21
+
22
+ /** Which build wrote a line: the release (`app.jsonl`) or Marver Dev (`app-dev.jsonl`). One writer per file (A3.8 #12). */
23
+ export type Flavour = 'release' | 'dev'
24
+ /** The file each flavour writes, under `<MARVER_HOME>/perf/`. */
25
+ export const APP_LOG: Record<Flavour, string> = { release: 'app.jsonl', dev: 'app-dev.jsonl' }
26
+
27
+ /**
28
+ * The record kinds (A3.8 #8). `main-error` is app 0.1's (errors.ts), kept so a 0.1 line still parses once the
29
+ * recorder stamps it with the envelope.
30
+ */
31
+ export const APP_KINDS = [
32
+ 'start', 'sample', 'agx', 'gone', 'child-gone', 'gpu-restart', 'unresponsive', 'responsive', 'gpu', 'power',
33
+ 'tab', 'shown', 'pressure', 'unload', 'unload-skip', 'unload-effect', 'reopen', 'cover', 'flash',
34
+ 'whiteout-candidate', 'dropped', 'main-error',
35
+ ] as const
36
+ export type AppKind = (typeof APP_KINDS)[number]
37
+
38
+ /** Every line (A3.8 #8). `app`: a random id per launch (12 hex); `seq`: counted per launch from 0, contiguous; `machine`: the profile hash in force, null only when none could be made in 3 s. */
39
+ export interface AppEnvelope {
40
+ v: 1
41
+ ts: number
42
+ kind: AppKind
43
+ app: string
44
+ seq: number
45
+ flavour: Flavour
46
+ machine: string | null
47
+ }
48
+
49
+ /**
50
+ * A record about a tab carries its identity, captured in the event's turn before any await (A3.8 #8). `page` is the
51
+ * one the admitted document's accepted `mv:hello` sent; a document that has not said hello has none, and never gets
52
+ * the next document's. `commit` is the tab's commit count (tabs.ts `doc.commits`).
53
+ */
54
+ export interface TabIdent { tab: string; ws?: string; commit?: number; page?: string }
55
+
56
+ /** A process, as the budgets and `--crashes` name it. */
57
+ export interface ProcId { pid: number; born: number }
58
+
59
+ // ---- the sampler (A3.8 #4-#6): what memory.ts, a flash and the budgets read -----------------------------------
60
+
61
+ export type ProcType = 'browser' | 'gpu' | 'utility' | 'renderer' | 'other'
62
+ /** A renderer's role: the page kind it hosts ('mixed': two app-page kinds; 'cover': S15's variant 3); every other process 'none'. */
63
+ export type Role = 'canvas' | 'strip' | 'home' | 'settings' | 'tabpage' | 'cover' | 'mixed' | 'none' | 'unknown'
64
+ /** Electron's `powerMonitor.getCurrentThermalState()`. */
65
+ export type ThermalState = 'unknown' | 'nominal' | 'fair' | 'serious' | 'critical'
66
+
67
+ /** `kern.memorystatus_vm_pressure_level`: 1 normal, 2 warn, 4 critical. */
68
+ export type PressureLevel = 1 | 2 | 4
69
+ /** One pressure read (A3.8 #6): `level` null is unknown (a failed, timed-out or other answer) - never normal, never acted on. */
70
+ export interface PressureReading {
71
+ level: PressureLevel | null
72
+ /** `kern.memorystatus_level`, 0-100: recorded, not acted on */
73
+ availablePct: number | null
74
+ /** epoch ms of the read */
75
+ at: number
76
+ }
77
+
78
+ export interface ProcSample {
79
+ pid: number
80
+ /** creationTime; with pid, the key */
81
+ born: number
82
+ type: ProcType
83
+ /** Electron's `name` (utility processes) */
84
+ name?: string
85
+ role: Role
86
+ /** the tabs with any frame in it (a canvas renderer shared by two tabs lists both; its out-of-process iframes count for their tab) */
87
+ tabs: string[]
88
+ /** cores; null on a process's first sample and the first after a resume */
89
+ cpu: number | null
90
+ rssMB: number
91
+ /** canvas renderers: the preload's footprint (`private`), at most 10 s old (A3.8 #5); else null - RSS stands in */
92
+ footprintMB: number | null
93
+ }
94
+
95
+ export interface Sample {
96
+ /** epoch ms */
97
+ ts: number
98
+ /** monotonic ms (performance.now()) */
99
+ mono: number
100
+ /** monotonic s since the previous sample; null for the first and after a resume */
101
+ dt: number | null
102
+ /** every unique process; a process is counted once in any sum */
103
+ procs: ProcSample[]
104
+ gpu: { pid: number; born: number; cpu: number | null; gpuProcessRssMB: number } | null
105
+ /** read only while recording or while a hidden tab could be unloaded (A3.8 #6); null when not read */
106
+ pressure: PressureReading | null
107
+ thermal: ThermalState
108
+ /** process.getSystemMemoryInfo(), KB to MB */
109
+ sys: { freeMB: number; purgeableMB: number } | null
110
+ /** the visible tab's last `mem` answer, at most 10 s old */
111
+ visible: (TabIdent & { privateMB: number; heapMB: number; at: number }) | null
112
+ }
113
+
114
+ /**
115
+ * The one sampler, two consumers (A3.8 #4): `recorder.ts` owns the only `getAppMetrics()` loop, every 5 s, while
116
+ * recording or while `wantPressure()` says an unload is possible; with the recorder off it runs only for
117
+ * `memory.ts` and writes nothing.
118
+ */
119
+ export interface Sampler {
120
+ /** every sample, as it is published (after its pressure read ended) */
121
+ onSample(fn: (s: Sample) => void): () => void
122
+ /** memory.ts: asked at every tick - true while some hidden tab could be unloaded (A3.8 #6); it also keeps the tick alive with the recorder off */
123
+ wantPressure(fn: () => boolean): void
124
+ /** one extra sample now, on the same baselines (an unload's "after", A3.8 #45) */
125
+ requestSample(): Promise<Sample>
126
+ /** the last sample published, or null */
127
+ last(): Sample | null
128
+ }
129
+
130
+ /** The GPU process's identity: `getAppMetrics()`'s `GPU` entry (A3.8 #27, r3 #1). A change, or none, is a loss. */
131
+ export type GpuIdentity = ProcId
132
+
133
+ // ---- bodies -----------------------------------------------------------------------------------------------------
134
+
135
+ /** mean, max and last over a window; null when nothing was read */
136
+ export interface Agg { mean: number | null; max: number | null; last: number | null }
137
+
138
+ /** One minute of 5 s samples (A3.8 #7): CPU exact over the minute (Δ cumulative / Δ monotonic), memory as mean, max and last. */
139
+ export interface SampleBody {
140
+ /** ms covered, and the samples folded in */
141
+ span: number
142
+ n: number
143
+ pressure: { last: PressureLevel | null; max: PressureLevel | null }
144
+ thermal: ThermalState
145
+ /** every unique process seen in the minute (the CPU budget joins by pid and a start time within 1 s of `born`, A3.8 #49) */
146
+ procs: {
147
+ pid: number; born: number; type: ProcType; role: Role; name?: string; tabs: string[]; cpu: Agg; rssMB: Agg; footprintMB: Agg
148
+ /** the core-seconds the process used in the minute (Δ cumulative) and the monotonic ms they cover: `cpu.mean` is s / (ms / 1000); absent with no CPU interval (added by the recorder stream, optional) */
149
+ cpuTime?: { s: number; ms: number }
150
+ }[]
151
+ gpu: { pid: number; born: number; cpu: Agg; gpuProcessRssMB: Agg } | null
152
+ /**
153
+ * canvas memory (A3.8 #41): Σ over unique canvas processes of footprintMB, else rssMB. `byTab` is each tab's own
154
+ * processes; `shared` (added by the recorder stream, optional) marks a tab whose renderer another tab shared in the
155
+ * minute - that renderer is whole in both tabs' entries, so byTab is never added up (`memMB` counts it once)
156
+ */
157
+ canvases: { memMB: Agg; byTab: Record<string, { memMB: Agg; cpu: Agg; shared?: true }> }
158
+ visible: Sample['visible']
159
+ sys: Sample['sys']
160
+ /** wall ms of this minute's sysctl / ioreg spawns: the recorder's own cost */
161
+ spawnMs: number
162
+ }
163
+
164
+ /** `ioreg -rc AGXAccelerator -d1`, machine-wide (A3.1, A3.8 #9): a missing key is 'unknown'. */
165
+ export interface AgxReading {
166
+ gpuSystemMemoryMB: number | 'unknown'
167
+ allocMB: number | 'unknown'
168
+ utilPct: number | 'unknown'
169
+ rendererPct: number | 'unknown'
170
+ tilerPct: number | 'unknown'
171
+ recoveryCount: number | 'unknown'
172
+ machineWide: true
173
+ }
174
+
175
+ export type UnloadReason = 'warn' | 'critical' | 'half-ram'
176
+ /** An unload's before and after figures (A3.8 #45). */
177
+ export interface UnloadFigures {
178
+ level: PressureLevel | null
179
+ availablePct: number | null
180
+ /** Σ canvas memory (A3.8 #41) */
181
+ canvasMB: number | null
182
+ /** the tab's own processes, unique */
183
+ tab: { pids: number[]; memMB: number | null }
184
+ gpuProcessRssMB: number | null
185
+ }
186
+
187
+ /** Why a flash's picture is missing (A3.8 #13). */
188
+ export type PictureWhy = 'window hidden' | 'timeout' | 'empty' | 'write failed' | 'quit' | 'no window'
189
+
190
+ /** A record held in the ring, as a flash quotes it: its kind, its time and its body. */
191
+ export type RingEvent = { kind: AppKind; ts: number } & Record<string, unknown>
192
+
193
+ export interface AppBodies {
194
+ start: { version: string; electron: string; chrome: string; recorder: boolean; pid: number }
195
+ sample: SampleBody
196
+ agx: AgxReading
197
+ /** a renderer ended (A3.8 #9): `ours` when main was ending it (an unload, Reload Page); an unload writes its own at `destroyed`, `source: 'unload'` */
198
+ gone: Partial<TabIdent> & { role: Role; pid: number; born: number; reason: string; exitCode: number; ours: boolean; source?: 'unload' | 'reload-page'; pressure: PressureLevel | null }
199
+ /** the GPU or a utility process ended; never ours */
200
+ 'child-gone': { type: string; name?: string; reason: string; exitCode: number; ours: false; machineWide: false }
201
+ /** a new GPU process with no child-gone within 2 s (A3.8 #9) */
202
+ 'gpu-restart': { pid: number; born: number; was: ProcId | null }
203
+ unresponsive: Partial<TabIdent> & { role: Role; pid: number; born: number }
204
+ responsive: Partial<TabIdent> & { role: Role; pid: number; born: number }
205
+ /** gpu-info-update whose getGPUFeatureStatus() changed */
206
+ gpu: { featureStatus: Record<string, string> }
207
+ power: { event: 'on-ac' | 'on-battery' | 'suspend' | 'resume' | 'thermal-state-change' | 'speed-limit-change'; thermal?: ThermalState; limit?: number }
208
+ /**
209
+ * a change of the tab's display state, active flag, view state, document commit count or main frame (A3.8 #9,
210
+ * r4 #1), diffed after each compose. `state` is tabs.ts's DisplayState, `view` its TabViewState.
211
+ */
212
+ tab: TabIdent & { state: string; active: boolean; view: string; main: ProcId | null }
213
+ /**
214
+ * main's show to main's receipt of the preload's answer from its second animation-frame callback, on tab switches
215
+ * only (A3.8 #9): the answer's IPC back to main is in it
216
+ */
217
+ shown: TabIdent & { ms: number }
218
+ /** memory.ts: a change of level (A3.8 #45) */
219
+ pressure: { level: PressureLevel | null; availablePct: number | null; was: PressureLevel | null }
220
+ /** `forced`: Force Quit Tab on a quit's stuck sheet (app 0.2 code review r2 #1) - the view taken out by hand, never a completed unload */
221
+ unload: TabIdent & { phase: 'start' | 'unsure' | 'done' | 'forced' | 'refused'; reason: UnloadReason; why?: string; before?: UnloadFigures }
222
+ /** once per tab and reason in each pressure episode (A3.8 #45); `why` an UnloadRefusal */
223
+ 'unload-skip': TabIdent & { reason: UnloadReason; why: string }
224
+ /** 5 s after an unload (A3.8 #45) */
225
+ 'unload-effect': TabIdent & { reason: UnloadReason; before: UnloadFigures; after: UnloadFigures; pidGone: boolean }
226
+ /** written at the reopened document's accepted hello, or its next document or 30 s after its lift with no page (A3.8 #45) */
227
+ reopen: TabIdent & { activateToLiftMs: number; unloadedForMs: number }
228
+ /** a presentation epoch's outcome (A3.8 #27; the one-ground stream's tuning record) */
229
+ cover: TabIdent & {
230
+ epoch: number
231
+ cause: 'doc' | 'size' | 'show' | 'fullscreen' | 'hello' | 'resize' | 'gpu'
232
+ outcome: 'uncovered' | 'mismatch' | 'superseded' | 'never'
233
+ /** ms from the epoch's start: sent, answered, uncovered */
234
+ sentMs?: number
235
+ answeredMs?: number
236
+ uncoveredMs?: number
237
+ /**
238
+ * ms from the epoch's start to when it ended because its view stopped showing - another tab or an app page, a tab
239
+ * page over it, its document no longer presentable, the window hidden, the app quitting; absent when a newer key
240
+ * superseded it while shown. A hidden view draws no frames: its silence after this is not the page's
241
+ */
242
+ hiddenMs?: number
243
+ frames: number
244
+ uncoverDelayMs: number
245
+ }
246
+ /** Mark a Flash (A3.3, A3.8 #13, #14): written once the picture settled, the AGX read ended and the +1 s GPU window closed */
247
+ flash: Partial<TabIdent> & {
248
+ id: string
249
+ via: 'key' | 'menu'
250
+ recorder: boolean
251
+ /** the ring, only with the recorder on: the last 12 samples and 60 s of events */
252
+ ring: { samples: Sample[]; events: RingEvent[] } | null
253
+ /** the state at the mark: one getAppMetrics(), in the mark's turn - its `ts` is the mark's time, which the CLI dates the mark by (the line's own `ts` is when it was written, about mark + 2 s) */
254
+ now: Sample
255
+ /** GPU process events from 1 s before the mark to 1 s after it */
256
+ gpuEvents: RingEvent[]
257
+ thermal: ThermalState
258
+ pressure: PressureReading | null
259
+ featureStatus: Record<string, string>
260
+ agx: AgxReading
261
+ /** `flashes/<id>.png` under perf/, or null with `pictureWhy` */
262
+ picture: string | null
263
+ pictureWhy?: PictureWhy
264
+ }
265
+ /** two completed white samples at consecutive ticks (A3.8 #16): white at `observedAt` only, nothing between them */
266
+ 'whiteout-candidate': TabIdent & {
267
+ gesture: number
268
+ observedAt: number[]
269
+ rateHz: 4 | 2
270
+ samples: number
271
+ skipped: number
272
+ inconclusive: number
273
+ gpuEvents: RingEvent[]
274
+ agx: AgxReading
275
+ }
276
+ /** the writer's queue overflowed (2,000 lines): how many went */
277
+ dropped: { n: number }
278
+ /** app 0.1's error policy (errors.ts) */
279
+ 'main-error': { what: 'exception' | 'rejection'; name: string; message: string; stack: string[] }
280
+ }
281
+
282
+ /** A kind's body alone (what `recorder.event` and the writer take; the writer adds the envelope). */
283
+ export type AppBody<K extends AppKind> = AppBodies[K]
284
+ /** One line of app.jsonl. */
285
+ export type AppRecord = { [K in AppKind]: AppEnvelope & { kind: K } & AppBodies[K] }[AppKind]
286
+
287
+ // ---- the reader -------------------------------------------------------------------------------------------------
288
+
289
+ const KINDS = new Set<string>(APP_KINDS)
290
+ const isInt = (v: unknown): v is number => typeof v === 'number' && Number.isInteger(v) && v >= 0
291
+
292
+ /**
293
+ * One line of app.jsonl, or null (A3.5): the envelope checked - `v: 1`, a finite `ts`, a known `kind`, an `app` id,
294
+ * a whole `seq`, a `flavour`, a `machine` hash or null. The body is the writer's and is passed on as it is: a
295
+ * reader takes the fields it knows. A line without the envelope (app 0.1's main-error lines) is null.
296
+ */
297
+ export function parseAppLine(line: string): AppRecord | null {
298
+ let r: unknown
299
+ try { r = JSON.parse(line) } catch { return null }
300
+ if (!r || typeof r !== 'object' || Array.isArray(r)) return null
301
+ const o = r as Record<string, unknown>
302
+ if (o.v !== 1 || typeof o.ts !== 'number' || !Number.isFinite(o.ts)) return null
303
+ if (typeof o.kind !== 'string' || !KINDS.has(o.kind)) return null
304
+ if (typeof o.app !== 'string' || !/^[0-9a-f]{12}$/.test(o.app) || !isInt(o.seq)) return null
305
+ if (o.flavour !== 'release' && o.flavour !== 'dev') return null
306
+ if (o.machine !== null && (typeof o.machine !== 'string' || !/^[0-9a-f]{16}$/.test(o.machine))) return null
307
+ return o as unknown as AppRecord
308
+ }