@marver-design/marver 0.29.0 → 0.30.0

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 +44 -0
  2. package/README.md +2 -1
  3. package/dist/{anchor-check-DhlpKl2K.mjs → anchor-check-c52IDkiQ.mjs} +1 -1
  4. package/dist/{build-CWbrb2bl.mjs → build-C3mUtjEn.mjs} +5 -4
  5. package/dist/cli.mjs +5 -5
  6. package/dist/{daemon-Sc_z8gT6.mjs → daemon-B0Wi1OQ3.mjs} +5 -3
  7. package/dist/{dev-DWBKQhxf.mjs → dev-5dlxoW28.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-CXRoMA8g.mjs} +898 -539
  11. package/dist/{poster-CrsjqhY4.mjs → poster-CYmCa00B.mjs} +1 -1
  12. package/dist/{publish-bakes-DW-NDgU2.mjs → publish-bakes-C_2ZtHou.mjs} +2 -2
  13. package/dist/{recover-GtJ9UDAB.mjs → recover-XD8iXJOj.mjs} +1 -1
  14. package/dist/{shot-T04Ixrvq.mjs → shot-CRRGgxru.mjs} +3 -3
  15. package/docs/app.md +194 -0
  16. package/docs/performance.md +98 -18
  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 +115 -41
  68. package/src/client/shell/store.ts +56 -22
  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
@@ -13,7 +13,8 @@ import { useEffect, useRef, useState, type CSSProperties } from 'react'
13
13
  import { setSessionEnding, useJamCapture } from './jam-capture.ts'
14
14
  import { laneCards, startCapture } from './jam-keys.ts'
15
15
  import { useJamQueue, type JamCard } from './jam-queue.ts'
16
- import { useJamUi } from './jam-state.ts'
16
+ import { endOnOk, useJamUi } from './jam-state.ts'
17
+ import { cmd, endAfterFrames, keysOf, type CmdHandle, type CmdOpts } from './commands.ts'
17
18
  import { JamStateIcon } from './jam-ui.tsx'
18
19
  import { Marver, moreDraftOf, setMoreDraft } from './jam-panel.tsx'
19
20
  import { useJamVoice, voiceSession, voiceSessionEnd, voiceSessionId } from './jam-voice.ts'
@@ -26,6 +27,7 @@ import { api, STOPPED_TIP, useStopped } from './api.ts'
26
27
 
27
28
  const csrf = () => /(?:^|;\s*)mv_c=([\w-]+)/.exec(document.cookie)?.[1] ?? ''
28
29
  const now = () => performance.timeOrigin + performance.now()
30
+ const CLICK: CmdOpts = { via: 'click', in: 'shell' }
29
31
 
30
32
  // ---- the session's moves -------------------------------------------------------------------------------
31
33
 
@@ -110,11 +112,11 @@ let endingOp = 0
110
112
 
111
113
 
