@marver-design/marver 0.29.0 → 0.30.1

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 (76) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +2 -1
  3. package/dist/{anchor-check-DhlpKl2K.mjs → anchor-check-Bv4o-R2T.mjs} +1 -1
  4. package/dist/{build-CWbrb2bl.mjs → build-zWGXSzly.mjs} +5 -4
  5. package/dist/cli.mjs +5 -5
  6. package/dist/{daemon-Sc_z8gT6.mjs → daemon-CChgWJNq.mjs} +2 -2
  7. package/dist/{dev-DWBKQhxf.mjs → dev-DOgIITpT.mjs} +8 -8
  8. package/dist/{perf-Denssrko.mjs → perf-6MOTHxay.mjs} +710 -99
  9. package/dist/perf-BCxAo0IS.mjs +1743 -0
  10. package/dist/{plugin-DqoZB-D6.mjs → plugin-CFWBcAba.mjs} +928 -539
  11. package/dist/{poster-CrsjqhY4.mjs → poster-DPPpQiva.mjs} +1 -1
  12. package/dist/{publish-bakes-DW-NDgU2.mjs → publish-bakes-_Zx8crP3.mjs} +2 -2
  13. package/dist/{recover-GtJ9UDAB.mjs → recover-mDUVsnPd.mjs} +1 -1
  14. package/dist/{shot-T04Ixrvq.mjs → shot-d4h_hJi9.mjs} +3 -3
  15. package/docs/app.md +194 -0
  16. package/docs/performance.md +100 -19
  17. package/package.json +1 -1
  18. package/src/client/frame-host/bridge.js +17 -8
  19. package/src/client/frame-host/inplace.ts +124 -0
  20. package/src/client/frame-host/inspect.d.ts +1 -0
  21. package/src/client/frame-host/inspect.js +13 -4
  22. package/src/client/frame-host/main.tsx +12 -3
  23. package/src/client/frame-host/messages.ts +85 -0
  24. package/src/client/frame-host/signals.d.ts +15 -0
  25. package/src/client/frame-host/signals.js +219 -0
  26. package/src/client/recorder-level.ts +41 -0
  27. package/src/client/shell/App.tsx +158 -88
  28. package/src/client/shell/BoardList.tsx +103 -48
  29. package/src/client/shell/Comments.tsx +66 -42
  30. package/src/client/shell/ContextMenu.tsx +3 -2
  31. package/src/client/shell/JamSurface.tsx +116 -71
  32. package/src/client/shell/LockedApp.tsx +19 -3
  33. package/src/client/shell/Play.tsx +94 -58
  34. package/src/client/shell/StatusPicker.tsx +19 -9
  35. package/src/client/shell/Toolbar.tsx +15 -7
  36. package/src/client/shell/api.ts +18 -4
  37. package/src/client/shell/app-bridge.ts +12 -6
  38. package/src/client/shell/app-perf.ts +31 -1
  39. package/src/client/shell/canvas/Canvas.tsx +17 -6
  40. package/src/client/shell/canvas/FrameNode.tsx +25 -12
  41. package/src/client/shell/canvas/Sticky.tsx +4 -2
  42. package/src/client/shell/canvas/ctl.ts +2 -0
  43. package/src/client/shell/canvas/ready-watch.ts +4 -0
  44. package/src/client/shell/canvas/sleep.ts +2 -0
  45. package/src/client/shell/canvas/updates.ts +13 -6
  46. package/src/client/shell/commands.ts +765 -0
  47. package/src/client/shell/comments-store.ts +42 -27
  48. package/src/client/shell/goto.ts +11 -6
  49. package/src/client/shell/jam-keys.ts +141 -75
  50. package/src/client/shell/jam-lane.tsx +19 -12
  51. package/src/client/shell/jam-panel.tsx +61 -48
  52. package/src/client/shell/jam-session.tsx +41 -37
  53. package/src/client/shell/jam-state.ts +9 -1
  54. package/src/client/shell/jam-surface-parts.tsx +8 -6
  55. package/src/client/shell/jam-ui.tsx +9 -6
  56. package/src/client/shell/jam-voice.ts +4 -2
  57. package/src/client/shell/main.tsx +7 -1
  58. package/src/client/shell/marks-ui.tsx +11 -0
  59. package/src/client/shell/perf.ts +51 -5
  60. package/src/client/shell/recorder-core.ts +4 -1
  61. package/src/client/shell/recorder-hmr.ts +36 -0
  62. package/src/client/shell/recorder-reloads.ts +264 -0
  63. package/src/client/shell/recorder-seams.ts +116 -0
  64. package/src/client/shell/recorder-self.ts +73 -0
  65. package/src/client/shell/recorder-signals-core.ts +139 -0
  66. package/src/client/shell/recorder-signals.ts +485 -0
  67. package/src/client/shell/recorder.ts +118 -43
  68. package/src/client/shell/store.ts +112 -32
  69. package/src/client/shell/whiteout-probes.ts +3 -1
  70. package/src/client/stage/main.tsx +10 -5
  71. package/src/shared/app-api.ts +28 -6
  72. package/src/shared/app-perf.ts +99 -6
  73. package/src/shared/app-report.ts +586 -0
  74. package/src/shared/perf-records.ts +445 -0
  75. package/src/shared/perf-run.ts +6 -2
  76. package/dist/perf-jam-CLkERSHo.mjs +0 -642
