@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,765 @@
1
+ /**
2
+ * One vocabulary in code (spec 30 R12 #48-#52): every command the canvas records, as data - its lifecycle, the signal
3
+ * that ends it, its deadline and its codes - and the one call every dispatch point makes, `cmd(name, { via, keys, in })`,
4
+ * which returns `done()`, `fail(why)`, `noop(why)`, `cancel()`, `step(name)`. The static gate
5
+ * (test/r30-commands-static.test.ts) checks that every input site and dispatcher branch reaches `cmd()` or appears in
6
+ * test/not-commands.json; the runtime tests (test/r30-commands-browser.test.ts, -engine.test.ts) expect each name's
7
+ * declared lifecycle.
8
+ *
9
+ * The rules the commands stream implements here:
10
+ * - A record per command (#48): `start` at the input and `end` after its signal, the same `id` (12 hex). A command
11
+ * decided in its input's own turn - `once` names, and any `noop` - writes one `once` record instead. Starts are bounded
12
+ * at 10/s per page, burst 20; past it `dropped { reason: 'cmd' }` (perf-records.ts `CMD_BOUNDS`).
13
+ * - Outcomes are bound to real signals (#49): its deadline passing with no signal ends it `unobserved` (why
14
+ * `deadline`); a completion after that is a second `end` with `late: true`.
15
+ * - Provenance from the handler that received it (#50): `via`, `keys` (jam-keys.ts `descriptor()`, key inputs only)
16
+ * and `in`. A relay is recorded once, by the side that executes it (#51).
17
+ * - Effects name the command behind them (`by`): one started in the command's turn reads `currentCmd()`; one started
18
+ * later in its chain runs under `withCmd(id, fn)`, and a write that waits or retries keeps them with `keepCmds()`.
19
+ * - Silence (the R12 note): `deselect`, `thread-close` and `jam-close` write nothing when they change nothing.
20
+ *
21
+ * Owner: the commands stream. Everything here is gated by the recorder being on at the `full` level (recorder-level.ts) -
22
+ * on a published canvas or under `core` a call costs one check, and writes nothing.
23
+ */
24
+ import { CMD_BOUNDS, decodeCmds, ID12, WRITER_HEADERS, type Candidates, type CmdIn, type CmdStep, type CmdVia, type ModeName } from '../../shared/perf-records.ts'
25
+ import { fullRecorder } from '../recorder-level.ts'
26
+ import { newId } from './recorder-core.ts'
27
+ import { hooked, perfSeams, type Answered, type LoadPhase } from './recorder-seams.ts'
28
+ import { canvasCtl } from './canvas/ctl.ts'
29
+ import { bootOf, fromLiveDocument, iframeOf } from './canvas/frame-registry.ts'
30
+
31
+ /** `once`: decided in its input's own turn, one record. `start-end`: a start at the input, an end after its signal. */
32
+ export type Lifecycle = 'once' | 'start-end'
33
+
34
+ /**
35
+ * What ends a command (`done`), named after the table's "Done when" column:
36
+ * - `2raf`: two animation frames after the state changed; `turn`: the input's own turn (`once`);
37
+ * - `mode-applied`: the displayed cohort's `sh:mode-applied` (#26); `mode`: the `mode` record's enter or exit;
38
+ * - `stage-shown`: the (new) screen's `sh:stage-shown`; `camera`: the camera lands or its motion ends;
39
+ * - `layout`: the layout animation ends (and, for `device`, the fit); `gesture`: the pan gesture ends;
40
+ * - `clipboard`: `clipboard.write`/`writeText` resolved; `theme`: the `theme` record's outcome (#23);
41
+ * - `selection`: the selection changed; `exit`: the exit it made (`escape`'s steps);
42
+ * - `save`: the board save carrying its id landed; `ready`: the node's next `ready`; `settled`: its load settled,
43
+ * with steps (#49); `where`: where it leads (`history-nav`); `goto`: the camera, the target board's `visible`, or
44
+ * `sh:stage-shown`;
45
+ * - `answer`: the API, the queue or the store answered ok (the table names which); `thread`: the thread revealed;
46
+ * `shell-boot`: the next page's `shell-boot` (the id kept in `sessionStorage`); `image`: the picked image read;
47
+ * `jam`: the Jam state's transition (jam.jsonl keeps the timings); `voice`: the voice, consent or download state
48
+ * changed; `note-step`: the capture's note step added.
49
+ */
50
+ export type Signal =
51
+ | '2raf' | 'turn' | 'mode-applied' | 'mode' | 'stage-shown' | 'camera' | 'layout' | 'gesture' | 'clipboard' | 'theme'
52
+ | 'selection' | 'exit' | 'save' | 'ready' | 'settled' | 'where' | 'goto' | 'answer' | 'thread' | 'shell-boot' | 'image'
53
+ | 'jam' | 'voice' | 'note-step'
54
+
55
+ /** One command's row of the R12 tables. Codes are the `why` each outcome may carry; `cancelled` and `unobserved` are
56
+ * always possible where listed (`unobserved` by its deadline whatever the row says). */
57
+ export interface CmdSpec {
58
+ life: Lifecycle
59
+ done: Signal
60
+ /** ms from the input; the table's "(N s)", else 10 s */
61
+ deadlineMs: number
62
+ failed?: readonly string[]
63
+ noop?: readonly string[]
64
+ /** the person can back out (Esc on a rename, a refused sheet), or another load or an edit took over */
65
+ cancelled?: true
66
+ /** codes beyond `deadline`: a load cut `hidden` or `timeout` (#49) */
67
+ unobserved?: readonly string[]
68
+ /** the milestones it may record in `steps` */
69
+ steps?: readonly string[]
70
+ /** writes nothing when it changes nothing (the R12 note's three incidental inputs) */
71
+ silent?: true
72
+ }
73
+
74
+ const D = CMD_BOUNDS.deadlineMs
75
+ const S30 = 30_000, S60 = 60_000, S120 = 120_000
76
+ const se = (done: Signal, o: Partial<Omit<CmdSpec, 'life' | 'done'>> = {}): CmdSpec => ({ life: 'start-end', done, deadlineMs: D, ...o })
77
+ const once = (o: Partial<Omit<CmdSpec, 'life' | 'done'>> = {}): CmdSpec => ({ life: 'once', done: 'turn', deadlineMs: D, ...o })
78
+ /** #49's board codes: `board-open` and `history-nav` end on where the load goes. */
79
+ const LOAD_CODES = { unobserved: ['hidden', 'timeout'], cancelled: true, failed: ['load-error', 'save-blocked'] } as const
80
+ const CLIP = ['clipboard-blocked'] as const
81
+ const REFUSED = ['refused'] as const
82
+
83
+ /** The canvas's commands (R12's Canvas and sidebar, Comments, Play and Jam tables), by name. */
84
+ export const COMMANDS = {
85
+ // ---- canvas and sidebar
86
+ comments: se('mode-applied', { noop: ['unplaced', 'stopped'] }),
87
+ pins: se('2raf'),
88
+ laser: se('mode-applied', { noop: ['stripped'] }),
89
+ inspect: se('mode-applied', { noop: ['stripped'] }),
90
+ 'laser-comment': se('mode-applied'),
91
+ // `nothing-to-play` (not in R12's table): `enterPlay` refused - no playable frame, or a lock
92
+ play: se('stage-shown', { deadlineMs: S30, noop: ['nothing-to-play'], failed: ['stage-error'] }),
93
+ slides: se('stage-shown', { deadlineMs: S30, noop: ['nothing-to-play'], failed: ['stage-error'] }),
94
+ 'hide-ui': se('2raf'),
95
+ tidy: se('layout', { noop: ['nothing-moved'] }),
96
+ 'next-new': se('camera', { noop: ['nothing-new'] }),
97
+ notes: se('2raf'),
98
+ 'space-pan': se('gesture', { noop: ['no-drag'] }),
99
+ 'copy-image': se('clipboard', { deadlineMs: S60, noop: ['multi', 'busy', 'indexing'], failed: ['browser', 'clipboard-blocked', 'render-failed', 'render-timeout'] }),
100
+ 'copy-path': se('clipboard', { noop: ['no-selection'], failed: CLIP }),
101
+ 'laser-copy': se('clipboard', { failed: CLIP }),
102
+ 'thread-copy-link': se('clipboard', { failed: CLIP }),
103
+ 'copy-error': se('clipboard', { failed: CLIP }),
104
+ theme: se('theme', { noop: ['one-theme'] }),
105
+ device: se('layout', { noop: ['unknown-device'] }),
106
+ 'zoom-100': se('camera', { noop: ['no-selection'] }),
107
+ 'fit-all': se('camera', { noop: ['no-selection'] }),
108
+ 'fit-selection': se('camera', { noop: ['no-selection'] }),
109
+ 'zoom-to': se('camera', { noop: ['no-selection'] }),
110
+ 'group-fit': se('camera'),
111
+ 'scene-pick': se('camera'),
112
+ 'frame-pick': se('camera'),
113
+ 'scene-toggle': se('2raf'),
114
+ 'folder-toggle': se('2raf'),
115
+ goto: se('goto', { failed: ['no-target'] }),
116
+ 'history-nav': se('where', { deadlineMs: S120, ...LOAD_CODES, failed: [...LOAD_CODES.failed, 'stage-error'], steps: ['visible', 'visible-ready', 'commit-late'] }),
117
+ panel: se('2raf'),
118
+ toolbar: se('2raf'),
119
+ select: se('selection'),
120
+ 'select-all': se('selection'),
121
+ deselect: se('2raf', { silent: true }),
122
+ escape: se('exit', { steps: ['comments-off', 'laser-off', 'interact-off', 'deselect'] }),
123
+ interact: se('mode'),
124
+ 'interact-off': se('mode'),
125
+ 'frame-move': se('save', { deadlineMs: S30, failed: ['save-conflict', 'save-failed'] }),
126
+ 'frame-resize': se('save', { deadlineMs: S30, failed: ['save-conflict', 'save-failed'] }),
127
+ 'frame-reload': se('ready', { deadlineMs: S30, failed: ['error'] }),
128
+ 'remove-node': se('save', { deadlineMs: S30, failed: ['save-failed'] }),
129
+ 'board-open': se('settled', { deadlineMs: S120, ...LOAD_CODES, steps: ['visible', 'visible-ready', 'commit-late'] }),
130
+ 'board-move': se('answer', { deadlineMs: S30, cancelled: true, failed: ['api'] }),
131
+ 'folder-new': se('answer', { deadlineMs: S30, cancelled: true, failed: ['api'] }),
132
+ 'folder-move': se('answer', { deadlineMs: S30, cancelled: true, failed: ['api'] }),
133
+ 'folder-delete': se('answer', { deadlineMs: S30, cancelled: true, failed: ['api'] }),
134
+ 'board-rename': se('answer', { deadlineMs: S30, cancelled: true, failed: ['exists', 'invalid', 'api'] }),
135
+ 'folder-rename': se('answer', { deadlineMs: S30, cancelled: true, failed: ['exists', 'invalid', 'api'] }),
136
+ 'scene-rename': se('answer', { deadlineMs: S30, cancelled: true, failed: ['exists', 'invalid', 'api'] }),
137
+ 'board-status': se('answer', { deadlineMs: S30, cancelled: true, failed: ['api'] }),
138
+ // `nothing-new` (not in R12's table): no write goes, so no answer can come
139
+ 'mark-seen': se('answer', { noop: ['nothing-new'], failed: ['api'] }),
140
+ 'add-to-board': se('answer', { failed: ['api'] }),
141
+ 'update-copy': se('clipboard', { failed: CLIP }),
142
+ 'update-dismiss': se('2raf'),
143
+ 'notice-view': se('thread', { failed: ['missing'] }),
144
+ 'notice-retry': se('answer', { deadlineMs: S30, failed: ['refused', 'missing'] }),
145
+ 'notice-dismiss': se('2raf'),
146
+ 'notices-clear': se('2raf'),
147
+ 'notices-expand': se('2raf'),
148
+ 'notices-collapse': se('2raf'),
149
+ 'shell-reload': se('shell-boot'),
150
+
151
+ // ---- comments
152
+ 'comment-pick': se('2raf'),
153
+ 'comment-send': se('answer', { deadlineMs: S30, failed: ['send-failed', 'signed-out'] }),
154
+ 'comment-reply': se('answer', { deadlineMs: S30, failed: ['send-failed', 'signed-out'] }),
155
+ 'draft-discard': se('2raf'),
156
+ 'comment-resolve': se('answer', { deadlineMs: S30, failed: ['send-failed'] }),
157
+ 'mention-pick': once(),
158
+ 'mention-dismiss': once(),
159
+ 'thread-open': se('2raf'),
160
+ 'thread-close': se('2raf', { silent: true }),
161
+ 'ask-to-comment': se('answer', { deadlineMs: S30, noop: ['too-soon'], failed: ['api'] }),
162
+ 'identity-open': se('2raf'),
163
+ 'identity-switch': se('2raf'),
164
+ 'sign-in': se('answer', { deadlineMs: S30, failed: ['rejected', 'api'] }),
165
+ claim: se('answer', { deadlineMs: S30, failed: ['rejected', 'api'] }),
166
+ 'identity-dismiss': se('2raf'),
167
+ 'profile-dismiss': se('2raf'),
168
+ 'profile-open': se('2raf'),
169
+ 'profile-save': se('answer', { deadlineMs: S30, failed: ['rejected', 'api'] }),
170
+ 'avatar-pick': se('image', { failed: ['unreadable'] }),
171
+
172
+ // ---- play (`escape` and `toolbar` in play are the canvas's names, `in: 'shell'` or `'stage'`)
173
+ 'play-next': se('stage-shown', { noop: ['end'] }),
174
+ 'play-prev': se('stage-shown', { noop: ['end'] }),
175
+ // `no-variants`, `no-frames` (not in R12's table): `[ ]` on a screen with none, R where nothing can walk
176
+ 'play-variant': se('stage-shown', { noop: ['no-variants'] }),
177
+ 'play-restart': se('stage-shown', { noop: ['no-frames'] }),
178
+ 'play-board': se('stage-shown', { deadlineMs: S30, failed: ['stage-error'] }),
179
+ // `no-door` (not in R12's table): a locked board has no way out, Esc stays
180
+ 'play-exit': se('2raf', { noop: ['no-door'] }),
181
+ 'play-update': se('stage-shown', { deadlineMs: S30, failed: ['stage-error'] }),
182
+
183
+ // ---- Jam (never a note's, an answer's or a read-back's words)
184
+ // `stopped` (not in R12's table): the canvas stopped, and no sheet to close
185
+ 'jam-session': se('2raf', { noop: ['stopped'] }),
186
+ 'jam-start': se('answer', { deadlineMs: S30, failed: REFUSED }),
187
+ 'jam-sheet-close': se('2raf'),
188
+ 'jam-pref': se('answer', { failed: ['api'] }),
189
+ 'jam-talk': se('2raf'),
190
+ 'jam-end-bare': se('answer', { deadlineMs: S30, failed: REFUSED }),
191
+ 'jam-capture': se('jam', { failed: REFUSED }),
192
+ 'jam-end': se('jam', { failed: REFUSED }),
193
+ 'jam-end-review': se('jam', { failed: REFUSED }),
194
+ 'jam-notes': se('jam', { failed: REFUSED }),
195
+ 'jam-picture': se('jam', { failed: REFUSED }),
196
+ // `no-selection` (not in R12's table): ⌫ on the lane with no tile selected
197
+ 'jam-drop': se('jam', { noop: ['no-selection'], failed: REFUSED }),
198
+ // `empty` (not in R12's table): Q with no tile on the lane
199
+ 'jam-lane': se('jam', { noop: ['empty'], failed: REFUSED }),
200
+ // `nothing-to-review` (not in R12's table): V's toast
201
+ 'jam-next-review': se('jam', { noop: ['nothing-to-review'], failed: REFUSED }),
202
+ // `more-open` (not in R12's table): ⏎ with the composer open, its field not focused
203
+ 'jam-good': se('jam', { noop: ['more-open'], failed: REFUSED }),
204
+ 'jam-more': se('jam', { failed: REFUSED }),
205
+ 'jam-later': se('jam', { failed: REFUSED }),
206
+ // `end` (not in R12's table): no review left to step back to
207
+ 'jam-back': se('jam', { noop: ['end'], failed: REFUSED }),
208
+ 'jam-before-after': se('jam', { failed: REFUSED }),
209
+ // `end` (not in R12's table): ⌥← ⌥→ at the last tab
210
+ 'jam-frame-tab': se('jam', { noop: ['end'], failed: REFUSED }),
211
+ 'jam-confirm': se('jam', { failed: REFUSED }),
212
+ // `not-keepable` (not in R12's table): K on a lane tile neither a draft nor queued
213
+ 'jam-keep': se('jam', { noop: ['not-keepable'], failed: REFUSED }),
214
+ 'jam-resume': se('jam', { failed: REFUSED }),
215
+ // `end` (not in R12's table): ← → at the lane's end
216
+ 'jam-lane-move': se('jam', { noop: ['end'], failed: REFUSED }),
217
+ // `no-selection` (not in R12's table): ⏎ on the lane with no tile selected
218
+ 'jam-open': se('jam', { noop: ['no-selection'], failed: REFUSED }),
219
+ // `not-queued` (not in R12's table): ⌘⏎ on a tile that is not queued
220
+ 'jam-do-next': se('jam', { noop: ['not-queued'], failed: REFUSED }),
221
+ // `on` (not in R12's table): the mic button while it hears you has nothing to ask
222
+ 'jam-mic': se('voice', { noop: ['on'] }),
223
+ 'jam-capture-note': se('note-step'),
224
+ 'jam-notes-close': se('2raf'),
225
+ 'jam-note-add': se('answer', { deadlineMs: S30, failed: REFUSED }),
226
+ 'jam-more-send': se('answer', { deadlineMs: S30, failed: REFUSED }),
227
+ // `busy` (not in R12's table): Write the record while its last try is out
228
+ 'jam-wrap-send': se('answer', { deadlineMs: S30, noop: ['busy'], failed: REFUSED }),
229
+ 'jam-field-discard': se('2raf'),
230
+ 'jam-edit': se('answer', { deadlineMs: S30, failed: REFUSED }),
231
+ 'jam-answer': se('answer', { deadlineMs: S30, failed: ['send-failed'] }),
232
+ 'jam-close': se('2raf', { silent: true }),
233
+ 'jam-done-fold': se('2raf'),
234
+ 'jam-step': se('2raf'),
235
+ 'jam-pane': se('2raf'),
236
+ // the download's 120 s is the longest of its choices'
237
+ 'jam-voice': se('voice', { deadlineMs: S120, cancelled: true, failed: ['download-failed'] }),
238
+ 'jam-status-open': se('2raf'),
239
+ 'jam-status-close': se('2raf'),
240
+ 'jam-status-act': se('answer', { deadlineMs: S30, failed: REFUSED }),
241
+ 'jam-rename': se('answer', { deadlineMs: S30, cancelled: true, failed: REFUSED }),
242
+ 'jam-retry': se('answer', { deadlineMs: S30, cancelled: true, failed: REFUSED }),
243
+ 'jam-again': se('answer', { deadlineMs: S30, cancelled: true, failed: REFUSED }),
244
+ 'jam-background': se('answer', { deadlineMs: S30, cancelled: true, failed: REFUSED }),
245
+ 'jam-reply': se('answer', { deadlineMs: S30, cancelled: true, failed: REFUSED }),
246
+ 'jam-thread': se('answer', { deadlineMs: S30, cancelled: true, failed: REFUSED }),
247
+ } as const satisfies Record<string, CmdSpec>
248
+
249
+ export type CmdName = keyof typeof COMMANDS
250
+
251
+ /**
252
+ * #50, #51: how and where the input arrived. `keys` only for `via: 'key'` and key relays; `arg` a fixed identifier
253
+ * the command acts on (a Jam switch's name), never a value; `board`, `frames` (n) and `frame` what it acts on.
254
+ */
255
+ export interface CmdOpts { via: CmdVia; in: CmdIn; keys?: string; arg?: string; board?: string; frames?: number; frame?: string }
256
+
257
+ /**
258
+ * A command in flight. The first ending call wins; later ones are ignored, except a completion after `unobserved`
259
+ * (its deadline passed), written as a second `end` with `late: true`. `step` records a milestone (#49).
260
+ */
261
+ export interface CmdHandle {
262
+ /** 12 hex; '' when nothing records */
263
+ readonly id: string
264
+ readonly name: CmdName
265
+ done(): void
266
+ fail(why: string): void
267
+ noop(why: string): void
268
+ /** the person backed out, or another load or an edit took over (`why`: the cut's reason) */
269
+ cancel(why?: string): void
270
+ /** no signal can come (the page hid, a load timed out): `why` the reason; the deadline's own is `deadline` */
271
+ unobserved(why: string): void
272
+ step(name: string): void
273
+ }
274
+
275
+ const NOTHING: CmdHandle = { id: '', name: 'escape', done() {}, fail() {}, noop() {}, cancel() {}, unobserved() {}, step() {} }
276
+
277
+ // ---- the engine (the commands stream) -------------------------------------------------------------------------------
278
+
279
+ /** What a flight waits for, beside its own call site's ending: set from its signal (auto) or by a helper below. */
280
+ type Wait =
281
+ | { on: 'mode'; mode: ModeName; phase?: 'enter' | 'exit' }
282
+ | { on: 'acks' }
283
+ | { on: 'theme' }
284
+ | { on: 'stage'; at?: string }
285
+ | { on: 'load'; board: string; until: 'settled' | 'visible'; load?: string }
286
+ | { on: 'save'; board: string }
287
+ | { on: 'ready'; node: string; was?: string }
288
+ | { on: 'answer'; path: string; failed: string }
289
+
290
+ interface Flight {
291
+ id: string
292
+ name: CmdName
293
+ spec: CmdSpec
294
+ input: Record<string, unknown>
295
+ t0: number
296
+ started: boolean
297
+ ended: boolean
298
+ /** its deadline passed (or no signal can come): a later completion is a `late` end */
299
+ lapsed: boolean
300
+ steps: CmdStep[]
301
+ waits: Wait[]
302
+ /** `t`s minted while it was the current command (#26's acks), and the documents that acknowledged them */
303
+ ts: Set<string>
304
+ posts: number
305
+ acked: Set<string>
306
+ timer?: ReturnType<typeof setTimeout>
307
+ }
308
+
309
+ let current: string | undefined
310
+ let clearAt: ReturnType<typeof setTimeout> | undefined
311
+ const flights = new Map<string, Flight>()
312
+ let relay: CmdIn | null = null
313
+ let started = false
314
+
315
+ /** The start bucket (#48): 10/s, burst 20; what it refuses is counted and written once a second. */
316
+ const bucket = { tokens: CMD_BOUNDS.burst as number, at: 0 }
317
+ let refused = 0
318
+ let refusedTimer: ReturnType<typeof setTimeout> | undefined
319
+ function admit(now: number): boolean {
320
+ bucket.tokens = Math.min(CMD_BOUNDS.burst, bucket.tokens + ((now - bucket.at) / 1000) * CMD_BOUNDS.perSecond)
321
+ bucket.at = now
322
+ if (bucket.tokens >= 1) { bucket.tokens -= 1; return true }
323
+ refused++
324
+ refusedTimer ??= setTimeout(() => {
325
+ refusedTimer = undefined
326
+ const n = refused
327
+ refused = 0
328
+ if (n) write('dropped', { n, reason: 'cmd' })
329
+ }, 1_000)
330
+ return false
331
+ }
332
+
333
+ /** Every write, charged to `cmd` in `self` (#58). */
334
+ const write = hooked('cmd', (kind: 'cmd' | 'dropped', body: Record<string, unknown>) => perfSeams.record(kind, body))
335
+ const ms = (f: Flight) => Math.max(0, Math.round(performance.now() - f.t0))
336
+ const clean = (o: Record<string, unknown>) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined))
337
+
338
+ function writeStart(f: Flight): void {
339
+ if (f.started || f.spec.life === 'once') return
340
+ f.started = true
341
+ write('cmd', { phase: 'start', id: f.id, cmd: f.name, ...f.input })
342
+ }
343
+
344
+ type Outcome = 'done' | 'failed' | 'noop' | 'cancelled' | 'unobserved'
345
+ function end(f: Flight, outcome: Outcome, why?: string): void {
346
+ if (f.ended) {
347
+ // after `unobserved`: only a real completion is written again, once, as `late` (#49)
348
+ if (!f.lapsed || (outcome !== 'done' && outcome !== 'failed')) return
349
+ f.lapsed = false
350
+ write('cmd', clean({ phase: 'end', id: f.id, cmd: f.name, outcome, why, ms: ms(f), steps: f.steps.length ? f.steps : undefined, late: true }))
351
+ drop(f)
352
+ return
353
+ }
354
+ f.ended = true
355
+ const result = clean({ outcome, why, ms: ms(f), steps: f.steps.length ? f.steps : undefined })
356
+ // decided in its input's own turn: a `once` name, or a noop before its start went (#48)
357
+ if (f.spec.life === 'once' || (!f.started && outcome === 'noop')) write('cmd', { phase: 'once', id: f.id, cmd: f.name, ...f.input, ...result })
358
+ else { writeStart(f); write('cmd', { phase: 'end', id: f.id, cmd: f.name, ...result }) }
359
+ if (outcome === 'unobserved') {
360
+ // kept a while for a late completion: as long again as its deadline
361
+ f.lapsed = true
362
+ clearTimeout(f.timer)
363
+ f.timer = setTimeout(() => drop(f), f.spec.deadlineMs)
364
+ return
365
+ }
366
+ drop(f)
367
+ }
368
+ function drop(f: Flight): void {
369
+ clearTimeout(f.timer)
370
+ f.lapsed = false
371
+ flights.delete(f.id)
372
+ for (const w of f.waits) if (w.on === 'save') pendingSave.get(w.board)?.delete(f.id)
373
+ }
374
+
375
+ function handle(f: Flight): CmdHandle {
376
+ return {
377
+ id: f.id,
378
+ name: f.name,
379
+ done: () => end(f, 'done'),
380
+ fail: (why) => end(f, 'failed', why),
381
+ noop: (why) => end(f, 'noop', why),
382
+ cancel: (why) => end(f, 'cancelled', why),
383
+ unobserved: (why) => end(f, 'unobserved', why),
384
+ step: (name) => { if (!f.ended && f.steps.length < 16) f.steps.push({ name, ms: ms(f) }) },
385
+ }
386
+ }
387
+ const flightOf = (h: CmdHandle): Flight | undefined => (h.id ? flights.get(h.id) : undefined)
388
+
389
+ /** The one call every dispatch point makes (#52): the command named for the rest of this turn (`currentCmd()`), its
390
+ * start written at the end of the turn (a noop decided before then is one `once` record), and its declared signal
391
+ * waited for - a call site ends the rest itself (`answer`, `clipboard`, ...) or through a helper below. */
392
+ export function cmd(name: CmdName, o: CmdOpts): CmdHandle {
393
+ if (!perfSeams.on || !started || !fullRecorder()) return NOTHING
394
+ try {
395
+ const now = performance.now()
396
+ if (!admit(now)) return NOTHING
397
+ const spec: CmdSpec = COMMANDS[name]
398
+ const id = newId()
399
+ // a relayed menu item (#51): the key handler that runs it records it, as the relay it is
400
+ const via = relay && o.via === 'key' ? 'relay' : o.via
401
+ const where = relay && o.via === 'key' ? relay : o.in
402
+ const input = clean({ via, keys: via === 'key' || via === 'relay' ? o.keys : undefined, in: where, arg: o.arg, board: o.board, frames: o.frames, frame: o.frame })
403
+ const f: Flight = { id, name, spec, input, t0: now, started: false, ended: false, lapsed: false, steps: [], waits: [], ts: new Set(), posts: 0, acked: new Set() }
404
+ flights.set(id, f)
405
+ setCurrent(id)
406
+ queueMicrotask(() => { if (!f.ended) writeStart(f) })
407
+ f.timer = setTimeout(() => end(f, 'unobserved', 'deadline'), spec.deadlineMs)
408
+ autoWait(f, o)
409
+ return handle(f)
410
+ } catch { return NOTHING }
411
+ }
412
+
413
+ /** `current` names the command for the rest of its input's task: React's render and effects of the change it made
414
+ * (a sync-lane commit flushes them in a microtask) read it for `by`; the next task starts without it. */
415
+ function setCurrent(id: string): void {
416
+ current = id
417
+ clearTimeout(clearAt)
418
+ clearAt = setTimeout(() => { current = undefined }, 0)
419
+ }
420
+
421
+ /** The command whose input this turn is, for an effect's `by`; undefined when none. */
422
+ export const currentCmd = (): string | undefined => current
423
+
424
+ /** `fn` run as `id`'s effect: an effect started later in a command's chain (after an await) names it in `by`. */
425
+ export function withCmd<T>(id: string | undefined, fn: () => T): T {
426
+ const was = current
427
+ current = id || was
428
+ try { return fn() } finally { current = was }
429
+ }
430
+
431
+ /** The commands one request names when it carries a batch (the sidebar's queue, one tree write); else `current`. */
432
+ let carried: readonly string[] | undefined
433
+ const named = (): readonly string[] => carried ?? (current ? [current] : [])
434
+ /** `fn`'s requests name these commands (#18), and no other that happens to be current. */
435
+ export function withCmds<T>(ids: readonly string[], fn: () => T): T {
436
+ const was = carried
437
+ carried = ids
438
+ try { return fn() } finally { carried = was }
439
+ }
440
+ /**
441
+ * A write that waits its turn (a queue, a flush first) or goes again (a 409): the commands behind it, read now - in its
442
+ * command's own turn, or under `withCmd`/`withCmds` further along its chain - and put back around each request it
443
+ * sends, long after `current` has cleared (#18).
444
+ */
445
+ export function keepCmds(): <T>(send: () => T) => T {
446
+ const ids = named()
447
+ return (send) => withCmds(ids, send)
448
+ }
449
+
450
+ /** #51: a menu item relayed from the app (`runMenuItem`): the key handler that runs it records `via: 'relay'` with the
451
+ * menu it came from - `in: 'app'` from an app that does not say (1.0.0). */
452
+ export function relayed(from: CmdIn, fn: () => void): void {
453
+ const was = relay
454
+ relay = from
455
+ try { fn() } finally { relay = was }
456
+ }
457
+
458
+ /** A key as jam-keys.ts `descriptor()` writes it - `[Ctrl+][Meta+][Alt+][Shift+]key`, a letter lowercase - from the
459
+ * key the handler matched (`key` for an ⌥ letter or a shifted digit, which the event's own `key` misnames). */
460
+ export function keysOf(e: { key: string; shiftKey?: boolean; altKey?: boolean; metaKey?: boolean; ctrlKey?: boolean; shift?: boolean; alt?: boolean; meta?: boolean; ctrl?: boolean }, key = e.key): string {
461
+ const k = key === ' ' ? 'Space' : key
462
+ return `${e.ctrlKey || e.ctrl ? 'Ctrl+' : ''}${e.metaKey || e.meta ? 'Meta+' : ''}${e.altKey || e.alt ? 'Alt+' : ''}${e.shiftKey || e.shift ? 'Shift+' : ''}${k.length === 1 ? k.toLowerCase() : k}`
463
+ }
464
+
465
+ // ---- signals: what ends a command (#49) ---------------------------------------------------------------------------
466
+
467
+ /**
468
+ * The `mode` record (signals, #25) that ends each mode-applied or mode command: its own mode's transition, never the
469
+ * exit a switch makes on its way (⌥L with the laser on: `laser` exits, then `inspect` enters, and only that is applied).
470
+ * No `phase` for a toggle: the one record its press writes for that mode, enter or exit, is the one it meant.
471
+ */
472
+ const MODE_OF: Partial<Record<CmdName, { mode: ModeName; phase?: 'enter' | 'exit' }>> = {
473
+ comments: { mode: 'comments' }, laser: { mode: 'laser' }, inspect: { mode: 'inspect' }, interact: { mode: 'interact', phase: 'enter' }, 'interact-off': { mode: 'interact', phase: 'exit' },
474
+ }
475
+ /** The signals stream's transition ids (#21, #26): its `perfSeams.transition` replaces this default when it runs. */
476
+ const NO_TRANSITIONS = perfSeams.transition
477
+ /** `startCommands`' wrapper, and what it wraps. */
478
+ let wrapper: typeof perfSeams.transition | undefined
479
+ let wrapped = NO_TRANSITIONS
480
+ const signalsOn = () => (perfSeams.transition === wrapper ? wrapped : perfSeams.transition) !== NO_TRANSITIONS
481
+
482
+ function autoWait(f: Flight, o: CmdOpts): void {
483
+ switch (f.spec.done) {
484
+ case '2raf': endAfterFrames(handle(f)); return
485
+ case 'selection': queueMicrotask(() => end(f, 'done')); return
486
+ case 'camera': endOnCamera(handle(f)); return
487
+ case 'layout': watch(f, layoutDone); return
488
+ case 'mode-applied': case 'mode': {
489
+ const own = MODE_OF[f.name]
490
+ if (own) f.waits.push({ on: 'mode', ...own })
491
+ if (f.spec.done === 'mode-applied') f.waits.push({ on: 'acks' })
492
+ // without the stream that writes `mode` records and mints transitions, two frames after the change is the signal
493
+ // #26 itself uses for the modes no document acknowledges; with it, the acks or the record - and a change that
494
+ // posted to no document (none displayed) is applied once it rendered
495
+ frames(2, () => { if (!f.ended && (!signalsOn() || (!own && !f.posts))) end(f, 'done') })
496
+ return
497
+ }
498
+ case 'theme':
499
+ f.waits.push({ on: 'theme' })
500
+ frames(2, () => { if (!f.ended && !signalsOn()) end(f, 'done') })
501
+ return
502
+ case 'stage-shown': f.waits.push({ on: 'stage' }); return
503
+ case 'settled': if (o.board) f.waits.push({ on: 'load', board: o.board, until: 'settled' }); return
504
+ case 'save': if (o.board) endOnSave(handle(f), o.board); return
505
+ default:
506
+ }
507
+ }
508
+
509
+ const raf = (fn: () => void) => { try { requestAnimationFrame(fn) } catch { setTimeout(fn, 16) } }
510
+ function frames(n: number, fn: () => void): void { raf(() => (n <= 1 ? fn() : frames(n - 1, fn))) }
511
+
512
+ /** Ends `h` two animation frames after the change (the table's "2 rAF"): a page hidden meanwhile draws none, and its
513
+ * deadline says so. */
514
+ export function endAfterFrames(h: CmdHandle): void { const f = flightOf(h); if (f) frames(2, () => end(f, 'done')) }
515
+
516
+ /** Polls a flight's condition once per animation frame until it holds or the flight ends. */
517
+ function watch(f: Flight, cond: (st: { n: number; busy: boolean; sawBusy: boolean; since: number }) => boolean): void {
518
+ const st = { n: 0, busy: false, sawBusy: false, since: performance.now() }
519
+ const tick = () => {
520
+ if (f.ended) return
521
+ st.n++
522
+ st.busy = canvasCtl.cameraBusy()
523
+ if (st.busy) st.sawBusy = true
524
+ if (cond(st)) end(f, 'done')
525
+ else raf(tick)
526
+ }
527
+ raf(tick)
528
+ }
529
+ /** A fit or a zoom: the camera landed - it flew and came to rest, or rested for 250 ms (a fit to where it already is,
530
+ * or one a caller sends after a short delay). */
531
+ const cameraDone = (st: { n: number; busy: boolean; sawBusy: boolean; since: number }) => !st.busy && (st.sawBusy || performance.now() - st.since > 250) && st.n >= 2
532
+ /** A layout animation (`animateLayout`'s `sh-preset`) ended, and the fit after it landed. */
533
+ const layoutDone = (st: { n: number; busy: boolean; sawBusy: boolean; since: number }) => !canvasCtl.layoutBusy() && cameraDone(st)
534
+
535
+ /** Ends `h` when the camera lands (`fit-*`, `zoom-*`, a pick, `next-new`, a goto on this board). */
536
+ export function endOnCamera(h: CmdHandle): void { const f = flightOf(h); if (f) watch(f, cameraDone) }
537
+ /** Ends `h` on the next load of `board` after it: `settled` (with its steps, #49), or its `visible` (a goto's). */
538
+ export function endOnLoad(h: CmdHandle, board: string, until: 'settled' | 'visible' = 'settled'): void {
539
+ const f = flightOf(h)
540
+ if (!f) return
541
+ f.waits = f.waits.filter((w) => w.on !== 'load')
542
+ f.waits.push({ on: 'load', board, until })
543
+ }
544
+ /** Ends `h` on the play stage's `sh:stage-shown` - of `at` when given (the screen it walks to) - or fails it on a
545
+ * stage error when its row lists `stage-error`. */
546
+ export function endOnStage(h: CmdHandle, at?: string): void {
547
+ const f = flightOf(h)
548
+ if (!f) return
549
+ f.waits = f.waits.filter((w) => w.on !== 'stage')
550
+ f.waits.push({ on: 'stage', at })
551
+ }
552
+ /** Ends `h` on the `ready` of the document that replaces the one node `node` shows now (a reload by hand, asked before it
553
+ * navigates), or fails it on that document's `sh:error`. */
554
+ export function endOnReady(h: CmdHandle, node: string): void { const f = flightOf(h); if (f) f.waits.push({ on: 'ready', node, was: bootOf(iframeOf(node)) }) }
555
+ /** `h` changed `board`: it ends when the save carrying its id landed (#18, #49) - `save-conflict` on a 409. */
556
+ export function endOnSave(h: CmdHandle, board: string): void {
557
+ const f = flightOf(h)
558
+ if (!f || f.waits.some((w) => w.on === 'save')) return
559
+ f.waits.push({ on: 'save', board })
560
+ const p = pendingSave.get(board) ?? new Set<string>()
561
+ p.add(f.id)
562
+ pendingSave.set(board, p)
563
+ }
564
+
565
+ /** Ends `h` on the answer to the next request to `/api/<path>` after it (the marks write, a pin): ok → done, else
566
+ * `failed` with `code`. */
567
+ export function endOnAnswer(h: CmdHandle, path: string, code = 'api'): void { const f = flightOf(h); if (f) f.waits.push({ on: 'answer', path, failed: code }) }
568
+
569
+ // ---- board writes (#18): the ids a write carries, and its answer -----------------------------------------------------
570
+
571
+ /** Commands that changed a board, waiting for the save that carries them. */
572
+ const pendingSave = new Map<string, Set<string>>()
573
+ /** Commands that changed the board and end on their own signal (a tidy, a theme pin, a device): the next save still
574
+ * names them (#18). A short list: what a save cannot carry is counted, never kept. */
575
+ const folded: string[] = []
576
+ let foldedLost = 0
577
+ /** `h` changed the open board and ends elsewhere: the debounced save that follows names it (#18). */
578
+ export function foldsIntoSave(h: CmdHandle): void {
579
+ if (!h.id) return
580
+ folded.push(h.id)
581
+ if (folded.length > CMD_BOUNDS.writeIds * 8) { folded.shift(); foldedLost++ }
582
+ }
583
+ /** A board's save PUT (store.ts `save`): `${ROUTE}/api/boards/<name>`. */
584
+ const SAVE_URL = /\/api\/boards\/([^/?#]+)(?:[?#]|$)/
585
+
586
+ /**
587
+ * #18: the commands folded into a board write this page is about to send - a debounced save carries every command
588
+ * that changed the board since its last save, a single write the command behind it - at most 8 ids, plus their count.
589
+ * Read once per request by the edits stream's `perfSeams.requestHeaders` (`x-mv-cmds`); the commands stream keeps the
590
+ * list, and ends those waiting on the write from `perfSeams.answered` (its headers carry the ids).
591
+ */
592
+ export function cmdsForWrite(board: string, route: string): Candidates {
593
+ // any other write: the commands behind it
594
+ if (!(route === 'save' || route === 'boards/:board' || route.endsWith(`boards/${board}`) || route.endsWith(`boards/${encodeURIComponent(board)}`))) {
595
+ const c = named()
596
+ return { ids: c.slice(0, CMD_BOUNDS.writeIds), n: c.length }
597
+ }
598
+ // the board's own save: every command since the last one
599
+ const ids = [...new Set([...(pendingSave.get(board) ?? []), ...folded])]
600
+ const n = ids.length + foldedLost
601
+ pendingSave.delete(board)
602
+ folded.length = 0
603
+ foldedLost = 0
604
+ return { ids: ids.slice(0, CMD_BOUNDS.writeIds), n }
605
+ }
606
+
607
+ function answered(a: Answered): void {
608
+ if (!flights.size) return
609
+ const ok = typeof a.status === 'number' && a.status >= 200 && a.status < 300
610
+ const sentAt = performance.now() - a.ms
611
+ for (const [f, w] of waiting('answer')) {
612
+ if (f.t0 > sentAt + 1 || !a.url.split(/[?#]/)[0].endsWith(`/api/${w.path}`)) continue
613
+ f.waits = f.waits.filter((x) => x !== w)
614
+ if (ok) end(f, 'done'); else end(f, 'failed', w.failed)
615
+ }
616
+ const outcome = (f: Flight) => (ok ? end(f, 'done') : end(f, 'failed', a.status === 409 && f.spec.failed?.includes('save-conflict') ? 'save-conflict' : 'save-failed'))
617
+ const header = a.headers?.[WRITER_HEADERS.cmds]
618
+ const carried = decodeCmds(header)
619
+ if (carried) {
620
+ for (const id of carried.ids) { const f = flights.get(id); if (f?.waits.some((w) => w.on === 'save')) outcome(f) }
621
+ return
622
+ }
623
+ // no `x-mv-cmds` on it (a page whose writes do not name their commands): the board's save ends the commands that
624
+ // were waiting before it was sent
625
+ const m = SAVE_URL.exec(a.url)
626
+ if (!m || (a.init.method ?? 'GET').toUpperCase() !== 'PUT') return
627
+ const board = decodeURIComponent(m[1])
628
+ for (const id of [...(pendingSave.get(board) ?? [])]) {
629
+ const f = flights.get(id)
630
+ if (f && f.t0 <= sentAt) { pendingSave.get(board)?.delete(id); outcome(f) }
631
+ }
632
+ }
633
+
634
+ // ---- what the shell's documents and loads say -------------------------------------------------------------------------
635
+
636
+ function waiting<W extends Wait['on']>(on: W): [Flight, Extract<Wait, { on: W }>][] {
637
+ const out: [Flight, Extract<Wait, { on: W }>][] = []
638
+ for (const f of flights.values()) for (const w of f.waits) if (w.on === on) out.push([f, w as Extract<Wait, { on: W }>])
639
+ return out
640
+ }
641
+
642
+ /** A record the page writes - signals' `mode` and `theme` (#23, #25) name the command behind them in `by`. */
643
+ function observed(kind: string, body: Record<string, unknown>): void {
644
+ if (kind !== 'mode' && kind !== 'theme') return
645
+ const by = typeof body.by === 'string' ? body.by : undefined
646
+ const outcome = body.outcome
647
+ const finish = (f: Flight) => (outcome === 'timeout' ? end(f, 'unobserved', 'timeout') : outcome === 'superseded' ? end(f, 'cancelled', 'superseded') : end(f, 'done'))
648
+ if (kind === 'theme') {
649
+ const ws = waiting('theme')
650
+ const f = by ? ws.find(([x]) => x.id === by)?.[0] : ws.length === 1 ? ws[0][0] : undefined
651
+ if (f) finish(f)
652
+ return
653
+ }
654
+ const ws = waiting('mode').filter(([, w]) => w.mode === body.mode && (!w.phase || w.phase === body.phase))
655
+ const f = by ? ws.find(([x]) => x.id === by)?.[0] : ws.length === 1 ? ws[0][0] : undefined
656
+ if (f) finish(f)
657
+ }
658
+
659
+ /** A document's message (a frame's or the stage's): acks, readies, the stage's screens. */
660
+ function message(node: string | null, data: Record<string, unknown>): void {
661
+ if (!flights.size) return
662
+ const type = data.type
663
+ if (type === 'sh:mode-applied') {
664
+ const t = String(data.t ?? '')
665
+ for (const [f] of waiting('acks')) {
666
+ if (!f.ts.has(t)) continue
667
+ f.acked.add(`${t}:${String(data.boot ?? node ?? '')}`)
668
+ if (f.posts && f.acked.size >= f.posts) end(f, 'done')
669
+ }
670
+ } else if (node && (type === 'sh:ready' || type === 'sh:error')) {
671
+ // told before App.tsx's own guard: a message still on its way from the document since replaced, or from the one
672
+ // being replaced until its navigation commits, says nothing of the reload
673
+ const iframe = iframeOf(node)
674
+ if (!iframe || !fromLiveDocument(iframe, data)) return
675
+ for (const [f, w] of waiting('ready')) if (w.node === node && data.boot !== w.was) (type === 'sh:ready' ? end(f, 'done') : end(f, 'failed', 'error'))
676
+ } else if (!node && type === 'sh:stage-shown') {
677
+ const at = String(data.at ?? '')
678
+ for (const [f, w] of waiting('stage')) if (!w.at || w.at === at) end(f, 'done')
679
+ } else if (!node && type === 'sh:stage-error') {
680
+ for (const [f] of waiting('stage')) if (f.spec.failed?.includes('stage-error')) end(f, 'failed', 'stage-error')
681
+ }
682
+ }
683
+
684
+ /** A load's way (#49): `board-open`, `history-nav` and a goto to another board end on theirs. */
685
+ function loadPhase(p: LoadPhase): void {
686
+ for (const [f, w] of waiting('load')) {
687
+ if (p.phase === 'request') { if (!w.load && p.board === w.board) w.load = p.load; continue }
688
+ if (w.load !== p.load) continue
689
+ const h = handle(f)
690
+ switch (p.phase) {
691
+ case 'visible': h.step('visible'); if (w.until === 'visible') end(f, 'done'); break
692
+ case 'visible-ready': h.step('visible-ready'); break
693
+ // a request already cut mounted all the same: a milestone, never the completion (#49)
694
+ case 'commit': if (p.late) { if (f.ended && f.lapsed) f.steps.push({ name: 'commit-late', ms: ms(f) }); else h.step('commit-late') } break
695
+ case 'settled': end(f, 'done'); break
696
+ case 'cut': {
697
+ const r = p.reason
698
+ if (r === 'hidden' || r === 'timeout') end(f, 'unobserved', r)
699
+ else if (r === 'unsaved') end(f, 'failed', 'save-blocked')
700
+ else if (r === 'error') end(f, 'failed', 'load-error')
701
+ else end(f, 'cancelled', r)
702
+ }
703
+ }
704
+ }
705
+ }
706
+
707
+ /** #26's acks: the transition ids minted while a mode command was the current one. */
708
+ function minted(kind: 'theme' | 'mode', t: string | undefined): void {
709
+ if (!t || kind !== 'mode' || !current) return
710
+ const f = flights.get(current)
711
+ if (!f || f.ended || !f.waits.some((w) => w.on === 'acks')) return
712
+ f.ts.add(t)
713
+ f.posts++
714
+ }
715
+
716
+ /** The id `shell-reload` keeps across the reload it asks for: the next page writes its end (the table's row). */
717
+ const RELOAD_KEY = 'mv-cmd-reload'
718
+ /** `shell-reload`: its start now, kept for the page the reload brings, which writes its end at its own start. */
719
+ export function shellReload(h: CmdHandle): void {
720
+ const f = flightOf(h)
721
+ if (!f) return
722
+ writeStart(f)
723
+ try { sessionStorage.setItem(RELOAD_KEY, JSON.stringify({ id: f.id, cmd: f.name, at: Date.now() - ms(f) })) } catch { /* storage off: its end cannot come, and the reader says so */ }
724
+ }
725
+ function reloaded(): void {
726
+ try {
727
+ const raw = sessionStorage.getItem(RELOAD_KEY)
728
+ if (!raw) return
729
+ sessionStorage.removeItem(RELOAD_KEY)
730
+ const r = JSON.parse(raw) as { id?: unknown; cmd?: unknown; at?: unknown }
731
+ if (typeof r.id !== 'string' || !ID12.test(r.id) || r.cmd !== 'shell-reload' || typeof r.at !== 'number') return
732
+ write('cmd', { phase: 'end', id: r.id, cmd: 'shell-reload', outcome: 'done', ms: Math.max(0, Math.round(Date.now() - r.at)) })
733
+ } catch { /* storage off */ }
734
+ }
735
+
736
+ /** recorder.ts `startRecorder`, at the full level: the rate bucket, the deadline timers, the listeners. */
737
+ export function startCommands(): void {
738
+ if (started) return
739
+ started = true
740
+ bucket.at = performance.now()
741
+ // signals' records and transition ids, seen as they are written and minted (their streams start first)
742
+ const record = perfSeams.record
743
+ perfSeams.record = (kind, body, load) => { record(kind, body, load); try { observed(kind, body) } catch { /* never in the way */ } }
744
+ wrapped = perfSeams.transition
745
+ wrapper = perfSeams.transition = (kind) => { const t = wrapped(kind); try { minted(kind, t) } catch { /* never in the way */ } return t }
746
+ perfSeams.frameMessage.on(hooked('cmd', (node: string, data: Record<string, unknown>) => message(node, data)))
747
+ perfSeams.stageMessage.on(hooked('cmd', (data: Record<string, unknown>) => message(null, data)))
748
+ perfSeams.load.on(hooked('cmd', loadPhase))
749
+ perfSeams.answered.on(hooked('cmd', answered))
750
+ reloaded()
751
+ if (import.meta.env.DEV) (window as unknown as { __mvCommands: unknown }).__mvCommands = { flights: () => [...flights.values()].map((f) => ({ id: f.id, name: f.name, started: f.started, ended: f.ended, waits: f.waits.map((w) => w.on) })) }
752
+ }
753
+
754
+ /**
755
+ * Forwarding paths with declared owners (R16 static gate): an input recorded elsewhere, and where. The walk checks that
756
+ * each owner exists and records. The app's twin is app/src/main/commands.ts `APP_RELAYS`.
757
+ */
758
+ export interface Relay { from: string; owner: string; why: string }
759
+ export const RELAYS: readonly Relay[] = [
760
+ { from: 'ContextMenu.tsx dispatcher (:71)', owner: "each MenuItem's onClick", why: 'each item is an input site of its own' },
761
+ { from: "a frame's post({ type }) (bridge.js, inspect.js, keys.js)", owner: "App.tsx's frame message branch for that type", why: 'the shell executes it' },
762
+ { from: "the stage's post({ type }) (stage/main.tsx)", owner: "Play.tsx's stage message branch for that type", why: 'the shell executes it' },
763
+ { from: 'app-bridge.ts runMenuItem (a synthetic keydown)', owner: "App.tsx's key handler branch", why: "#51: via 'relay', in 'menu', 'tab-menu' or 'app'" },
764
+ { from: "app-bridge.ts runMenuItem('mark-all-seen')", owner: 'mark-seen', why: "#51: via 'relay', in 'tab-menu'" },
765
+ ]