112
114
  /** `J` (or the Jam button): at rest, the start sheet (again: closes it); in a session, the wrap-up - a
113
- * capture recording ends first, and the wrap-up waits for its read-back to close. */
114
- export function pressJ() {
115
+ * capture recording ends first, and the wrap-up waits for its read-back to close. `h`: its `jam-session`, from the input. */
116
+ export function pressJ(h: CmdHandle) {
115
117
  const ui = useJamUi.getState()
116
118
  // the canvas stopped (spec 28 A1.11): a sheet open still closes; nothing new starts or wraps up
117
- if (!ui.sheet && stoppedFor('Jam needs the canvas running')) return
119
+ if (!ui.sheet && stoppedFor('Jam needs the canvas running')) { h.noop('stopped'); return }
118
120
  if (!useJamQueue.getState().session) { ui.setSheet(ui.sheet === 'start' ? null : 'start'); return }
119
121
  if (ui.sheet === 'wrap' || ui.sheet === 'wrap-pending') { ui.setSheet(null); return }
120
122
  if (useJamCapture.getState().current) { useJamCapture.getState().end(true); ui.setSheet('wrap-pending'); return }
@@ -142,7 +144,7 @@ export function JamButton({ inPlay }: { inPlay?: boolean }) {
142
144
  return (
143
145
  <Tip side="bottom" inv={inPlay} label={label}>
144
146
  <button className={`sh-pill-btn jm-jam${state !== 'idle' ? ` ${state}` : ''}${sheet === 'start' || sheet === 'wrap' ? ' press' : ''}${stopped ? ' off' : ''}`}
145
- data-jam-button={state} data-stopped={stopped ? '' : undefined} aria-disabled={stopped || undefined} aria-label={session ? 'End the Jam session' : 'Jam session'} onClick={pressJ}>
147
+ data-jam-button={state} data-stopped={stopped ? '' : undefined} aria-disabled={stopped || undefined} aria-label={session ? 'End the Jam session' : 'Jam session'} onClick={() => pressJ(cmd('jam-session', { via: 'click', in: 'pill' }))}>
146
148
  {/* the whole session reads as on: the dot pulses from start to end, between captures too */}
147
149
  {session || recording ? <i className="jm-live-dot" /> : <WaveformIcon size={16} />}
148
150
  {session && <span className="jm-clock">{minutes}</span>}
@@ -201,7 +203,8 @@ function WhoWorks({ fallback }: { fallback: string }) {
201
203
  const next = sessions.length > 1 ? sessions[(sessions.findIndex((x) => x.selected) + 1) % sessions.length] : undefined
202
204
  // the Codex hint only for someone who is not working in another session now: it is noise to a Claude Code user
203
205
  const trust = !sel && info?.connectors?.some((c) => c.agent === 'codex' && c.state === 'installed') && !sessions.some((x) => x.agent === 'codex')
204
- const set = useJamQueue.getState().setPrefs
206
+ // a switch's name, never its value; the command ends on the save's answer
207
+ const set = (arg: string, p: Parameters<ReturnType<typeof useJamQueue.getState>['setPrefs']>[0]) => void endOnOk(cmd('jam-pref', { ...CLICK, arg }), useJamQueue.getState().setPrefs(p), 'api')
205
208
  const sw = (on: boolean) => <span className="v">{on ? 'On' : 'Off'}<i className={`jm-switch${on ? ' on' : ''}`} /></span>
206
209
  return (<>
207
210
  {(() => {
@@ -211,16 +214,16 @@ function WhoWorks({ fallback }: { fallback: string }) {
211
214
  {sel && <span className="v"><span className="jm-agent"><i /></span></span>}
212
215
  </>)
213
216
  return next
214
- ? <button className="row jm-two" data-jam-who={sel ? sel.agent : 'background'} onClick={() => void set({ pick: next.id })}>{body}</button>
217
+ ? <button className="row jm-two" data-jam-who={sel ? sel.agent : 'background'} onClick={() => set('agent', { pick: next.id })}>{body}</button>
215
218
  : <div className="row jm-two" data-jam-who={sel ? sel.agent : 'background'}>{body}</div>
216
219
  })()}
217
- <button className="row jm-two" data-jam-switch="mcp" onClick={() => void set({ mcp: !settings.mcp, skills: !settings.mcp })}>
220
+ <button className="row jm-two" data-jam-switch="mcp" onClick={() => set('mcp', { mcp: !settings.mcp, skills: !settings.mcp })}>
218
221
  <LinkIcon size={15} /><span>MCP servers and skills<br /><small>Background runs use yours</small></span>{sw(settings.mcp)}
219
222
  </button>
220
- <button className="row jm-two" data-jam-switch="context" onClick={() => void set({ context: context ? 'fresh' : 'fork' })}>
223
+ <button className="row jm-two" data-jam-switch="context" onClick={() => set('context', { context: context ? 'fresh' : 'fork' })}>
221
224
  <NotebookIcon size={15} /><span>Your session's context<br /><small>Your session or a copy works</small></span>{sw(context)}
222
225
  </button>
223
- <button className="row jm-two" data-jam-switch="others" onClick={() => void set({ others: !settings.others })}>
226
+ <button className="row jm-two" data-jam-switch="others" onClick={() => set('collaborators', { others: !settings.others })}>
224
227
  <CommentIcon size={15} /><span>Collaborators' comments<br /><small>Their words reach the agent</small></span>{sw(settings.others)}
225
228
  </button>
226
229
  {trust && <div className="note-line" style={{ margin: '4px 8px' }}><WarningIcon size={14} /><span>Codex runs go to a copy of your session. To let your open Codex session take them itself, type <code style={{ color: 'inherit' }}>/hooks</code> in Codex once and trust Marver's.</span></div>}
@@ -239,7 +242,7 @@ export function StartSheet({ style }: { style?: CSSProperties }) {
239
242
  <p>Start captures at once. Between captures the session stays on; S captures again, J wraps up.</p>
240
243
  </div>
241
244
  <div className="rows">
242
- <button className="row" data-jam-mic-switch={mic ? 'on' : 'off'} onClick={() => voice.setChoice(mic ? 'no' : 'yes')}>
245
+ <button className="row" data-jam-mic-switch={mic ? 'on' : 'off'} onClick={() => { const h = cmd('jam-pref', { ...CLICK, arg: 'mic' }); void voice.setChoice(mic ? 'no' : 'yes'); h.done() }}>
243
246
  {mic ? <MicrophoneIcon size={15} /> : <MicrophoneSlashIcon size={15} />}
244
247
  <span>Microphone<br /><small>Transcribed on this Mac{CONFIG.jam?.names ? ' · Claude Haiku names each capture from its words, sent to Anthropic' : ''}</small></span>
245
248
  <span className="v">{mic ? 'On' : 'Off'}<i className={`jm-switch${mic ? ' on' : ''}`} /></span>
@@ -251,8 +254,8 @@ export function StartSheet({ style }: { style?: CSSProperties }) {
251
254
  <ShortcutsRow />
252
255
  <div className="actions">
253
256
  <span className="sp" />
254
- <button className="jm-btn ghost" onClick={() => useJamUi.getState().setSheet(null)}>Not now</button>
255
- <button className="jm-btn primary" onClick={() => void startSession()}>Start <kbd>⏎</kbd></button>
257
+ <button className="jm-btn ghost" onClick={() => { cmd('jam-sheet-close', CLICK); useJamUi.getState().setSheet(null) }}>Not now</button>
258
+ <button className="jm-btn primary" onClick={() => void endOnOk(cmd('jam-start', CLICK), startSession())}>Start <kbd>⏎</kbd></button>
256
259
  </div>
257
260
  </div>
258
261
  )
@@ -260,8 +263,8 @@ export function StartSheet({ style }: { style?: CSSProperties }) {
260
263
 
261
264
  // ---- the wrap-up ----------------------------------------------------------------------------------------------
262
265
 
263
- /** The open wrap-up sheet's Write the record (the key row calls it). */
264
- export const wrapWrite: { current: (() => void) | null } = { current: null }
266
+ /** The open wrap-up sheet's Write the record (the key row calls it, with its `jam-wrap-send`). */
267
+ export const wrapWrite: { current: ((h: CmdHandle) => void) | null } = { current: null }
265
268
 
266
269
  const STATE_NOTE: Partial<Record<JamCard['state'], string>> = {
267
270
  draft: 'to confirm', confirming: 'sending', queued: 'queued', working: 'with the agent', asks: 'asks you', review: 'to review',
@@ -294,15 +297,15 @@ export function WrapSheet({ style }: { style?: CSSProperties }) {
294
297
  const caps = laneCards(cards, run).filter((c) => c.kind === 'capture' && c.session === session.id && c.state !== 'dropped')
295
298
  const name = agent ? HARNESS[agent] ?? agent : 'your agent'
296
299
  // Write is busy until the server answers THIS try (an older try's late end never frees it)
297
- const write = async () => {
298
- if (busy) return
300
+ const write = async (h: CmdHandle) => {
301
+ if (busy) { h.noop('busy'); return }
299
302
  const n = ++tries.current
300
303
  setBusy(true)
301
- await endSession({ instructions: text.trim(), includeTalk: talk }, () => { if (n === tries.current) setBusy(false) })
304
+ await endOnOk(h, endSession({ instructions: text.trim(), includeTalk: talk }, () => { if (n === tries.current) setBusy(false) }))
302
305
  if (n === tries.current) setBusy(false)
303
306
  }
304
307
  // ⏎ anywhere in the sheet writes the record - it never reaches a panel beneath it (jam-keys' sheet row)
305
- wrapWrite.current = () => void write()
308
+ wrapWrite.current = (h) => void write(h)
306
309
  const summary = caps.length
307
310
  ? `${caps.length} capture${caps.length === 1 ? '' : 's'} in ${minutes} min.`
308
311
  : `No captures in ${minutes} min.`
@@ -329,12 +332,12 @@ export function WrapSheet({ style }: { style?: CSSProperties }) {
329
332
  onKeyDown={(e) => {
330
333
  e.stopPropagation()
331
334
  if ((e.nativeEvent as unknown as { isComposing?: boolean }).isComposing) return
332
- if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); void write() }
333
- else if (e.key === 'Escape') { e.preventDefault(); useJamUi.getState().setSheet(null) }
335
+ if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); void write(cmd('jam-wrap-send', { via: 'key', in: 'shell', keys: keysOf(e) })) }
336
+ else if (e.key === 'Escape') { e.preventDefault(); cmd('jam-sheet-close', { via: 'key', in: 'shell', keys: keysOf(e) }); useJamUi.getState().setSheet(null) }
334
337
  }} />
335
338
  </div>
336
339
  <div className="rows">
337
- <button className="row" data-jam-talk={talk ? 'on' : 'off'} onClick={() => setTalk(!talk)}>
340
+ <button className="row" data-jam-talk={talk ? 'on' : 'off'} onClick={() => { cmd('jam-talk', CLICK); setTalk(!talk) }}>
338
341
  <span>Include what was said between captures</span>
339
342
  <span className="v">{talkMin ? <small>{talkMin} min</small> : null}<i className={`jm-switch${talk ? ' on' : ''}`} /></span>
340
343
  </button>
@@ -343,9 +346,9 @@ export function WrapSheet({ style }: { style?: CSSProperties }) {
343
346
  {name} reads your instructions, every capture you sent or kept with its reply, and your verdicts{talk ? ', and what was said between captures' : ''}. It writes one page{folder ? <> in <code>{folder}</code></> : null} and nothing else.
344
347
  </p>
345
348
  <div className="actions">
346
- <button className="jm-btn ghost" onClick={() => void endSession(null)}>End without a record</button>
349
+ <button className="jm-btn ghost" onClick={() => void endOnOk(cmd('jam-end-bare', CLICK), endSession(null))}>End without a record</button>
347
350
  <span className="sp" />
348
- <button className="jm-btn primary" disabled={busy} onClick={() => void write()}>Write the record <kbd>⏎</kbd></button>
351
+ <button className="jm-btn primary" disabled={busy} onClick={() => void write(cmd('jam-wrap-send', CLICK))}>Write the record <kbd>⏎</kbd></button>
349
352
  </div>
350
353
  </div>
351
354
  )
@@ -356,9 +359,10 @@ export function WrapSheet({ style }: { style?: CSSProperties }) {
356
359
  /** A session record (a wrap-up card): the page the agent wrote, its reply, and the review's moves. */
357
360
  export function RecordDetail({ card, agent, more, onMore, onMoreOpen, onGood, onLater, onRetry, onDrop, of, onPrev, onNext }: {
358
361
  card: JamCard; agent: string; more: boolean; of?: [number, number]
359
- onMore(text: string): void; onMoreOpen(on: boolean): void; onGood(): void; onLater(): void
362
+ /** each ends the command its button started (spec 30), from the handle it is handed */
363
+ onMore(text: string, h: CmdHandle): void; onMoreOpen(on: boolean): void; onGood(h: CmdHandle): void; onLater(h: CmdHandle): void
360
364
  /** a record job that failed: try it again, or let it go */
361
- onRetry(): void; onDrop(): void
365
+ onRetry(h: CmdHandle): void; onDrop(h: CmdHandle): void
362
366
  onPrev?: () => void; onNext?: () => void
363
367
  }) {
364
368
  const [rec, setRec] = useState<{ file: string; text: string | null; reply?: string } | null>(null)
@@ -384,8 +388,8 @@ export function RecordDetail({ card, agent, more, onMore, onMoreOpen, onGood, on
384
388
  <JamStateIcon state={card.state as any} />
385
389
  <h3>{card.title ?? 'Session record'}</h3>
386
390
  {of && <><span className="dim">{of[0]} of {of[1]}</span>
387
- <button className="jm-iconbtn" disabled={!onPrev} onClick={onPrev} aria-label="Previous"><CaretIcon size={11} style={{ transform: 'rotate(90deg)' }} /></button>
388
- <button className="jm-iconbtn" disabled={!onNext} onClick={onNext} aria-label="Next"><CaretIcon size={11} style={{ transform: 'rotate(-90deg)' }} /></button></>}
391
+ <button className="jm-iconbtn" disabled={!onPrev} onClick={() => { cmd('jam-step', { ...CLICK, arg: 'prev' }); onPrev?.() }} aria-label="Previous"><CaretIcon size={11} style={{ transform: 'rotate(90deg)' }} /></button>
392
+ <button className="jm-iconbtn" disabled={!onNext} onClick={() => { cmd('jam-step', { ...CLICK, arg: 'next' }); onNext?.() }} aria-label="Next"><CaretIcon size={11} style={{ transform: 'rotate(-90deg)' }} /></button></>}
389
393
  </div>
390
394
  <div className="meta"><span><code>{rec?.file ?? card.file ?? 'context/sessions/'}</code></span><i /><span>{agent}</span></div>
391
395
  {rec?.reply && <div className="jm-reply"><Marver size={20} /><p>{rec.reply}</p></div>}
@@ -397,8 +401,8 @@ export function RecordDetail({ card, agent, more, onMore, onMoreOpen, onGood, on
397
401
  {failed && <div className="rule" />}
398
402
  {failed && (
399
403
  <div className="actions">
400
- <button className="jm-btn primary" data-jam-run-act="retry" onClick={onRetry}>Retry</button>
401
- <button className="jm-btn ghost" data-jam-run-act="drop" onClick={onDrop}>Drop</button>
404
+ <button className="jm-btn primary" data-jam-run-act="retry" onClick={() => onRetry(cmd('jam-retry', CLICK))}>Retry</button>
405
+ <button className="jm-btn ghost" data-jam-run-act="drop" onClick={() => onDrop(cmd('jam-drop', CLICK))}>Drop</button>
402
406
  </div>
403
407
  )}
404
408
  {review && <div className="rule" />}
@@ -409,16 +413,16 @@ export function RecordDetail({ card, agent, more, onMore, onMoreOpen, onGood, on
409
413
  onKeyDown={(e) => {
410
414
  e.stopPropagation()
411
415
  if ((e.nativeEvent as unknown as { isComposing?: boolean }).isComposing) return
412
- if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); if (note.trim()) onMore(note.trim()) }
413
- if (e.key === 'Escape') { e.preventDefault(); setNote(''); onMoreOpen(false) }
416
+ if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); if (note.trim()) onMore(note.trim(), cmd('jam-more-send', { via: 'key', in: 'shell', keys: keysOf(e) })) }
417
+ if (e.key === 'Escape') { e.preventDefault(); cmd('jam-field-discard', { via: 'key', in: 'shell', keys: keysOf(e), arg: 'more' }); setNote(''); onMoreOpen(false) }
414
418
  }} />
415
- <button className="jm-send" disabled={!note.trim()} onClick={() => onMore(note.trim())}>Send <kbd>⏎</kbd></button>
419
+ <button className="jm-send" disabled={!note.trim()} onClick={() => onMore(note.trim(), cmd('jam-more-send', CLICK))}>Send <kbd>⏎</kbd></button>
416
420
  </div>
417
421
  ) : (
418
422
  <div className="actions">
419
- <button className="jm-btn primary" onClick={onGood}>Looks good <kbd>⏎</kbd></button>
420
- <button className="jm-btn" onClick={() => onMoreOpen(true)}>More work <kbd>⇧⏎</kbd></button>
421
- <button className="jm-btn ghost" onClick={onLater}>Later <kbd>→</kbd></button>
423
+ <button className="jm-btn primary" onClick={() => onGood(cmd('jam-good', CLICK))}>Looks good <kbd>⏎</kbd></button>
424
+ <button className="jm-btn" onClick={() => { const h = cmd('jam-more', CLICK); onMoreOpen(true); endAfterFrames(h) }}>More work <kbd>⇧⏎</kbd></button>
425
+ <button className="jm-btn ghost" onClick={() => onLater(cmd('jam-later', CLICK))}>Later <kbd>→</kbd></button>
422
426
  </div>
423
427
  ))}
424
428
  </div>
@@ -435,7 +439,7 @@ export function PlayCounter({ cards, style }: { cards: JamCard[]; style?: CSSPro
435
439
  const settled = cards.filter((c) => c.state === 'done' || c.state === 'kept').length
436
440
  if (!pairs.length && !settled) return null
437
441
  return (
438
- <div className="jm-count jm-stage" data-jam-counter="" style={style} onClick={() => useJamUi.getState().setLaneKeys(true)}>
442
+ <div className="jm-count jm-stage" data-jam-counter="" style={style} onClick={() => { const h = cmd('jam-lane', CLICK); useJamUi.getState().setLaneKeys(true); endAfterFrames(h) }}>
439
443
  {pairs.map(([s, k]) => <span key={s}><JamStateIcon state={s as any} size={13} />{k}</span>)}
440
444
  {settled > 0 && <span key="done"><JamStateIcon state="done" size={13} />{settled}</span>}
441
445
  <i className="sep" /><span className="q">Q</span>
@@ -3,6 +3,7 @@
3
3
  * review, a wrap-up, a thread), the lane's selection and its keyboard (`Q`), the review's picture view.
4
4
  */
5
5
  import { create } from 'zustand'
6
+ import { cmd, type CmdHandle, type CmdOpts } from './commands.ts'
6
7
 
7
8
  /** The focus panel. `thread` (spec 28 A4.6 #30, r1 #3): a thread no frame on its board can show - frameless, its
8
9
  * frame gone, resolved - opened where it can be read and answered; `id` is the thread's, on `board`. */
@@ -79,14 +80,21 @@ export const useJamUi = create<JamUi>((set, get) => ({
79
80
  * closes, its tile lets go, and the lane gives the keys back (trial 1: "anywhere on the canvas should
80
81
  * close the review card and deselect the capture card"). Words being edited in the read-back save first:
81
82
  * the field is left before the panel goes. */
82
- export function letGoOfTile() {
83
+ export function letGoOfTile(from?: Pick<CmdOpts, 'via' | 'in'>) {
83
84
  const s = useJamUi.getState()
84
85
  if (!s.panel && !s.selected && !s.laneKeys) return
86
+ // an input's press: it changed something, so it is a `jam-close` (R12's silence: the return above writes nothing)
87
+ if (from) cmd('jam-close', from)
85
88
  const a = document.activeElement
86
89
  if (a instanceof HTMLElement && a.closest('.jm-focus')) a.blur()
87
90
  useJamUi.setState({ panel: null, moreOpen: false, selected: null, laneKeys: false })
88
91
  }
89
92
 
93
+ /** A command whose work answers a boolean - `act`, `runAct`, a session's move, a tile's surface drawn (spec 30): true ends
94
+ * it `done`; false, or a rejection, `failed` with `code`. Hands the answer on (a rejection reads false). */
95
+ export const endOnOk = (h: CmdHandle, answer: Promise<boolean>, code = 'refused'): Promise<boolean> =>
96
+ answer.then((ok) => { if (ok) h.done(); else h.fail(code); return ok }, () => { h.fail(code); return false })
97
+
90
98
  /** What JamSurface lends the helpers that open things (jam-keys.ts): a tile's menu opened at the tile, as a right-click
91
99
  * opens it (spec 28 A4.6 #30) - false when the tile is not drawn. */
92
100
  export const jamSurface = { tileMenu: (_id: string): boolean => false }
@@ -8,9 +8,10 @@ import { Lane, type LaneBetween, type LaneRecording, type LaneTile } from './jam
8
8
  import { Caption, FocusPanel, NotesCard, ReadBack, ReviewDetail, VoiceAsk } from './jam-panel.tsx'
9
9
  import type { TimelineLine } from './jam-lines.ts'
10
10
  import type { JamCard } from './jam-queue.ts'
11
+ import { cmd, type CmdHandle } from './commands.ts'
11
12
 
12
13
  export function CaptureLaneRow({ tiles, recording, between, selected, keyboard, followEnd, onOpen, onMenu, notes, ask, caption, doneOpen, onDoneOpen }: {
13
- tiles: LaneTile[]; recording?: LaneRecording; between?: LaneBetween; selected?: string; keyboard?: boolean; followEnd?: number; onOpen(id: string): void
14
+ tiles: LaneTile[]; recording?: LaneRecording; between?: LaneBetween; selected?: string; keyboard?: boolean; followEnd?: number; onOpen(id: string, h: CmdHandle): void
14
15
  doneOpen?: boolean; onDoneOpen?(open: boolean, doneIds: string[]): void
15
16
  onMenu?(e: React.MouseEvent, id: string): void
16
17
  notes?: { notes: { t: string; text: string }[]; draft: string; onDraft(t: string): void; onAdd(): void; onClose(): void }
@@ -62,9 +63,10 @@ export function FocusPanelView(p: {
62
63
  shots: { frame: string; before?: string; after?: string; new?: boolean }[]; reply: string
63
64
  view: 'both' | 'before' | 'after'; tab: number; moreOpen: boolean
64
65
  onTab(i: number): void; onFlip(view: 'both' | 'before' | 'after'): void; onMoreOpen(on: boolean): void; onClose(): void
65
- onEdit(text: string): void; onConfirm(): void; onKeep(): void; onDrop(): void; onResume?: () => void
66
- onGood(): void; onMore(text: string): void; onLater(): void; onOpenThread(): void
67
- onPrev?: () => void; onNext?: () => void; pending?: string; onRetry?: () => void; locked?: boolean
66
+ /** each ends the command its button started (spec 30), from the handle it is handed */
67
+ onEdit(text: string, h: CmdHandle): void; onConfirm(h: CmdHandle): void; onKeep(h: CmdHandle): void; onDrop(h: CmdHandle): void; onResume?: (h: CmdHandle) => void
68
+ onGood(h: CmdHandle): void; onMore(text: string, h: CmdHandle): void; onLater(h: CmdHandle): void; onOpenThread(h: CmdHandle): void
69
+ onPrev?: () => void; onNext?: () => void; pending?: string; onRetry?: (h: CmdHandle) => void; locked?: boolean
68
70
  /** a note added in the read-back (a draft) */
69
71
  onAddNote?(text: string, id: string): Promise<boolean>
70
72
  /** a card that asks, opened here (its thread cannot show on this board): its question and your answer */
@@ -81,7 +83,7 @@ export function FocusPanelView(p: {
81
83
  const [fit, setFit] = useState<number | undefined>(undefined)
82
84
  const head = p.kind === 'review' ? (
83
85
  <div className="jm-ftabs jm-panes" role="tablist" data-jam-panes="">
84
- {(['review', 'capture'] as const).map((v) => <button key={v} role="tab" aria-selected={v === pane} className={v === pane ? 'on' : undefined} onClick={() => setPane(v)}>{v === 'review' ? 'Review' : 'Capture'}</button>)}
86
+ {(['review', 'capture'] as const).map((v) => <button key={v} role="tab" aria-selected={v === pane} className={v === pane ? 'on' : undefined} onClick={() => { cmd('jam-pane', { via: 'click', in: 'shell', arg: v }); setPane(v) }}>{v === 'review' ? 'Review' : 'Capture'}</button>)}
85
87
  </div>
86
88
  ) : undefined
87
89
  // points are picks and clicks (a picture line carries its own number, not a point)
@@ -94,7 +96,7 @@ export function FocusPanelView(p: {
94
96
  <FocusPanel left={p.left} onClose={p.onClose} width={p.kind === 'review' && pane === 'review' ? fit : undefined}>
95
97
  {p.kind === 'review' && pane === 'review' ? (
96
98
  <ReviewDetail key={c.id} title={title} head={head} of={p.of} onPrev={p.onPrev} onNext={p.onNext} frames={p.shots.map((s) => s.frame)} active={p.tab} onTab={p.onTab}
97
- view={p.view} onFlip={(v) => p.onFlip(v)} onFit={setFit} reply={p.reply} shots={p.shots} agent={p.agent}
99
+ view={p.view} onFlip={p.onFlip} onFit={setFit} reply={p.reply} shots={p.shots} agent={p.agent}
98
100
  more={p.moreOpen} draftKey={c.id} onMore={p.onMore} onMoreOpen={p.onMoreOpen} onGood={p.onGood} onLater={p.onLater} onOpenThread={p.onOpenThread} />
99
101
  ) : (
100
102
  <ReadBack key={c.id} title={title} head={head} of={p.of} onPrev={p.onPrev} onNext={p.onNext} meta={meta} lines={p.lines} pictures={p.pictures} edited={c.edited} pending={p.pending}
@@ -11,7 +11,10 @@ import { useEffect, useId, useLayoutEffect, useRef, useState, type ReactNode } f
11
11
  import { Tip } from './Tip.tsx'
12
12
  import { cardForEvent, useJamQueue, type JamCardState } from './jam-queue.ts'
13
13
  import { statusLines } from './jam-lines.ts'
14
- import { useJamUi } from './jam-state.ts'
14
+ import { endOnOk, useJamUi } from './jam-state.ts'
15
+ import { cmd, type CmdOpts } from './commands.ts'
16
+
17
+ const CLICK: CmdOpts = { via: 'click', in: 'shell' }
15
18
 
16
19
  const GRAY = 'var(--glass-ink-3)'
17
20
  const RED = '#e5484d' // board-icons.tsx RED - errors and failures only
@@ -67,7 +70,7 @@ export function TagStatus({ board, eventId, harness }: { board?: string; eventId
67
70
  }, [card?.state])
68
71
  useEffect(() => {
69
72
  if (!open) return
70
- const away = (e: PointerEvent) => { if (!ref.current?.contains(e.target as Node)) setOpen(false) }
73
+ const away = (e: PointerEvent) => { if (!ref.current?.contains(e.target as Node)) { cmd('jam-status-close', CLICK); setOpen(false) } }
71
74
  window.addEventListener('pointerdown', away, true)
72
75
  return () => window.removeEventListener('pointerdown', away, true)
73
76
  }, [open])
@@ -93,18 +96,18 @@ export function TagStatus({ board, eventId, harness }: { board?: string; eventId
93
96
  return (
94
97
  <span className={`cm-tstat${open ? ' on' : ''}`} ref={ref} data-jam-card={card.id} data-jam-state={card.state}>
95
98
  {open ? (
96
- <button className="cm-tstat-btn" aria-expanded aria-label={head} onClick={() => setOpen(false)}><JamStateIcon state={card.state} size={13} /></button>
99
+ <button className="cm-tstat-btn" aria-expanded aria-label={head} onClick={() => { cmd('jam-status-close', CLICK); setOpen(false) }}><JamStateIcon state={card.state} size={13} /></button>
97
100
  ) : (
98
101
  <Tip side="top" label={lines}>
99
- <button className="cm-tstat-btn" aria-label={head} onClick={() => setOpen(true)}><JamStateIcon state={card.state} size={13} /></button>
102
+ <button className="cm-tstat-btn" aria-label={head} onClick={() => { cmd('jam-status-open', CLICK); setOpen(true) }}><JamStateIcon state={card.state} size={13} /></button>
100
103
  </Tip>
101
104
  )}
102
105
  {open && (
103
106
  <span className={`cm-tstat-pop${stalled ? ' many' : ''}`} role="dialog" aria-label={head} ref={popRef}>
104
107
  {lines}
105
- {move && <button className="cm-tstat-act" onClick={() => { void useJamQueue.getState().act(card, move); setOpen(false) }}>{move === 'drop' ? 'Drop' : 'Retry'}</button>}
108
+ {move && <button className="cm-tstat-act" onClick={() => { void endOnOk(cmd('jam-status-act', { ...CLICK, arg: move }), useJamQueue.getState().act(card, move)); setOpen(false) }}>{move === 'drop' ? 'Drop' : 'Retry'}</button>}
106
109
  {stalled && ([['again', 'Give it back'], ['background', 'Run in the background'], ['drop', 'Drop it']] as const).map(([a, label]) => (
107
- <button key={a} className="cm-tstat-act" data-jam-run-act={a} onClick={() => { void useJamQueue.getState().runAct(card, a); setOpen(false) }}>{label}</button>
110
+ <button key={a} className="cm-tstat-act" data-jam-run-act={a} onClick={() => { void endOnOk(cmd('jam-status-act', { ...CLICK, arg: a }), useJamQueue.getState().runAct(card, a)); setOpen(false) }}>{label}</button>
108
111
  ))}
109
112
  </span>
110
113
  )}
@@ -50,7 +50,8 @@ interface VoiceStore {
50
50
  denied: boolean
51
51
  /** words heard so far, by capture - the live caption */
52
52
  heard: Record<string, Heard[]>
53
- setChoice(c: 'yes' | 'no'): void
53
+ /** resolves once a yes's engine answered (a no at once): what `jam-voice` ends on (spec 30) */
54
+ setChoice(c: 'yes' | 'no'): Promise<void>
54
55
  refresh(): Promise<void>
55
56
  /** try the engine again (it failed to start before) and refresh */
56
57
  retry(): Promise<void>
@@ -66,7 +67,8 @@ export const useJamVoice = create<VoiceStore>((set, get) => ({
66
67
  // no: an opening is cancelled, an open microphone is cut now - the words said so far are kept
67
68
  if (c === 'no') void reconcile()
68
69
  // yes: an engine that failed to start is tried again, then the microphone opens for what runs now
69
- if (c === 'yes') void get().retry().then(() => { if (get().server === 'ready' || get().server === 'loading') set({ asking: false }); void reconcile() })
70
+ if (c === 'yes') return get().retry().then(() => { if (get().server === 'ready' || get().server === 'loading') set({ asking: false }); void reconcile() })
71
+ return Promise.resolve()
70
72
  },
71
73
  async refresh() {
72
74
  try {
@@ -1,8 +1,11 @@
1
+ import { Profiler } from 'react'
1
2
  import { createRoot } from 'react-dom/client'
2
3
  // an all-boards-locked build gives LockedApp.tsx in App.tsx's place: what only the canvas uses comes through it
3
4
  import { App, ShellBoundary, startPerfRunProbe } from './App.tsx'
4
5
  import { useStore } from './store.ts'
5
6
  import { startRecorder } from './recorder.ts'
7
+ import { shellRendered } from './recorder-signals.ts'
8
+ import { fullRecorder } from '../recorder-level.ts'
6
9
  import { capturesPending, sealOnLeave } from './jam-capture.ts'
7
10
  import { startAppBridge } from './app-bridge.ts'
8
11
  import { startAppPerf } from './app-perf.ts'
@@ -23,4 +26,7 @@ startAppPerf()
23
26
  // a headless perf run (spec 28 A3.8 #17): what its driver reads and asks, through CDP - nothing without ?mvperfrun
24
27
  startPerfRunProbe()
25
28
 
26
- createRoot(document.getElementById('root')!).render(<ShellBoundary><App /></ShellBoundary>)
29
+ const app = <ShellBoundary><App /></ShellBoundary>
30
+ // the recorder's minute of this root's commits (spec 30 #36): dev only, at the full level - it counts nothing until the
31
+ // recorder runs, and `core` (the cost proof's other side, #58) has no Profiler at all
32
+ createRoot(document.getElementById('root')!).render(import.meta.env.DEV && fullRecorder() ? <Profiler id="shell" onRender={shellRendered}>{app}</Profiler> : app)
@@ -9,6 +9,17 @@ import { create } from 'zustand'
9
9
  import { useStore, PUBLISHED, shownRev } from './store.ts'
10
10
  import { useComments } from './comments-store.ts'
11
11
  import { frameMark, isNew, questions, type Ask, type FrameMark } from '../../shared/marks.ts'
12
+ import { cmd, endOnAnswer, type CmdOpts } from './commands.ts'
13
+
14
+ /** Mark all as seen (spec 30): `mark-seen` ends on the marks write's answer - the sidebar's, or the relay from the
15
+ * tab's menu (#51). Nothing new to clear is a noop: no write goes. */
16
+ export function markSeenFrom(how: CmdOpts, frames: string[]): void {
17
+ const s = useStore.getState(), m = s.marks
18
+ const h = cmd('mark-seen', { ...how, frames: frames.length })
19
+ if (!m || !frames.some((id) => isNew(m, id))) { h.noop('nothing-new'); return }
20
+ endOnAnswer(h, 'marks/seen')
21
+ s.markSeen(frames)
22
+ }
12
23
 
13
24
  /** Every frame's mark, derived ONCE per change of marks, threads or manifest. Rows and headers read
14
25
  * one string each, so a change re-renders only what it changes - never the whole shell. */
@@ -15,6 +15,12 @@ import { onMotion, type Motion } from './canvas/camera-broadcast.ts'
15
15
  import { gestureOff, gestureOn } from './app-perf.ts'
16
16
  import { recorder } from './recorder.ts'
17
17
  import { gestureStats } from './recorder-core.ts'
18
+ import { canvasCtl } from './canvas/ctl.ts'
19
+ import { frameByWindow } from './canvas/frame-registry.ts'
20
+ import { currentCmd } from './commands.ts'
21
+ import { fullRecorder } from '../recorder-level.ts'
22
+ import { keepLongest, pickLoafs, type LoafEntry } from './recorder-signals-core.ts'
23
+ import { useStore } from './store.ts'
18
24
 
19
25
  const LOAF = typeof PerformanceObserver !== 'undefined' && (PerformanceObserver.supportedEntryTypes ?? []).includes('long-animation-frame')
20
26
  const frames: number[] = [] // inter-frame intervals (ms) across gestures, for report()
@@ -32,7 +38,38 @@ const enabled = (): boolean => {
32
38
  } catch { return false }
33
39
  }
34
40
 
35
- interface Run { t0: number; last: number; dts: number[]; pan: boolean; zoom: boolean; layout: boolean; longs: number[]; obs?: PerformanceObserver; raf: number }
41
+ interface Run {
42
+ t0: number; last: number; dts: number[]; pan: boolean; zoom: boolean; layout: boolean; longs: number[]; obs?: PerformanceObserver; raf: number
43
+ // spec 30 #34, #35: at the full level, the camera's scale over its frames, the longest frames, the command behind it
44
+ scale?: { from: number; to: number; min: number; max: number }; top: LoafEntry[]; by?: string
45
+ }
46
+ const FULL = fullRecorder()
47
+ const scaleNow = (): number | undefined => { const s = canvasCtl.transform()?.s; return typeof s === 'number' && s > 0 ? s : undefined }
48
+ function readScale(run: Run): void {
49
+ const s = FULL ? scaleNow() : undefined
50
+ if (s === undefined) return
51
+ if (!run.scale) { run.scale = { from: s, to: s, min: s, max: s }; return }
52
+ run.scale.to = s
53
+ if (s < run.scale.min) run.scale.min = s
54
+ if (s > run.scale.max) run.scale.max = s
55
+ }
56
+ /** What a script's path or window names (#35): a frame's module, else the frame whose document ran it. */
57
+ function frameOf(src: string, win: unknown): string | undefined {
58
+ const s = useStore.getState()
59
+ const byPath = src ? s.manifest?.frames.find((f) => `/${f.file}` === src)?.id : undefined
60
+ if (byPath) return byPath
61
+ const reg = frameByWindow(win)
62
+ return reg ? s.nodes.find((n) => n.key === reg.key)?.frame : undefined
63
+ }
64
+ const r3 = (x: number) => Math.round(x * 1000) / 1000
65
+ /** The command behind a layout animation (#34), read in the turn that starts it - the sampler hears of it a microtask
66
+ * later, from the observer, and a command's name lasts its turn - and kept only that long. */
67
+ let nextBy: string | undefined
68
+ export function noteGestureCmd(): void {
69
+ if (!FULL) return
70
+ nextBy = currentCmd()
71
+ if (nextBy) queueMicrotask(() => queueMicrotask(() => { nextBy = undefined }))
72
+ }
36
73
  /** the gesture running now */
37
74
  let g: Run | null = null
38
75
  /** gestures ended so far, every one (a headless perf run waits for each of its three, spec 28 A3.8 #20) */
@@ -49,13 +86,14 @@ function note(m: Motion) {
49
86
  }
50
87
 
51
88
  function begin(m: Motion) {
52
- const run: Run = { t0: performance.now(), last: 0, dts: [], pan: false, zoom: false, layout: false, longs: [], raf: 0 }
89
+ const run: Run = { t0: performance.now(), last: 0, dts: [], pan: false, zoom: false, layout: false, longs: [], raf: 0, top: [], ...(FULL ? { by: nextBy ?? currentCmd() } : {}) }
53
90
  g = run
54
91
  note(m)
92
+ readScale(run)
55
93
  // the Mac app's recorder hears it start (the white-out detector's window, spec 28 A3.8 #15); nothing elsewhere
56
94
  gestureOn(run.pan ? 'pan' : run.zoom ? 'zoom' : run.layout ? 'layout' : undefined)
57
95
  try {
58
- run.obs = new PerformanceObserver((l) => { for (const e of l.getEntries()) if (e.startTime >= run.t0) run.longs.push(e.duration) })
96
+ run.obs = new PerformanceObserver((l) => { for (const e of l.getEntries()) if (e.startTime >= run.t0) { run.longs.push(e.duration); if (FULL) keepLongest(run.top, e as unknown as LoafEntry) } })
59
97
  run.obs.observe({ type: LOAF ? 'long-animation-frame' : 'longtask', buffered: false })
60
98
  } catch { /* neither entry type (Safari): the intervals still sample */ }
61
99
  // this gesture's own loop: a frame of an earlier one that is still queued finds another run and stops
@@ -63,6 +101,7 @@ function begin(m: Motion) {
63
101
  if (g !== run) return
64
102
  if (run.last) run.dts.push(t - run.last)
65
103
  run.last = t
104
+ readScale(run)
66
105
  run.raf = requestAnimationFrame(tick)
67
106
  }
68
107
  run.raf = requestAnimationFrame(tick)
@@ -74,13 +113,20 @@ function end() {
74
113
  ended++
75
114
  cancelAnimationFrame(run.raf)
76
115
  const t1 = performance.now()
77
- for (const e of run.obs?.takeRecords() ?? []) if (e.startTime >= run.t0 && e.startTime <= t1) run.longs.push(e.duration)
116
+ for (const e of run.obs?.takeRecords() ?? []) if (e.startTime >= run.t0 && e.startTime <= t1) { run.longs.push(e.duration); if (FULL) keepLongest(run.top, e as unknown as LoafEntry) }
78
117
  run.obs?.disconnect()
79
118
  gestureOff()
80
119
  for (const d of run.dts) { frames.push(d); if (frames.length > MAX) frames.shift() }
81
120
  for (const d of run.longs) { longs.push(d); if (longs.length > MAX) longs.shift() }
82
121
  if (run.dts.length < 2) return // a press that never moved the camera
83
- recorder.gesture({ type: run.pan ? 'pan' : run.zoom ? 'zoom' : 'layout', ms: Math.round(t1 - run.t0), ...gestureStats(run.dts, run.longs.length) })
122
+ readScale(run)
123
+ const c = run.scale
124
+ recorder.gesture({
125
+ type: run.pan ? 'pan' : run.zoom ? 'zoom' : 'layout', ms: Math.round(t1 - run.t0), ...gestureStats(run.dts, run.longs.length),
126
+ ...(c ? { scale: { from: r3(c.from), to: r3(c.to), min: r3(c.min), max: r3(c.max) } } : {}),
127
+ ...(run.top.length ? { loaf: pickLoafs(run.top, frameOf) } : {}),
128
+ ...(run.by ? { by: run.by } : {}),
129
+ })
84
130
  }
85
131
 
86
132
  /** One-shot event later stages record (e.g. a blank frame, or warm-promotion latency). */
@@ -3,8 +3,11 @@
3
3
  * (the ready-watch.ts precedent): the bounded outbox, sizes in UTF-8 bytes, what fits a page's last keepalive send, a
4
4
  * gesture's numbers, and a node's outcome from what its live document said.
5
5
  */
6
+ import { PAGE_KINDS } from '../../shared/perf-records.ts'
6
7
 
7
- export const KINDS = ['load', 'commit', 'visible', 'frame', 'move', 'quiet', 'settled', 'cut', 'gesture', 'error', 'dropped'] as const
8
+ /** Every kind a page records: 0.29's, and spec 30's (`renders`, `warnings`, `theme`, `mode`, `hmr`, `cmd`, `self`) -
9
+ * one list, the server's allowlist reads it too (perf-records.ts). */
10
+ export const KINDS = PAGE_KINDS
8
11
  export type Kind = typeof KINDS[number]
9
12
  /** Every record: the workspace, this page, the load that owns the geometry ('-' before the first commit), its place
10
13
  * in this page's order, and when it happened. */
@@ -0,0 +1,36 @@
1
+ /**
2
+ * #30: Vite's socket lost, and the canvas back - api.ts's two hooks, in a module of their own: api.ts sits under store.ts
3
+ * and every stream module that reads the stores, so what it imports reaches nothing that imports it back at load.
4
+ * `lost` queues `hmr {phase:'lost'}` when `vite:ws:disconnect` arrives; `back` is `resume()`'s: it writes `hmr
5
+ * {phase:'back', downMs}` and waits at most `HMR_BACK_WAIT_MS` for it to go, before the page may reload itself. The
6
+ * queue's own retries apply (#7): a server down longer than they last counts `lost` in a `dropped` record, and `back`'s
7
+ * `downMs` still says how long.
8
+ */
9
+ import { HMR_BACK_WAIT_MS } from '../../shared/perf-records.ts'
10
+ import { fullRecorder } from '../recorder-level.ts'
11
+ import { perfSeams } from './recorder-seams.ts'
12
+
13
+ let lostAt: number | null = null
14
+
15
+ /** `vite:ws:disconnect`. */
16
+ export function hmrLost(): void {
17
+ try {
18
+ if (!perfSeams.on || !fullRecorder() || lostAt !== null) return
19
+ lostAt = performance.now()
20
+ perfSeams.record('hmr', { phase: 'lost' })
21
+ } catch { /* never in the way */ }
22
+ }
23
+
24
+ /** The canvas answered again (`resume()`): says so once per loss, and waits at most a second for it to go. Nothing to
25
+ * wait for when the socket was never lost. */
26
+ export async function hmrBack(): Promise<void> {
27
+ try {
28
+ if (!perfSeams.on || lostAt === null) return
29
+ const downMs = Math.round(performance.now() - lostAt)
30
+ lostAt = null
31
+ perfSeams.record('hmr', { phase: 'back', downMs })
32
+ // the recorder's flush, late-bound: recorder.ts imports this module's importer
33
+ const sent = import('./recorder.ts').then((r) => r.flush()).catch(() => false)
34
+ await Promise.race([sent, new Promise((r) => setTimeout(r, HMR_BACK_WAIT_MS))])
35
+ } catch { /* never in the way */ }
36
+ }