@@ -0,0 +1,586 @@
1
+ /**
2
+ * The performance report (spec 28 A5.1 #26, #27; r1 #9, r2 #4, r3 #5): `PerfReport` v1, the one file Help > Export
3
+ * Performance Report… and the crashed tab page's latched state write (`app/src/main/report.ts`). Pure: the types, each
4
+ * record kind's projection, each value's rule and every aggregation, so the app's main bundle and the tests take it
5
+ * as it is. It imports only `app-perf.ts`'s constants and types.
6
+ *
7
+ * **An allowlist, never a filter.** A record is never exported whole: each kind lists the fields it may carry
8
+ * (nested objects field by field, `PROJECTIONS`), each with its rule. Anything unlisted is dropped. A string that
9
+ * fails its rule becomes `other` (a featureStatus value `unknown`, its key dropped); a number that is not finite is
10
+ * dropped, and so is any value of the wrong type; `null` stays where the record's schema has it (an unknown reading).
11
+ * A line of an unknown kind is counted, never exported; `tab` lines are counted, never listed; `sample` and `shown`
12
+ * lines are folded (below). Every string that leaves is one of the sets below, a pattern of at most 32 characters, or
13
+ * a version. **Never**: `ws`, `page` or `origin`; file paths, board or canvas names, hosts or URLs; error messages or
14
+ * stacks; process names, pids or creation times; pictures or their paths; flash ids, the ring, traces or dumps; the
15
+ * envelope's launch id, `seq` and profile hash.
16
+ *
17
+ * **Sources and bounds** (#26): `~/.marver/perf/` only - this flavour's log, the machine profiles its lines name and
18
+ * `crashpad/` as counts - over the last 7 days, or fewer if `keepPerfDays` keeps fewer. Lines outside the window are
19
+ * skipped by their envelope's `ts`. Out: one JSON file of at most 2 MB (`REPORT_MAX_BYTES`), events newest first and
20
+ * at most 2,000 of them, samples folded to one row per UTC hour. Each section says `ok`, `missing`, `unreadable` or
21
+ * `partial`, with the count of lines that did not parse (attributed by the kind a torn line still names, else to the
22
+ * events); a section is never silently empty: `partial` also when a bound cut something, with the count it cut.
23
+ *
24
+ * **What it cannot hold: the app's own memory footprint** (r1 #9). The recorder keeps a footprint only for canvas
25
+ * renderers and the budgets read the app's from outside (A3.8 #2); the report gives the app's own processes' resident
26
+ * memory, `ownRssMB`, never called a footprint.
27
+ *
28
+ * Units: MiB to one decimal place, cores to three, seconds to one decimal place; times are epoch ms; hours and days
29
+ * are UTC, named by their first ms.
30
+ *
31
+ * FROZEN (A5.1 #41): `PerfReport` v1, `PROJECTIONS` and the value sets. A kind's projection grows only by optional
32
+ * fields in a new version; a value set grows when the recorder's own set does (an unlisted value is `other` meanwhile).
33
+ */
34
+ import { APP_KINDS, UPDATE_MOVE_WHY, type AppKind, type Flavour, type PressureLevel, type Role, type ThermalState, type UpdateBody } from './app-perf.ts'
35
+
36
+ // ---- bounds -------------------------------------------------------------------------------------------------------
37
+
38
+ export const REPORT_V = 1 as const
39
+ /** the window: the last 7 days, or fewer if `keepPerfDays` keeps fewer (#26) */
40
+ export const REPORT_DAYS = 7
41
+ /** the file, whole (#26): past it the oldest events go first, counted in `events.cut` */
42
+ export const REPORT_MAX_BYTES = 2 * 1024 * 1024
43
+ /** events, newest first (#26) */
44
+ export const REPORT_EVENTS_MAX = 2000
45
+ /** the distinct profiles read, the most recently named first; past it counted in `mac.cut` */
46
+ export const REPORT_PROFILES_MAX = 20
47
+ /** a profile's displays kept */
48
+ export const REPORT_DISPLAYS_MAX = 16
49
+ /** the longest string a pattern admits */
50
+ export const REPORT_STRING_MAX = 32
51
+ const HOUR = 3_600_000
52
+ const DAY = 86_400_000
53
+
54
+ /** The window's days for a `keepPerfDays` (perflog.ts's rule: 1-90, else 14), at most REPORT_DAYS. */
55
+ export function reportDays(keepPerfDays: unknown): number {
56
+ const d = Number(keepPerfDays)
57
+ const kept = Number.isFinite(d) && d >= 1 ? Math.min(90, Math.round(d)) : 14
58
+ return Math.min(REPORT_DAYS, kept)
59
+ }
60
+
61
+ // ---- PerfReport v1 ------------------------------------------------------------------------------------------------
62
+
63
+ export type SectionStatus = 'ok' | 'missing' | 'unreadable' | 'partial'
64
+
65
+ /** The Mac (#27), from a profile's `host` and `displays` only: never the GPU's renderer string, a display's id or colour space. */
66
+ export interface MacRow {
67
+ /** the first and the last line in the window naming a profile this row came from (two profiles alike give one row) */
68
+ from: number
69
+ to: number
70
+ chip?: string
71
+ cores?: { total?: number; p?: number | 'unknown' | 'other'; e?: number | 'unknown' | 'other' }
72
+ memGB?: number
73
+ model?: string
74
+ macos?: string
75
+ /** Electron's `scaleFactor` and `displayFrequency` (the profile's `hz`); a headless profile has none */
76
+ displays: { scaleFactor?: number; displayFrequency?: number }[]
77
+ }
78
+ export interface MacSection {
79
+ status: SectionStatus
80
+ /** named profiles that could not be read or parsed */
81
+ unparsed: number
82
+ /** named profiles with no file */
83
+ absent: number
84
+ /** named profiles past REPORT_PROFILES_MAX, not read */
85
+ cut: number
86
+ /** the most recently named first */
87
+ rows: MacRow[]
88
+ }
89
+
90
+ /**
91
+ * One UTC hour of `sample` lines (r2 #4, r3 #5), each a minute the recorder folded with `SampleBody.own`. `ownCpu` is
92
+ * observed CPU, in cores, over the seconds fully measured (Σ s / (Σ ms / 1000)); `ownCpuMaxMinute` the highest
93
+ * minute's s over its ms; `measuredS` and `unmeasuredS` say how much was measured, so an unmeasured stretch is
94
+ * unknown, never idle. `ownRssMB`: the minutes' `mean` weighted by their `n`, and the max of their `max`. A line from
95
+ * before `own` gives neither figure and counts in `minutesMissing`. `canvasMemMB`: the max of `canvases.memMB.max`;
96
+ * `gpuRssMB`: the max of `gpu.gpuProcessRssMB.max`; `pressureMax`: the highest level; `thermalWorst`: the worst
97
+ * state (`unknown` with none known); `minutes`: the lines.
98
+ */
99
+ export interface HourRow {
100
+ hour: number
101
+ minutes: number
102
+ minutesMissing: number
103
+ ownCpu: number | null
104
+ ownCpuMaxMinute: number | null
105
+ measuredS: number
106
+ unmeasuredS: number
107
+ ownRssMB: { mean: number | null; max: number | null }
108
+ canvasMemMB: number | null
109
+ gpuRssMB: number | null
110
+ pressureMax: PressureLevel | null
111
+ thermalWorst: ThermalState
112
+ }
113
+ export interface SamplesSection { status: SectionStatus; unparsed: number; lines: number; rows: HourRow[] }
114
+
115
+ /** `shown` folded to each UTC day (#27): how many, and the 50th and 95th percentiles by nearest rank. */
116
+ export interface ShownDay { day: number; n: number; p50Ms: number; p95Ms: number }
117
+ export interface ShownSection { status: SectionStatus; unparsed: number; lines: number; days: ShownDay[] }
118
+
119
+ /** An exported event: its time, its kind and its projection (`PROJECTIONS`), in that order. */
120
+ export type ReportEvent = { ts: number; kind: ExportedKind } & Record<string, unknown>
121
+ export interface EventsSection {
122
+ status: SectionStatus
123
+ unparsed: number
124
+ /** lines of a kind this app does not know: counted, never exported */
125
+ unknown: number
126
+ /** events past REPORT_EVENTS_MAX or the 2 MB bound, the oldest */
127
+ cut: number
128
+ /** lines in the window by kind (`sample`, `shown` and `tab` included), in APP_KINDS order */
129
+ counts: Partial<Record<AppKind, number>>
130
+ /** newest first */
131
+ list: ReportEvent[]
132
+ }
133
+
134
+ /** Crashpad's reports in the window, by their file's time (#26): counts only, never a name, a path or a dump. */
135
+ export interface CrashpadSection { status: SectionStatus; completed: number; pending: number }
136
+
137
+ export interface PerfReport {
138
+ v: 1
139
+ /** when it was made */
140
+ made: number
141
+ /** the running app's version, Electron's and macOS's (ruled as the records' are) */
142
+ version: string
143
+ electron: string
144
+ macos: string
145
+ flavour: Flavour
146
+ /** the window */
147
+ start: number
148
+ end: number
149
+ mac: MacSection
150
+ samples: SamplesSection
151
+ shown: ShownSection
152
+ events: EventsSection
153
+ crashpad: CrashpadSection
154
+ }
155
+
156
+ // ---- value rules (#27) --------------------------------------------------------------------------------------------
157
+
158
+ /** A rule: the value as it may leave, or undefined to drop it. */
159
+ export type Rule = (v: unknown) => unknown
160
+ type Exact<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false
161
+
162
+ const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v)
163
+ /** a string: kept when `ok`, else `other`; any other type dropped */
164
+ const str = (ok: (s: string) => boolean): Rule => (v) => (typeof v === 'string' ? (ok(v) ? v : 'other') : undefined)
165
+ /** one of a set */
166
+ export const oneOf = (list: readonly string[]): Rule => { const s = new Set(list); return str((v) => s.has(v)) }
167
+ /** a pattern, at most REPORT_STRING_MAX characters */
168
+ export const matches = (re: RegExp): Rule => str((v) => v.length <= REPORT_STRING_MAX && re.test(v))
169
+ /** a finite number; null kept (the record's unknown) */
170
+ export const num: Rule = (v) => (v === null ? null : typeof v === 'number' && Number.isFinite(v) ? v : undefined)
171
+ export const bool: Rule = (v) => (typeof v === 'boolean' ? v : undefined)
172
+ /** a pressure level: 1, 2 or 4, null kept */
173
+ export const level: Rule = (v) => (v === 1 || v === 2 || v === 4 || v === null ? v : undefined)
174
+ /** a number or the record's own word `unknown` (AGX readings, a profile's cores) */
175
+ export const numOrUnknown: Rule = (v) => (typeof v === 'string' ? (v === 'unknown' ? v : 'other') : num(v))
176
+ /** a rule that also admits the profile's `unknown` */
177
+ const orUnknown = (r: Rule): Rule => (v) => (v === 'unknown' ? v : r(v))
178
+
179
+ /** A3's renderer roles (`Role`). */
180
+ export const ROLES = ['canvas', 'strip', 'home', 'settings', 'tabpage', 'cover', 'mixed', 'none', 'unknown'] as const
181
+ const rolesExact: Exact<(typeof ROLES)[number], Role> = true
182
+ /** `ThermalState`, best to worst after `unknown`. */
183
+ export const THERMAL = ['unknown', 'nominal', 'fair', 'serious', 'critical'] as const
184
+ const thermalExact: Exact<(typeof THERMAL)[number], ThermalState> = true
185
+ /** Electron 45's `RenderProcessGoneDetails.reason`, also `child-process-gone`'s. */
186
+ export const GONE_REASONS = ['clean-exit', 'abnormal-exit', 'killed', 'crashed', 'oom', 'launch-failed', 'integrity-failure', 'memory-eviction'] as const
187
+ /** Electron 45's `child-process-gone` `type`. */
188
+ export const CHILD_TYPES = ['Utility', 'Zygote', 'Sandbox helper', 'GPU', 'Pepper Plugin', 'Pepper Plugin Broker', 'Unknown'] as const
189
+ /** `main-error.name` (errors.ts keeps any text up to 100 characters): JavaScript's own error names only. */
190
+ export const ERROR_NAMES = ['Error', 'TypeError', 'RangeError', 'ReferenceError', 'SyntaxError', 'URIError', 'EvalError', 'AggregateError'] as const
191
+ /**
192
+ * `getGPUFeatureStatus()`'s keys in Electron 45 (`gpu.featureStatus`): its typings' (`GPUFeatureStatus`) and the
193
+ * names Chromium 142's `compositor_util.cc` sets, read from Electron 45.0.0's framework binary (2 Nov 2026). Any other
194
+ * key is dropped.
195
+ */
196
+ export const GPU_FEATURES = [
197
+ '2d_canvas', 'direct_rendering_display_compositor', 'flash_3d', 'flash_stage3d', 'flash_stage3d_baseline', 'gpu_compositing',
198
+ 'multiple_raster_threads', 'native_gpu_memory_buffers', 'opengl', 'rasterization', 'raw_draw', 'skia_graphite', 'trees_in_viz',
199
+ 'video_decode', 'video_encode', 'vpx_decode', 'vulkan', 'webgl', 'webgl2', 'webgpu', 'webnn',
200
+ ] as const
201
+ /** Electron's documented status words (`gpu-feature-status`); any other value is `unknown`. */
202
+ export const GPU_STATUS = [
203
+ 'disabled_software', 'disabled_off', 'disabled_off_ok', 'unavailable_software', 'unavailable_off', 'unavailable_off_ok',
204
+ 'enabled_readback', 'enabled_force', 'enabled', 'enabled_on', 'enabled_force_on',
205
+ ] as const
206
+ /** tabs.ts's `UnloadRefusal` (an app type: unit `report.test` holds the two equal). */
207
+ export const UNLOAD_REFUSALS = ['not-canvas', 'active', 'no-document', 'replacing', 'sweeping', 'no-bridge', 'unknown', 'stale',
208
+ 'unsaved', 'busy', 'crash', 'hung', 'audible', 'devtools', 'loading', 'refused-before', 'recent'] as const
209
+ export const UNLOAD_REASONS = ['warn', 'critical', 'half-ram'] as const
210
+ export const UNLOAD_PHASES = ['start', 'unsure', 'done', 'forced', 'refused'] as const
211
+ export const POWER_EVENTS = ['on-ac', 'on-battery', 'suspend', 'resume', 'thermal-state-change', 'speed-limit-change'] as const
212
+ export const COVER_CAUSES = ['doc', 'size', 'show', 'fullscreen', 'hello', 'resize', 'gpu'] as const
213
+ export const COVER_OUTCOMES = ['uncovered', 'mismatch', 'superseded', 'never'] as const
214
+ export const UPDATE_PHASES = ['blocked', 'check', 'current', 'downloading', 'downloaded', 'error', 'late', 'slow', 'restart',
215
+ 'restart-failed', 'installed', 'install-failed', 'move'] as const
216
+ const phasesExact: Exact<(typeof UPDATE_PHASES)[number], UpdateBody['phase']> = true
217
+ /**
218
+ * `update.why` (#25): a block's (update-model.ts `BlockedWhy`), a late event's (the updater's event names and
219
+ * `throw`) and a move's (UPDATE_MOVE_WHY). A why the restart stream adds is `other` until it is listed here.
220
+ */
221
+ export const UPDATE_WHY = ['feed', 'location', 'write', 'setup', 'throw', 'error', 'checking-for-update', 'update-available',
222
+ 'update-not-available', 'update-downloaded',
223
+ // #18: an intent naming neither version, or over 30 days old, cleared and recorded `late` (restart stream)
224
+ 'intent', 'intent-old', ...UPDATE_MOVE_WHY] as const
225
+ void rolesExact; void thermalExact; void phasesExact
226
+
227
+ /** A Mac's chip (#27). */
228
+ export const CHIP = /^Apple M\d+( Pro| Max| Ultra)?$/
229
+ /** A Mac's model identifier, e.g. `Mac15,9`. */
230
+ export const MODEL = /^[A-Za-z]+\d+,\d+$/
231
+ export const MACOS = /^\d+(\.\d+){0,2}$/
232
+ export const APP_VERSION = /^\d+\.\d+\.\d+$/
233
+ /** Electron's and Chrome's versions */
234
+ export const CHROMIUM_VERSION = /^\d+(\.\d+){1,3}$/
235
+ /** main's opaque tab id (tabs.ts: `t` and a base-36 counter), or Home's and Settings' own */
236
+ export const TAB = /^(t[0-9a-z]{1,12}|home|settings)$/
237
+
238
+ const role = oneOf(ROLES)
239
+ const thermal = oneOf(THERMAL)
240
+ const goneReason = oneOf(GONE_REASONS)
241
+ const tab = matches(TAB)
242
+ const appVersion = matches(APP_VERSION)
243
+ const chromium = matches(CHROMIUM_VERSION)
244
+ const unloadReason = oneOf(UNLOAD_REASONS)
245
+
246
+ /** `gpu.featureStatus` (#27): only Electron 45's keys, each value a documented word or `unknown`. */
247
+ const STATUS = new Set<string>(GPU_STATUS)
248
+ export const featureStatus: Rule = (v) => {
249
+ if (!isObj(v)) return undefined
250
+ const out: Record<string, string> = {}
251
+ for (const k of GPU_FEATURES) if (Object.hasOwn(v, k)) out[k] = typeof v[k] === 'string' && STATUS.has(v[k] as string) ? (v[k] as string) : 'unknown'
252
+ return out
253
+ }
254
+
255
+ // ---- projections (#27) --------------------------------------------------------------------------------------------
256
+
257
+ /** A field of a projection: its name out, and how it is read from the record's body. */
258
+ export type Field = readonly [string, (body: Record<string, unknown>) => unknown]
259
+ /** a field read from the body's own field of that name, through `rule` */
260
+ const f = (key: string, rule: Rule): Field => [key, (b) => rule(b[key])]
261
+ /** a nested object, field by field */
262
+ const nested = (fields: readonly Field[]): Rule => (v) => (isObj(v) ? project(fields, v) : undefined)
263
+ /** Every record about a tab keeps only `tab` (#27). */
264
+ const TAB_FIELD = f('tab', tab)
265
+
266
+ /** An AGX reading's numbers (`agx`, and a flash's and a white-out candidate's), never `machineWide`. */
267
+ const AGX: readonly Field[] = ['gpuSystemMemoryMB', 'allocMB', 'utilPct', 'rendererPct', 'tilerPct', 'recoveryCount'].map((k) => f(k, numOrUnknown))
268
+ /** An unload's before and after: the level, availablePct, the canvases' memory, the tab's memMB (never its pids), the GPU process's RSS. */
269
+ const FIGURES: readonly Field[] = [f('level', level), f('availablePct', num), f('canvasMB', num), f('tab', nested([f('memMB', num)])), f('gpuProcessRssMB', num)]
270
+
271
+ /** The kinds exported one by one; `sample` and `shown` are folded (FOLDED_KINDS), `tab` only counted (COUNTED_KINDS) -
272
+ * and spec 30's `launch`, `cmd` and `window`, counted and never exported until a report v2 (spec 30 #56). */
273
+ export const FOLDED_KINDS = ['sample', 'shown'] as const
274
+ export const COUNTED_KINDS = ['tab', 'launch', 'cmd', 'window'] as const
275
+ export type ExportedKind = Exclude<AppKind, (typeof FOLDED_KINDS)[number] | (typeof COUNTED_KINDS)[number]>
276
+
277
+ /** Each kind's projection, field by field (#27): what a record may carry out, in this order after `ts` and `kind`. */
278
+ export const PROJECTIONS: { readonly [K in ExportedKind]: readonly Field[] } = {
279
+ start: [f('version', appVersion), f('electron', chromium), f('recorder', bool)],
280
+ agx: AGX,
281
+ gone: [TAB_FIELD, f('role', role), f('reason', goneReason), f('exitCode', num), f('ours', bool), f('source', oneOf(['unload', 'reload-page'])), f('pressure', level)],
282
+ 'child-gone': [f('type', oneOf(CHILD_TYPES)), f('reason', goneReason), f('exitCode', num)],
283
+ // its time alone
284
+ 'gpu-restart': [],
285
+ unresponsive: [TAB_FIELD, f('role', role)],
286
+ responsive: [TAB_FIELD, f('role', role)],
287
+ gpu: [f('featureStatus', featureStatus)],
288
+ power: [f('event', oneOf(POWER_EVENTS)), f('thermal', thermal)],
289
+ pressure: [f('level', level), f('availablePct', num)],
290
+ unload: [TAB_FIELD, f('phase', oneOf(UNLOAD_PHASES)), f('reason', unloadReason)],
291
+ 'unload-skip': [TAB_FIELD, f('reason', unloadReason), f('why', oneOf(UNLOAD_REFUSALS))],
292
+ 'unload-effect': [TAB_FIELD, f('reason', unloadReason), f('before', nested(FIGURES)), f('after', nested(FIGURES)), f('pidGone', bool)],
293
+ reopen: [TAB_FIELD, f('activateToLiftMs', num), f('unloadedForMs', num)],
294
+ cover: [TAB_FIELD, f('cause', oneOf(COVER_CAUSES)), f('outcome', oneOf(COVER_OUTCOMES)), f('sentMs', num), f('answeredMs', num),
295
+ f('uncoveredMs', num), f('hiddenMs', num), f('uncoverDelayMs', num), f('frames', num)],
296
+ // the pressure's level alone; whether a picture exists, never its path (nor `pictureWhy`, the ring, `now` or the id)
297
+ flash: [TAB_FIELD, f('via', oneOf(['key', 'menu'])), f('recorder', bool), f('thermal', thermal),
298
+ ['pressure', (b) => (b.pressure === null ? null : isObj(b.pressure) ? level(b.pressure.level) : undefined)],
299
+ f('agx', nested(AGX)),
300
+ ['picture', (b) => (typeof b.picture === 'string' ? true : b.picture === null ? false : undefined)]],
301
+ 'whiteout-candidate': [TAB_FIELD, f('rateHz', num), f('samples', num), f('skipped', num), f('inconclusive', num), f('agx', nested(AGX))],
302
+ dropped: [f('n', num)],
303
+ 'main-error': [f('what', oneOf(['exception', 'rejection'])), f('name', oneOf(ERROR_NAMES))],
304
+ // never `message` (the updater's error text) nor `attempt`
305
+ update: [f('phase', oneOf(UPDATE_PHASES)), f('version', appVersion), f('from', appVersion), f('to', appVersion), f('why', oneOf(UPDATE_WHY)), f('manual', bool)],
306
+ }
307
+
308
+ /** A body through its fields: only what they give (undefined dropped), in their order. */
309
+ export function project(fields: readonly Field[], body: Record<string, unknown>): Record<string, unknown> {
310
+ const out: Record<string, unknown> = {}
311
+ for (const [k, read] of fields) {
312
+ const v = read(body)
313
+ if (v !== undefined) out[k] = v
314
+ }
315
+ return out
316
+ }
317
+
318
+ /** One record as it may leave (#27): `ts`, `kind`, its projection; null for a kind that is folded, counted or unknown. */
319
+ export function projectRecord(kind: string, ts: number, body: Record<string, unknown>): ReportEvent | null {
320
+ if (!Object.hasOwn(PROJECTIONS, kind)) return null
321
+ const k = kind as ExportedKind
322
+ return { ts, kind: k, ...project(PROJECTIONS[k], body) }
323
+ }
324
+
325
+ /** The Mac (#27): a profile's host and displays through their rules; null for something that is no profile. */
326
+ export function projectMac(p: unknown): Omit<MacRow, 'from' | 'to'> | null {
327
+ if (!isObj(p) || p.v !== 1 || (p.kind !== 'app' && p.kind !== 'headless') || !isObj(p.host)) return null
328
+ const host = p.host
329
+ const out = project([
330
+ f('chip', orUnknown(matches(CHIP))),
331
+ f('cores', nested([f('total', num), f('p', numOrUnknown), f('e', numOrUnknown)])),
332
+ f('memGB', num),
333
+ f('model', orUnknown(matches(MODEL))),
334
+ ['macos', (h) => orUnknown(matches(MACOS))(h.os)],
335
+ ], host)
336
+ const displays = p.kind === 'app' && Array.isArray(p.displays)
337
+ ? p.displays.filter(isObj).slice(0, REPORT_DISPLAYS_MAX).map((d) => project([f('scaleFactor', num), ['displayFrequency', (x) => num(x.hz)]], d))
338
+ : []
339
+ return { ...out, displays } as Omit<MacRow, 'from' | 'to'>
340
+ }
341
+
342
+ // ---- the line -----------------------------------------------------------------------------------------------------
343
+
344
+ const KNOWN = new Set<string>(APP_KINDS)
345
+ const TS = /^\{"v":1,"ts":(\d{10,16})[,}]/
346
+ const KIND = /"kind":"([a-z-]{1,32})"/
347
+ const isSeq = (v: unknown): boolean => typeof v === 'number' && Number.isInteger(v) && v >= 0
348
+
349
+ /**
350
+ * One line's envelope (parseAppLine's checks, A3.5), telling an unknown kind from a line that does not parse: `skip`
351
+ * for a line outside the window, `bad` for one that does not parse, `unknown` for a well-formed line of a kind this
352
+ * app does not know.
353
+ */
354
+ export function readEnvelope(line: string, start: number, end: number):
355
+ | { at: 'skip' } | { at: 'bad'; kind: string | null } | { at: 'unknown' }
356
+ | { at: 'ok'; ts: number; kind: AppKind; machine: string | null; body: Record<string, unknown> } {
357
+ // the envelope comes first in every line the writer makes: a line outside the window is skipped unparsed
358
+ const m = TS.exec(line)
359
+ if (m) { const ts = Number(m[1]); if (ts < start || ts > end) return { at: 'skip' } }
360
+ const bad = () => ({ at: 'bad' as const, kind: KIND.exec(line)?.[1] ?? null })
361
+ let o: unknown
362
+ try { o = JSON.parse(line) } catch { return bad() }
363
+ if (!isObj(o) || o.v !== 1 || typeof o.ts !== 'number' || !Number.isFinite(o.ts)) return bad()
364
+ if (typeof o.app !== 'string' || !/^[0-9a-f]{12}$/.test(o.app) || !isSeq(o.seq)) return bad()
365
+ if (o.flavour !== 'release' && o.flavour !== 'dev') return bad()
366
+ if (o.machine !== null && (typeof o.machine !== 'string' || !/^[0-9a-f]{16}$/.test(o.machine))) return bad()
367
+ if (typeof o.kind !== 'string') return bad()
368
+ if (o.ts < start || o.ts > end) return { at: 'skip' }
369
+ if (!KNOWN.has(o.kind)) return { at: 'unknown' }
370
+ return { at: 'ok', ts: o.ts, kind: o.kind as AppKind, machine: o.machine as string | null, body: o }
371
+ }
372
+
373
+ // ---- the aggregations (#27) ---------------------------------------------------------------------------------------
374
+
375
+ const r1 = (v: number): number => Math.round(v * 10) / 10
376
+ const r3 = (v: number): number => Math.round(v * 1000) / 1000
377
+ const fin = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v)
378
+ const finNonNeg = (v: unknown): v is number => fin(v) && v >= 0
379
+ const maxOf = (a: number | null, b: number): number => (a === null ? b : Math.max(a, b))
380
+ const THERMAL_RANK: Record<string, number> = { nominal: 1, fair: 2, serious: 3, critical: 4 }
381
+
382
+ interface HourAcc {
383
+ minutes: number; missing: number; s: number; ms: number; unmeasuredMs: number; maxMinute: number | null
384
+ rssSum: number; rssN: number; rssMax: number | null; canvas: number | null; gpu: number | null; pressure: PressureLevel | null; thermal: number
385
+ }
386
+ const newHour = (): HourAcc => ({ minutes: 0, missing: 0, s: 0, ms: 0, unmeasuredMs: 0, maxMinute: null, rssSum: 0, rssN: 0, rssMax: null, canvas: null, gpu: null, pressure: null, thermal: 0 })
387
+
388
+ /** `own.cpu` as the recorder folds it: three finite figures, none negative, or none at all. */
389
+ function ownCpuOf(own: unknown): { s: number; ms: number; unmeasuredMs: number } | null {
390
+ if (!isObj(own) || !isObj(own.cpu)) return null
391
+ const { s, ms, unmeasuredMs } = own.cpu
392
+ return finNonNeg(s) && finNonNeg(ms) && finNonNeg(unmeasuredMs) ? { s, ms, unmeasuredMs } : null
393
+ }
394
+ const aggMax = (v: unknown): number | null => (isObj(v) && finNonNeg(v.max) ? v.max : null)
395
+
396
+ /** One `sample` line into its hour (r2 #4, r3 #5): never ownership from the per-process list. */
397
+ function foldSample(h: HourAcc, b: Record<string, unknown>): void {
398
+ h.minutes += 1
399
+ const cpu = ownCpuOf(b.own)
400
+ if (!cpu) h.missing += 1
401
+ else {
402
+ h.s += cpu.s
403
+ h.ms += cpu.ms
404
+ h.unmeasuredMs += cpu.unmeasuredMs
405
+ if (cpu.ms > 0) h.maxMinute = maxOf(h.maxMinute, cpu.s / (cpu.ms / 1000))
406
+ const rss = (b.own as { rssMB?: unknown }).rssMB
407
+ if (isObj(rss)) {
408
+ if (finNonNeg(rss.mean) && fin(b.n) && Number.isInteger(b.n) && b.n > 0) { h.rssSum += rss.mean * b.n; h.rssN += b.n }
409
+ if (finNonNeg(rss.max)) h.rssMax = maxOf(h.rssMax, rss.max)
410
+ }
411
+ }
412
+ const canvas = isObj(b.canvases) ? aggMax(b.canvases.memMB) : null
413
+ if (canvas !== null) h.canvas = maxOf(h.canvas, canvas)
414
+ const gpu = isObj(b.gpu) ? aggMax(b.gpu.gpuProcessRssMB) : null
415
+ if (gpu !== null) h.gpu = maxOf(h.gpu, gpu)
416
+ const p = isObj(b.pressure) ? b.pressure.max : null
417
+ if (p === 1 || p === 2 || p === 4) h.pressure = h.pressure === null ? p : (Math.max(h.pressure, p) as PressureLevel)
418
+ const t = typeof b.thermal === 'string' ? THERMAL_RANK[b.thermal] ?? 0 : 0
419
+ if (t > h.thermal) h.thermal = t
420
+ }
421
+
422
+ function hourRow(hour: number, h: HourAcc): HourRow {
423
+ return {
424
+ hour,
425
+ minutes: h.minutes,
426
+ minutesMissing: h.missing,
427
+ ownCpu: h.ms > 0 ? r3(h.s / (h.ms / 1000)) : null,
428
+ ownCpuMaxMinute: h.maxMinute === null ? null : r3(h.maxMinute),
429
+ measuredS: r1(h.ms / 1000),
430
+ unmeasuredS: r1(h.unmeasuredMs / 1000),
431
+ ownRssMB: { mean: h.rssN > 0 ? r1(h.rssSum / h.rssN) : null, max: h.rssMax === null ? null : r1(h.rssMax) },
432
+ canvasMemMB: h.canvas === null ? null : r1(h.canvas),
433
+ gpuRssMB: h.gpu === null ? null : r1(h.gpu),
434
+ pressureMax: h.pressure,
435
+ thermalWorst: (['unknown', 'nominal', 'fair', 'serious', 'critical'] as const)[h.thermal]!,
436
+ }
437
+ }
438
+
439
+ /** The nearest-rank percentile of sorted values. */
440
+ export const nearestRank = (sorted: readonly number[], p: number): number => sorted[Math.max(0, Math.ceil((p / 100) * sorted.length) - 1)]!
441
+
442
+ /** How the log read: whole, missing, unreadable, or stopped by an error after some lines. */
443
+ export type LogRead = 'ok' | 'missing' | 'unreadable' | 'stopped'
444
+ /** A named profile as read: its parsed JSON, absent (no file), or unreadable (it could not be read or parsed as JSON). */
445
+ export type ProfileRead = { json: unknown } | 'absent' | 'unreadable'
446
+
447
+ interface Held { ts: number; i: number; ev: ReportEvent }
448
+ /** newest first; the later line first at a tie */
449
+ const newestFirst = (a: Held, b: Held): number => b.ts - a.ts || b.i - a.i
450
+
451
+ /**
452
+ * The report folded line by line (#26): bounded whatever the log holds - at most 2 x REPORT_EVENTS_MAX events held,
453
+ * one accumulator per hour and a list of `shown` times per day in the window, the profiles named.
454
+ */
455
+ export class ReportFold {
456
+ private i = 0
457
+ private held: Held[] = []
458
+ private cut = 0
459
+ private counts = new Map<AppKind, number>()
460
+ private unknown = 0
461
+ private unparsed = { samples: 0, shown: 0, events: 0 }
462
+ private hours = new Map<number, HourAcc>()
463
+ private shownDays = new Map<number, number[]>()
464
+ private named = new Map<string, { from: number; to: number }>()
465
+ private namedCut = 0
466
+ private profiles = new Map<string, ProfileRead>()
467
+
468
+ constructor(readonly start: number, readonly end: number) {}
469
+
470
+ /** One line of the log. */
471
+ line(text: string): void {
472
+ if (!text) return
473
+ const e = readEnvelope(text, this.start, this.end)
474
+ if (e.at === 'skip') return
475
+ if (e.at === 'bad') { this.unparsed[e.kind === 'sample' ? 'samples' : e.kind === 'shown' ? 'shown' : 'events'] += 1; return }
476
+ if (e.at === 'unknown') { this.unknown += 1; return }
477
+ this.counts.set(e.kind, (this.counts.get(e.kind) ?? 0) + 1)
478
+ if (e.machine) this.name(e.machine, e.ts)
479
+ if (e.kind === 'sample') {
480
+ const hour = Math.floor(e.ts / HOUR) * HOUR
481
+ let h = this.hours.get(hour)
482
+ if (!h) this.hours.set(hour, h = newHour())
483
+ foldSample(h, e.body)
484
+ return
485
+ }
486
+ if (e.kind === 'shown') {
487
+ if (!finNonNeg(e.body.ms)) return
488
+ const day = Math.floor(e.ts / DAY) * DAY
489
+ let d = this.shownDays.get(day)
490
+ if (!d) this.shownDays.set(day, d = [])
491
+ d.push(e.body.ms)
492
+ return
493
+ }
494
+ const ev = projectRecord(e.kind, e.ts, e.body)
495
+ if (!ev) return
496
+ this.held.push({ ts: e.ts, i: this.i++, ev })
497
+ if (this.held.length > 2 * REPORT_EVENTS_MAX) this.trim()
498
+ }
499
+
500
+ private trim(): void {
501
+ this.held.sort(newestFirst)
502
+ this.cut += Math.max(0, this.held.length - REPORT_EVENTS_MAX)
503
+ this.held.length = Math.min(this.held.length, REPORT_EVENTS_MAX)
504
+ }
505
+
506
+ private name(hash: string, ts: number): void {
507
+ const n = this.named.get(hash)
508
+ if (n) { n.from = Math.min(n.from, ts); n.to = Math.max(n.to, ts); return }
509
+ // bounded: a log naming more profiles than any Mac makes keeps the first thousand
510
+ if (this.named.size >= 1000) { this.namedCut += 1; return }
511
+ this.named.set(hash, { from: ts, to: ts })
512
+ }
513
+
514
+ /** The profiles to read: those the window's lines name, the most recently named first, at most REPORT_PROFILES_MAX. */
515
+ wanted(): string[] {
516
+ return [...this.named].sort((a, b) => b[1].to - a[1].to || (a[0] < b[0] ? -1 : 1)).slice(0, REPORT_PROFILES_MAX).map(([h]) => h)
517
+ }
518
+
519
+ /** A named profile, as report.ts read it. */
520
+ profile(hash: string, p: ProfileRead): void { if (this.named.has(hash)) this.profiles.set(hash, p) }
521
+
522
+ /** The report, and its bytes (pretty-printed, at most REPORT_MAX_BYTES). Throws only if no cut can bring it under. */
523
+ finish(h: { made: number; version: unknown; electron: unknown; macos: unknown; flavour: Flavour; log: LogRead; crashpad: CrashpadSection }): { report: PerfReport; json: string } {
524
+ const word = (r: Rule, v: unknown): string => { const x = r(v); return typeof x === 'string' ? x : 'other' }
525
+ const head = {
526
+ v: REPORT_V, made: h.made,
527
+ version: word(appVersion, h.version), electron: word(chromium, h.electron), macos: word(matches(MACOS), h.macos),
528
+ flavour: h.flavour, start: this.start, end: this.end,
529
+ }
530
+ const status = (unparsed: number, cut = 0): SectionStatus => h.log === 'missing' ? 'missing' : h.log === 'unreadable' ? 'unreadable'
531
+ : h.log === 'stopped' || unparsed > 0 || cut > 0 ? 'partial' : 'ok'
532
+
533
+ // the Mac: each named profile read, projected, alike ones joined
534
+ const rows = new Map<string, MacRow>()
535
+ let absent = 0, badProfiles = 0
536
+ const wanted = this.wanted()
537
+ for (const hash of wanted) {
538
+ const p = this.profiles.get(hash) ?? 'absent'
539
+ const span = this.named.get(hash)!
540
+ if (p === 'absent') { absent += 1; continue }
541
+ const mac = p === 'unreadable' ? null : projectMac(p.json)
542
+ if (!mac) { badProfiles += 1; continue }
543
+ const key = JSON.stringify(mac)
544
+ const row = rows.get(key)
545
+ if (row) { row.from = Math.min(row.from, span.from); row.to = Math.max(row.to, span.to) } else rows.set(key, { from: span.from, to: span.to, ...mac })
546
+ }
547
+ const macCut = this.named.size - wanted.length + this.namedCut
548
+ const macRows = [...rows.values()].sort((a, b) => b.to - a.to || a.from - b.from)
549
+ const macStatus: SectionStatus = this.named.size === 0 && this.namedCut === 0 ? (h.log === 'unreadable' ? 'unreadable' : 'missing')
550
+ : macRows.length === 0 ? (badProfiles > 0 ? 'unreadable' : 'missing')
551
+ : badProfiles + absent + macCut > 0 || h.log !== 'ok' ? 'partial' : 'ok'
552
+
553
+ const hourRows = [...this.hours].sort((a, b) => b[0] - a[0]).map(([hour, acc]) => hourRow(hour, acc))
554
+ const days = [...this.shownDays].sort((a, b) => b[0] - a[0]).map(([day, ms]): ShownDay => {
555
+ const s = [...ms].sort((a, b) => a - b)
556
+ return { day, n: s.length, p50Ms: r1(nearestRank(s, 50)), p95Ms: r1(nearestRank(s, 95)) }
557
+ })
558
+ const counts: Partial<Record<AppKind, number>> = {}
559
+ for (const k of APP_KINDS) { const n = this.counts.get(k); if (n) counts[k] = n }
560
+
561
+ this.trim()
562
+ let list = this.held.map((x) => x.ev)
563
+ let cut = this.cut
564
+ const build = (): PerfReport => ({
565
+ ...head,
566
+ mac: { status: macStatus, unparsed: badProfiles, absent, cut: macCut, rows: macRows },
567
+ samples: { status: status(this.unparsed.samples), unparsed: this.unparsed.samples, lines: this.counts.get('sample') ?? 0, rows: hourRows },
568
+ shown: { status: status(this.unparsed.shown), unparsed: this.unparsed.shown, lines: this.counts.get('shown') ?? 0, days },
569
+ events: { status: status(this.unparsed.events, cut + this.unknown), unparsed: this.unparsed.events, unknown: this.unknown, cut, counts, list },
570
+ crashpad: h.crashpad,
571
+ })
572
+ const bytes = (t: string): number => new TextEncoder().encode(t).length
573
+ let report = build()
574
+ let json = JSON.stringify(report, null, 2) + '\n'
575
+ // the 2 MB bound: the oldest events go, a tenth at a time, counted
576
+ while (bytes(json) > REPORT_MAX_BYTES) {
577
+ if (!list.length) throw new Error('the report is over its bound with no event left to cut')
578
+ const n = Math.max(1, Math.ceil(list.length / 10))
579
+ list = list.slice(0, list.length - n)
580
+ cut += n
581
+ report = build()
582
+ json = JSON.stringify(report, null, 2) + '\n'
583
+ }
584
+ return { report, json }
585
+ }
586
+ }