@marver-design/marver 0.26.1 → 0.27.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/CHANGELOG.md +198 -0
  2. package/README.md +12 -4
  3. package/dist/{anchor-check-l-ny3UzH.mjs → anchor-check-gkxkPAIv.mjs} +1 -1
  4. package/dist/{board-tree-DRioF94d.mjs → board-tree-BXR8dw4b.mjs} +3 -1
  5. package/dist/{boards-CGg6piKF.mjs → boards-BHKP5yhI.mjs} +1 -1
  6. package/dist/{boards-DYG22tOe.mjs → boards-BqUqKNW8.mjs} +4 -4
  7. package/dist/{build-BDRiO_mP.mjs → build-VgNg4rr8.mjs} +8 -23
  8. package/dist/cli.mjs +45 -19
  9. package/dist/{collab-Dxg2trOK.mjs → collab-BEAcXrBb.mjs} +1 -1
  10. package/dist/{comments-BqXua-XL.mjs → comments-YEU1Zhv9.mjs} +4 -4
  11. package/dist/{context-HQ4Giw58.mjs → context-Ccjrhr1J.mjs} +3 -3
  12. package/dist/{daemon-DL6Fwq6D.mjs → daemon-Dc9AH0M3.mjs} +9 -7
  13. package/dist/detect-C0wpaePX.mjs +125 -0
  14. package/dist/dev-lock-C_FC70Mu.mjs +65 -0
  15. package/dist/dev-ri6nAlRp.mjs +1273 -0
  16. package/dist/exclusive-B1RtpeeP.mjs +150 -0
  17. package/dist/{init-D8DtrK_F.mjs → init-W0nxR1OY.mjs} +8 -6
  18. package/dist/{link-BNzLvdhI.mjs → link-CdTgn94Y.mjs} +23 -11
  19. package/dist/ls-BZ5TAtd5.mjs +38 -0
  20. package/dist/{manifest-Nl3KSVOk.mjs → manifest-aFyDmL8C.mjs} +2 -2
  21. package/dist/{marks-DyWMv_Z1.mjs → marks-BF9pNEgH.mjs} +3 -3
  22. package/dist/{marks-CKgzucHZ.mjs → marks-CnCCfAbD.mjs} +3 -3
  23. package/dist/{marver-id-gate-BjF6v4bT.mjs → marver-id-gate-D-R0hSt_.mjs} +1 -1
  24. package/dist/perf-DkAUFT6W.mjs +1319 -0
  25. package/dist/perf-jam-BaH3Lg0m.mjs +635 -0
  26. package/dist/plugin-B8UghYuF.mjs +5242 -0
  27. package/dist/{poster-BdtSKMDm.mjs → poster-BNgafWMK.mjs} +1 -1
  28. package/dist/{profile-WU9qcbIo.mjs → profile-jIS6BcAs.mjs} +1 -1
  29. package/dist/{publish-bakes-9RzRToXV.mjs → publish-bakes-38Nja78p.mjs} +3 -3
  30. package/dist/{queue-29ok5_eZ.mjs → queue-CAM_vNmX.mjs} +1 -1
  31. package/dist/recover-B8AiI29B.mjs +66 -0
  32. package/dist/{serve-C8rVheYk.mjs → serve-Dp3nHstu.mjs} +3 -3
  33. package/dist/{share--oFJ1bCI.mjs → share-Ce4tP7ji.mjs} +1 -1
  34. package/dist/{shot-XQV7HC9A.mjs → shot-CMQgMVZm.mjs} +1 -1
  35. package/dist/{shot-DQeR_Pfn.mjs → shot-Ch24tiMO.mjs} +36 -5
  36. package/dist/slots-CFNnegCc.mjs +478 -0
  37. package/dist/{sync-DKk-yT1V.mjs → sync-CQdGARJ9.mjs} +4 -3
  38. package/dist/{work-VvX_JIgl.mjs → work-Bxz-ObF3.mjs} +4 -2
  39. package/dist/{work-F5u-twpJ.mjs → work-CNhFF9pU.mjs} +5 -3
  40. package/docs/boards-and-folders.md +3 -1
  41. package/docs/jam-session.md +57 -2
  42. package/docs/performance.md +424 -0
  43. package/package.json +2 -2
  44. package/src/client/content/index.tsx +3 -0
  45. package/src/client/content/video.tsx +16 -4
  46. package/src/client/frame-host/bridge.js +22 -6
  47. package/src/client/frame-host/main.tsx +17 -5
  48. package/src/client/shell/App.tsx +188 -26
  49. package/src/client/shell/BoardList.tsx +5 -5
  50. package/src/client/shell/Comments.tsx +8 -5
  51. package/src/client/shell/ContextMenu.tsx +5 -3
  52. package/src/client/shell/JamSurface.tsx +4 -2
  53. package/src/client/shell/LockedApp.tsx +8 -5
  54. package/src/client/shell/Play.tsx +20 -10
  55. package/src/client/shell/Tip.tsx +3 -1
  56. package/src/client/shell/Toolbar.tsx +12 -1
  57. package/src/client/shell/api.ts +233 -0
  58. package/src/client/shell/app-bridge.ts +254 -0
  59. package/src/client/shell/app-perf.ts +92 -0
  60. package/src/client/shell/canvas/Canvas.tsx +141 -21
  61. package/src/client/shell/canvas/FrameNode.tsx +22 -9
  62. package/src/client/shell/canvas/admission.ts +31 -9
  63. package/src/client/shell/canvas/camera-broadcast.ts +15 -5
  64. package/src/client/shell/canvas/ctl.ts +8 -0
  65. package/src/client/shell/canvas/frame-registry.ts +28 -2
  66. package/src/client/shell/canvas/sleep.ts +60 -17
  67. package/src/client/shell/canvas/updates.ts +2 -1
  68. package/src/client/shell/comments-store.ts +12 -4
  69. package/src/client/shell/goto.ts +22 -10
  70. package/src/client/shell/inset.ts +44 -0
  71. package/src/client/shell/jam-capture.ts +41 -22
  72. package/src/client/shell/jam-keys.ts +12 -3
  73. package/src/client/shell/jam-panel.tsx +9 -3
  74. package/src/client/shell/jam-queue.ts +3 -3
  75. package/src/client/shell/jam-session.tsx +14 -8
  76. package/src/client/shell/jam-voice.ts +55 -15
  77. package/src/client/shell/legacy-links.ts +2 -2
  78. package/src/client/shell/main.tsx +18 -1
  79. package/src/client/shell/marks-ui.tsx +5 -3
  80. package/src/client/shell/marver-app.ts +21 -0
  81. package/src/client/shell/notes.ts +8 -1
  82. package/src/client/shell/perf-run-probe.ts +34 -0
  83. package/src/client/shell/perf-run.ts +70 -0
  84. package/src/client/shell/perf.ts +80 -58
  85. package/src/client/shell/recorder-core.ts +183 -0
  86. package/src/client/shell/recorder.ts +607 -0
  87. package/src/client/shell/store.ts +294 -110
  88. package/src/client/shell/styles.css +72 -15
  89. package/src/client/shell/unsaved.ts +81 -0
  90. package/src/client/shell/whiteout-probes.ts +141 -0
  91. package/src/shared/app-api.ts +205 -0
  92. package/src/shared/app-perf.ts +308 -0
  93. package/src/shared/logo-sniff.ts +86 -0
  94. package/src/shared/machine.ts +132 -0
  95. package/src/shared/perf-run.ts +177 -0
  96. package/templates/AGENTS-embedded.md +25 -4
  97. package/templates/AGENTS-studio.md +25 -4
  98. package/templates/demo/dark.tsx +1 -1
  99. package/templates/demo/welcome.tsx +1 -1
  100. package/templates/instructions/boards.md +3 -1
  101. package/templates/instructions/welcome.md +6 -3
  102. package/dist/bake-C-awKgLA.mjs +0 -786
  103. package/dist/config-Cf7EjAMf.mjs +0 -292
  104. package/dist/dev-Bw_qYWWq.mjs +0 -755
  105. package/dist/dev-lock-DWSpa6nj.mjs +0 -179
  106. package/dist/perf-C75MZ73h.mjs +0 -167
  107. package/dist/perf-DPbLGhhO.mjs +0 -49
  108. package/dist/perf-jam-BU3TVrZu.mjs +0 -239
  109. package/dist/plugin-DkGmZs_r.mjs +0 -2423
@@ -13,14 +13,18 @@
13
13
  * starts nothing - it is ended (E) or dropped (Esc) first. Each message lands in the capture whose
14
14
  * id it carries.
15
15
  */
16
+ import { onScreen, usable } from './inset.ts'
16
17
  import { create } from 'zustand'
17
- import { ROUTE, slideSize } from '../const.ts'
18
- import { CONFIG, SLIDE_INTRINSIC, useStore, type Node } from './store.ts'
18
+ import { slideSize } from '../const.ts'
19
+ import { CONFIG, SLIDE_INTRINSIC, stoppedFor, useStore, type Node } from './store.ts'
19
20
  import { UNPLACED } from './hash.ts'
20
21
  import type { Bundle, CaptureRecord, Step, View } from '../../server/jam/types.ts'
21
22
  import { forgetHeard, RATE, setWordsListener, voiceBegin, voiceDrop, voiceEnd } from './jam-voice.ts'
22
23
  import { touchedFrames } from '../../shared/capture-frames.ts'
23
24
  import { onStageSize, stageSize } from './stage-size.ts'
25
+ import { api, holdsReload } from './api.ts'
26
+ import { unsavedWhen, workChanged } from './unsaved.ts'
27
+ import { bytesOf } from './recorder-core.ts'
24
28
 
25
29
  const csrf = () => /(?:^|;\s*)mv_c=([\w-]+)/.exec(document.cookie)?.[1] ?? ''
26
30
  const now = () => performance.timeOrigin + performance.now()
@@ -173,7 +177,7 @@ function sizeNow(f: string, key?: string): { w: number; h: number; play?: true }
173
177
  const entry = st.manifest?.frames.find((x) => x.id === f)
174
178
  const slide = (entry && slideSize(entry, CONFIG.viewports)) ?? (st.play.slides ? SLIDE_INTRINSIC : null)
175
179
  if (slide) return { w: Math.round(slide.width), h: Math.round(slide.height), play: true }
176
- if (st.play.device === 'fill') return { w: window.innerWidth, h: window.innerHeight, play: true }
180
+ if (st.play.device === 'fill') { const u = usable(); return { w: u.width, h: u.height, play: true } }
177
181
  const v = CONFIG.viewports[st.play.device]
178
182
  return v ? { w: Math.round(v.width), h: Math.round(v.height), play: true } : undefined
179
183
  }
@@ -241,13 +245,13 @@ const viewNow = (focus = false): View => {
241
245
  * nothing that covers it (the panel and the lane leave their own room). */
242
246
  export function visibleNodes(): Node[] {
243
247
  const s = useStore.getState()
244
- const W = window.innerWidth, H = window.innerHeight
245
248
  const out: Node[] = []
246
249
  for (const n of s.nodes) {
247
250
  if (n.missing) continue
248
251
  const el = document.querySelector(`.sh-node[data-node="${CSS.escape(n.key)}"]`)
249
252
  const r = el?.getBoundingClientRect()
250
- if (r && r.right > 0 && r.bottom > 0 && r.left < W && r.top < H) out.push(n)
253
+ // on screen below the scroll edge (inset.ts): a frame under the Mac app's strip is not in view
254
+ if (r && onScreen(r)) out.push(n)
251
255
  }
252
256
  return out.slice(0, 20)
253
257
  }
@@ -550,7 +554,7 @@ function shoot(id: string, frame: string, why: 'key' | 'pick' | 'end', key?: str
550
554
  // settled exactly once - a picture, or a missing one - whatever fails: the request, its body, the abort
551
555
  let settled = false
552
556
  const finish = (pid: string | null) => { if (settled) return; settled = true; clearTimeout(timer); done(pid, ctl.signal.aborted) }
553
- fetch(`${ROUTE}/api/jam/picture`, {
557
+ api('jam/picture', {
554
558
  method: 'POST', signal: ctl.signal, headers: { 'content-type': 'application/json', 'x-mv-c': csrf() },
555
559
  body: JSON.stringify({ capture: id, frame, theme, ...(size ? { w: Math.round(size.width), h: Math.round(size.height) } : {}) }),
556
560
  }).then(async (r) => (r.ok ? ((await r.json()) as { id?: string }).id ?? null : null))
@@ -570,7 +574,7 @@ export const setSessionEnding = (on: boolean) => { sessionEnding = on }
570
574
  * that every 20 s until it lands or is dropped: the session's record waits for it, whatever tab ends it. */
571
575
  const openOnServer = new Map<string, { session: string; timer: ReturnType<typeof setInterval> }>()
572
576
  const tellOpen = (capture: string, session: string, on: boolean) => {
573
- void fetch(`${ROUTE}/api/jam/capture-open`, { method: 'POST', headers: { 'content-type': 'application/json', 'x-mv-c': csrf() }, body: JSON.stringify({ capture, session, on }) })
577
+ void api('jam/capture-open', { method: 'POST', headers: { 'content-type': 'application/json', 'x-mv-c': csrf() }, body: JSON.stringify({ capture, session, on }) })
574
578
  .then(async (r) => { if (on && r.status === 409 && (await r.json().catch(() => null))?.ended) leftOutOfSession(capture) }, () => {})
575
579
  }
576
580
  /** The server had already written the session's record (in another tab) when it heard of this capture: it is
@@ -761,7 +765,7 @@ function sealedSizes(c: Cap): Record<string, { w: number; h: number; play?: true
761
765
 
762
766
  /** Jam timings (spec 27a Part D): numbers only, to the dev server's local log - best effort, never in the way. */
763
767
  const perf = (body: Record<string, unknown>, keepalive = false) => {
764
- try { void fetch(`${ROUTE}/api/perf/jam`, { method: 'POST', headers: { 'content-type': 'application/json', 'x-mv-c': csrf() }, body: JSON.stringify(body), ...(keepalive ? { keepalive: true } : {}) }).catch(() => {}) } catch { /* never in the way */ }
768
+ try { void api('perf/jam', { method: 'POST', headers: { 'content-type': 'application/json', 'x-mv-c': csrf() }, body: JSON.stringify(body), ...(keepalive ? { keepalive: true } : {}) }).catch(() => {}) } catch { /* never in the way */ }
765
769
  }
766
770
  /** A capture's timing as it seals: E to sealed (none when the page sealed it), the wait for its words, its pictures. */
767
771
  function timeCapture(c: Cap, interrupted: boolean) {
@@ -806,6 +810,10 @@ function trySeal(id: string) {
806
810
  /** Kept per workspace: another project served later on the same port never receives this one's captures. */
807
811
  const KEPT = `mv-jam-sealed:${CONFIG.workspace ?? 'unknown'}`
808
812
  const syncUnsent = () => useJamCapture.setState({ unsent: [...pendingUploads.keys()] })
813
+ /** A capture is still open (a page that goes seals and sends it), or sealed and not taken by the server yet (waiting,
814
+ * or on its way): the recorder leaves a page's keepalive allowance to it (spec 28 A1.7). By state, not by the order
815
+ * the pagehide listeners run in. */
816
+ export const capturesPending = (): boolean => { const s = useJamCapture.getState(); return s.unsent.length > 0 || Object.keys(s.caps).length > 0 }
809
817
  const keepSealed = (r: CaptureRecord) => { try { const all = JSON.parse(localStorage.getItem(KEPT) ?? '{}'); all[r.id] = r; localStorage.setItem(KEPT, JSON.stringify(all)) } catch { /* memory only */ } pendingUploads.set(r.id, r); syncUnsent() }
810
818
  const forgetSealed = (id: string) => { pendingUploads.delete(id); syncUnsent(); try { const all = JSON.parse(localStorage.getItem(KEPT) ?? '{}'); delete all[id]; localStorage.setItem(KEPT, JSON.stringify(all)) } catch { /* memory only */ } }
811
819
  const pendingUploads = new Map<string, CaptureRecord>()
@@ -820,8 +828,9 @@ async function upload(record: CaptureRecord, leaving = false): Promise<void> {
820
828
  uploadTries.set(record.id, (uploadTries.get(record.id) ?? 0) + 1)
821
829
  const tUp = performance.now()
822
830
  const payload = JSON.stringify({ record, workspace: CONFIG.workspace })
823
- // a page that is going sends with keepalive (64 kB at most) so the request outlives it; a bigger one, the next page
824
- const res = await fetch(`${ROUTE}/api/jam/capture`, { method: 'POST', headers: { 'content-type': 'application/json', 'x-mv-c': csrf() }, body: payload, ...(leaving && payload.length < 60_000 ? { keepalive: true } : {}) })
831
+ // a page that is going sends with keepalive (64 kB at most, counted in UTF-8 bytes as the body carries it - not
832
+ // `.length`: notes in another script are wider) so the request outlives it; a bigger one, the next page
833
+ const res = await api('jam/capture', { method: 'POST', headers: { 'content-type': 'application/json', 'x-mv-c': csrf() }, body: payload, ...(leaving && bytesOf(payload) < 60_000 ? { keepalive: true } : {}) })
825
834
  const body = (await res.json().catch(() => null)) as Verdict | null
826
835
  // only an explicit verdict on THIS record is final: taken (200, naming its card) or refused as a
827
836
  // record (400, saying why). Anything else - jam not running yet, another workspace, an unreadable
@@ -847,20 +856,16 @@ async function upload(record: CaptureRecord, leaving = false): Promise<void> {
847
856
  }
848
857
 
849
858
  /** A capture still recording, or finishing (its pictures and last words coming in), lives only in this page until it
850
- * seals; a sealed one is kept in localStorage until it lands. Leaving the page asks first - and if you leave anyway
851
- * (`pagehide`: a close, a reload, a navigation, the back-forward cache alike), every capture not sealed yet is sealed
852
- * at once, as it stood, for good: a missing step says so, the server keeps it as a draft, and it goes out like any
853
- * sealed record not sent yet - from the next page, or this one if it comes back. Carrying on is Resume, with a new id.
854
- * Best effort: a crash or a killed process fires nothing. */
859
+ * seals; a sealed one is kept in localStorage until it lands. Leaving the page asks first - unsaved.ts's one
860
+ * `beforeunload`, which hears this module's two reasons below - and if you leave anyway (`pagehide`: a close, a
861
+ * reload, a navigation, the back-forward cache alike), every capture not sealed yet is sealed at once, as it stood,
862
+ * for good: a missing step says so, the server keeps it as a draft, and it goes out like any sealed record not sent
863
+ * yet - from the next page, or this one if it comes back. Carrying on is Resume, with a new id. Best effort: a crash
864
+ * or a killed process fires nothing. */
855
865
  let guarded = false
856
866
  function guardUnload() {
857
867
  if (guarded || typeof window === 'undefined') return
858
868
  guarded = true
859
- window.addEventListener('beforeunload', (e) => {
860
- if (!Object.keys(useJamCapture.getState().caps).length) return
861
- e.preventDefault()
862
- e.returnValue = ''
863
- })
864
869
  window.addEventListener('pagehide', () => sealOnLeave())
865
870
  // back from the back-forward cache: what was kept goes out now (never amended, never dropped)
866
871
  window.addEventListener('pageshow', (e) => { if (e.persisted) for (const r of pendingUploads.values()) void upload(r) })
@@ -906,11 +911,19 @@ export function resendSealed() {
906
911
  } catch { /* none */ }
907
912
  }
908
913
 
914
+ // the canvas answered again after it stopped (spec 28 A1.11): the page reloads only when no capture is
915
+ // recording or finishing - a sealed one waits in localStorage and goes out from the next page
916
+ holdsReload(() => capturesPending())
917
+ // leaving the page with a capture open, or one sealed and not taken by the server yet - a memory-only one too, its
918
+ // localStorage copy failed - asks first (spec 28 A2.9); the Mac app hears the same two reasons
919
+ unsavedWhen('capture-recording', () => Object.keys(useJamCapture.getState().caps).length > 0)
920
+ unsavedWhen('capture-unsent', () => useJamCapture.getState().unsent.length > 0)
921
+
909
922
  /** Resume's work, while the caller holds `settling`: load the record, let the caller settle, start. */
910
923
  async function resumeNow(draft: string, ready?: () => Promise<boolean>): Promise<boolean> {
911
924
  let rec: CaptureRecord | null = null
912
925
  try {
913
- const r = await fetch(`${ROUTE}/api/jam/capture?id=${encodeURIComponent(draft)}`, { headers: { 'x-mv-c': csrf() } })
926
+ const r = await api(`jam/capture?id=${encodeURIComponent(draft)}`, { headers: { 'x-mv-c': csrf() } })
914
927
  const body = r.ok ? ((await r.json()) as { record?: CaptureRecord; sealed?: boolean }) : null
915
928
  if (body?.record && body.sealed !== true) { useStore.getState().toast('the capture changed after it was sealed - it cannot be resumed'); return false }
916
929
  rec = body?.record ?? null
@@ -938,11 +951,14 @@ export const useJamCapture = create<CaptureState>((set, get) => ({
938
951
  lastEnded: null,
939
952
  settling: null,
940
953
  async resume(draft, ready) {
954
+ if (stoppedFor('Jam needs the canvas running')) return false // spec 28 A1.11: nothing to take it
941
955
  if (get().current) { useStore.getState().toast('a capture is recording - press E to end it first'); return false }
942
956
  if (sessionEnding) { useStore.getState().toast('the session is being wrapped up - a moment'); return false }
943
957
  return resumeNow(draft, ready)
944
958
  },
945
959
  start(reviewing, session) {
960
+ // the canvas stopped (spec 28 A1.11): a new capture waits for it - one recording goes on, and is kept
961
+ if (!get().current && stoppedFor('Jam needs the canvas running')) return
946
962
  // one capture at a time: the one recording is ended or dropped first
947
963
  if (get().current) { useStore.getState().toast('a capture is recording - press E to end it first'); return }
948
964
  if (sessionEnding) { useStore.getState().toast('the session is being wrapped up - a moment'); return }
@@ -988,6 +1004,9 @@ export const useJamCapture = create<CaptureState>((set, get) => ({
988
1004
  },
989
1005
  }))
990
1006
 
1007
+ // a capture opened, sealed or taken by the server: what this page holds changed (unsaved.ts)
1008
+ useJamCapture.subscribe((s, p) => { if (Object.keys(s.caps).length !== Object.keys(p.caps).length || s.unsent.length !== p.unsent.length) workChanged() })
1009
+
991
1010
  /** What the capture tile shows: the timer and the counts. */
992
1011
  export function captureCounts(c: Cap | undefined, t = now()): { time: string; counts: string; notes: number } {
993
1012
  if (!c) return { time: '0:00', counts: '', notes: 0 }
@@ -1002,4 +1021,4 @@ export function captureCounts(c: Cap | undefined, t = now()): { time: string; co
1002
1021
  }
1003
1022
  }
1004
1023
 
1005
- if (typeof window !== 'undefined' && (import.meta as any).env?.DEV) { (window as any).__mvJamCapture = useJamCapture; (window as any).__mvJamInstances = instances }
1024
+ if (typeof window !== 'undefined' && (import.meta as any).env?.DEV) { (window as any).__mvJamCapture = useJamCapture; (window as any).__mvJamInstances = instances; (window as any).__mvJamVisible = visibleNodes }
@@ -22,6 +22,8 @@ import { DONE_CLOSE, DONE_GROUP, doneFold, useJamUi } from './jam-state.ts'
22
22
  import { pressJ, startSession, wrapWrite } from './jam-session.tsx'
23
23
  import { clearMoreDraft } from './jam-panel.tsx'
24
24
  import { CONFIG, PUBLISHED, SOURCE_REVEALED, useStore } from './store.ts'
25
+ import { holdsReload } from './api.ts'
26
+ import { unsavedWhen, workChanged } from './unsaved.ts'
25
27
 
26
28
  export interface KeyIn { key: string; shift?: boolean; alt?: boolean; meta?: boolean; ctrl?: boolean }
27
29
  /** `[Ctrl+][Meta+][Alt+][Shift+]key`, a letter lowercase - the frames' descriptor (keys.js). */
@@ -58,18 +60,24 @@ export function saveEdit(c: JamCard, text: string) {
58
60
  const g = ++gen
59
61
  latest.set(c.id, g)
60
62
  unsaved.set(c.id, text)
63
+ workChanged()
61
64
  const before = saving.get(c.id) ?? Promise.resolve(true)
62
65
  // saves of one card run in order, each at the card's rev as the one before left it
63
66
  saving.set(c.id, before.then(() => {
64
67
  const fresh = useJamQueue.getState().cards?.find((x) => x.id === c.id) ?? c
65
68
  return useJamQueue.getState().act(fresh, 'edit', text)
66
- }).then((ok) => { if (ok && latest.get(c.id) === g) unsaved.delete(c.id); return ok }))
69
+ }).then((ok) => { if (ok && latest.get(c.id) === g) { unsaved.delete(c.id); workChanged() } return ok }))
67
70
  }
68
71
  /** Notes added in a read-back not saved yet, per card: each with its own id - one on its way, or one that failed
69
72
  * and waits to be sent again. Sent again (from the field, or before a decision) it keeps its id: the server
70
73
  * keeps a note once, whatever answer was lost; a different note never takes a failed one's place. */
71
74
  type PendingNote = { id: string; text: string; failed: boolean; order: number }
72
75
  const unsavedNotes = new Map<string, PendingNote[]>()
76
+ // spec 28 A1.11: a page whose canvas came back reloads only once every edit and note of a read-back has saved -
77
+ // one that failed while the canvas was away waits for the read-back's own retry (a decision saves it first)
78
+ holdsReload(() => unsaved.size > 0 || unsavedNotes.size > 0)
79
+ // and leaving the page asks first (spec 28 A2.9): a read-back's edit or note not saved yet is words not sent
80
+ unsavedWhen('typing', () => unsaved.size > 0 || unsavedNotes.size > 0)
73
81
  const sendNote = (c: JamCard, n: PendingNote): Promise<boolean> => {
74
82
  n.failed = false
75
83
  const before = saving.get(c.id) ?? Promise.resolve(true)
@@ -78,7 +86,7 @@ const sendNote = (c: JamCard, n: PendingNote): Promise<boolean> => {
78
86
  return useJamQueue.getState().act(fresh, 'note', JSON.stringify({ id: n.id, text: n.text, order: n.order }))
79
87
  }).then((ok) => {
80
88
  const list = unsavedNotes.get(c.id) ?? []
81
- if (ok) { const left = list.filter((x) => x !== n); if (left.length) unsavedNotes.set(c.id, left); else unsavedNotes.delete(c.id) } else n.failed = true
89
+ if (ok) { const left = list.filter((x) => x !== n); if (left.length) unsavedNotes.set(c.id, left); else unsavedNotes.delete(c.id); workChanged() } else n.failed = true
82
90
  return ok
83
91
  }, () => { n.failed = true; return false })
84
92
  saving.set(c.id, p.then(() => true))
@@ -91,6 +99,7 @@ export function addNote(c: JamCard, text: string, id: string): Promise<boolean>
91
99
  const was = (unsavedNotes.get(c.id) ?? []).find((x) => x.id === id)
92
100
  const n: PendingNote = { id, text, failed: false, order: was?.order ?? Date.now() }
93
101
  unsavedNotes.set(c.id, [...(unsavedNotes.get(c.id) ?? []).filter((x) => x.id !== id), n])
102
+ workChanged()
94
103
  return sendNote(c, n)
95
104
  }
96
105
  /** Every note added to a draft saved (a failed one sent again, once): before it is sent, kept or resumed. */
@@ -115,7 +124,7 @@ export async function decideDraft(id: string, action: 'confirm' | 'keep' | 'drop
115
124
  }
116
125
  // a note added in its read-back goes with it: one that did not save is sent again, and nothing is sent without it
117
126
  if (action !== 'drop' && unsavedNotes.has(id) && !(await notesSaved(id))) { useStore.getState().toast('your note could not be added - try again before you send it'); return }
118
- if (action === 'drop') { unsaved.delete(id); unsavedNotes.delete(id) }
127
+ if (action === 'drop') { unsaved.delete(id); unsavedNotes.delete(id); workChanged() }
119
128
  const fresh = useJamQueue.getState().cards?.find((c) => c.id === id)
120
129
  if (!fresh) return
121
130
  if (await useJamQueue.getState().act(fresh, action)) useJamUi.getState().close()
@@ -18,6 +18,8 @@ import {
18
18
  import { LANE_H } from './jam-lane.tsx'
19
19
  import { Tip } from './Tip.tsx'
20
20
  import { useJamQueue } from './jam-queue.ts'
21
+ import { holdsReload } from './api.ts'
22
+ import { unsavedWhen, workChanged } from './unsaved.ts'
21
23
 
22
24
  /** A heading cut short by its ellipsis: its tooltip shows it whole (one that fits shows none). */
23
25
  const cutShort = (el: HTMLElement) => el.scrollWidth > el.clientWidth + 1
@@ -54,9 +56,13 @@ export function FocusPanel({ children, left, width = 580, onClose }: { children:
54
56
 
55
57
  /** More work words not sent yet, by card - they survive the panel closing on a click elsewhere. */
56
58
  const moreDrafts = new Map<string, string>()
57
- export const clearMoreDraft = (id: string) => { moreDrafts.delete(id) }
59
+ export const clearMoreDraft = (id: string) => { moreDrafts.delete(id); workChanged() }
58
60
  export const moreDraftOf = (id: string): string => moreDrafts.get(id) ?? ''
59
- export const setMoreDraft = (id: string, t: string) => { if (t) moreDrafts.set(id, t); else moreDrafts.delete(id) }
61
+ export const setMoreDraft = (id: string, t: string) => { if (t) moreDrafts.set(id, t); else moreDrafts.delete(id); workChanged() }
62
+ // spec 28 A1.11: a page whose canvas came back reloads only once no such words wait (a reload would drop them)
63
+ holdsReload(() => moreDrafts.size > 0)
64
+ // and leaving the page asks first (spec 28 A2.9)
65
+ unsavedWhen('typing', () => moreDrafts.size > 0)
60
66
 
61
67
  const unquote = (s: string) => s.replace(/^"(.*)"$/s, '$1')
62
68
  const DEVICE: Record<string, string> = { phone: 'mobile', mobile: 'mobile', tablet: 'tablet', laptop: 'laptop', desktop: 'monitor', monitor: 'monitor', tv: 'tv' }
@@ -367,7 +373,7 @@ export function ReviewDetail({ title, head, of, onPrev, onNext, frames, active,
367
373
  // the More work words outlive the panel: a click elsewhere closes it, and the words wait for its return -
368
374
  // they go only when sent, or when you leave the composer yourself (Esc)
369
375
  const [text, setTextState] = useState(() => (draftKey ? moreDrafts.get(draftKey) ?? '' : ''))
370
- const setText = (t: string) => { setTextState(t); if (draftKey) { if (t) moreDrafts.set(draftKey, t); else moreDrafts.delete(draftKey) } }
376
+ const setText = (t: string) => { setTextState(t); if (draftKey) { if (t) moreDrafts.set(draftKey, t); else moreDrafts.delete(draftKey); workChanged() } }
371
377
  const field = useRef<HTMLTextAreaElement>(null)
372
378
  useEffect(() => { if (draftKey && moreDrafts.get(draftKey) && !more) onMoreOpen(true) }, []) // back with words waiting: the composer is open
373
379
  // left on purpose (Esc cleared its words from the map): the composer's words go too; closed by a click
@@ -5,8 +5,8 @@
5
5
  * failed). A card that fails raises one notice; nothing else here interrupts.
6
6
  */
7
7
  import { create } from 'zustand'
8
- import { ROUTE } from '../const.ts'
9
8
  import { PUBLISHED } from './store.ts'
9
+ import { api } from './api.ts'
10
10
 
11
11
  export type JamAction = 'drop' | 'retry' | 'keep' | 'first' | 'confirm' | 'edit' | 'good' | 'more' | 'later' | 'rename' | 'note'
12
12
  export type JamCardState = 'draft' | 'confirming' | 'queued' | 'working' | 'asks' | 'review' | 'done' | 'kept' | 'failed' | 'dropped'
@@ -72,7 +72,7 @@ export const useJamQueue = create<QueueState>((set, get) => {
72
72
  async load() {
73
73
  if (PUBLISHED) return
74
74
  try {
75
- const res = await fetch(`${ROUTE}/api/jam/queue`, { headers: { 'x-mv-c': csrf() } })
75
+ const res = await api('jam/queue', { headers: { 'x-mv-c': csrf() } })
76
76
  if (res.ok) get().apply(await res.json())
77
77
  } catch { /* no queue: no icons */ }
78
78
  },
@@ -113,7 +113,7 @@ export const useJamQueue = create<QueueState>((set, get) => {
113
113
  if (get().session?.id === session) set({ session: null })
114
114
  },
115
115
  async act(card, action, body) {
116
- const res = await fetch(`${ROUTE}/api/jam/card`, {
116
+ const res = await api('jam/card', {
117
117
  method: 'POST', headers: { 'content-type': 'application/json', 'x-mv-c': csrf() },
118
118
  body: JSON.stringify({ id: card.id, rev: card.rev, action, ...(body !== undefined ? { body } : {}) }),
119
119
  }).catch(() => null)
@@ -10,7 +10,6 @@
10
10
  * crossed microphone without one); a teal dot only while a capture records. Blue only on hover and press.
11
11
  */
12
12
  import { useEffect, useRef, useState, type CSSProperties } from 'react'
13
- import { ROUTE } from '../const.ts'
14
13
  import { setSessionEnding, useJamCapture } from './jam-capture.ts'
15
14
  import { laneCards, startCapture } from './jam-keys.ts'
16
15
  import { useJamQueue, type JamCard } from './jam-queue.ts'
@@ -22,7 +21,8 @@ import { HARNESS } from './Comments.tsx'
22
21
  import { ArrowRightIcon, CaretIcon, KeyboardIcon, MicrophoneIcon, MicrophoneSlashIcon, WarningIcon, WaveformIcon } from './icons.tsx'
23
22
  import { Tip } from './Tip.tsx'
24
23
  import { useSessionClock } from './jam-lane.tsx'
25
- import { CONFIG, useStore } from './store.ts'
24
+ import { CONFIG, stoppedFor, useStore } from './store.ts'
25
+ import { api, STOPPED_TIP, useStopped } from './api.ts'
26
26
 
27
27
  const csrf = () => /(?:^|;\s*)mv_c=([\w-]+)/.exec(document.cookie)?.[1] ?? ''
28
28
  const now = () => performance.timeOrigin + performance.now()
@@ -32,7 +32,7 @@ const now = () => performance.timeOrigin + performance.now()
32
32
  /** Why the last session move was refused (the server's words), for the one line that says so. */
33
33
  let lastError: string | undefined
34
34
  async function post(body: Record<string, unknown>, onAnswer?: (ok: boolean) => void): Promise<boolean> {
35
- const r = await fetch(`${ROUTE}/api/jam/session`, { method: 'POST', headers: { 'content-type': 'application/json', 'x-mv-c': csrf() }, body: JSON.stringify(body) }).catch(() => null)
35
+ const r = await api('jam/session', { method: 'POST', headers: { 'content-type': 'application/json', 'x-mv-c': csrf() }, body: JSON.stringify(body) }).catch(() => null)
36
36
  lastError = r && !r.ok ? ((await r.json().catch(() => null)) as { error?: string } | null)?.error : r ? undefined : 'marver dev did not answer'
37
37
  // what the server's answer settles happens at once, never behind the refresh (which may be slow, and a push
38
38
  // may come first)
@@ -43,6 +43,7 @@ async function post(body: Record<string, unknown>, onAnswer?: (ok: boolean) => v
43
43
 
44
44
  /** Start a session: the dev server holds it (it survives a reload); the microphone hears its talk. */
45
45
  export async function startSession(): Promise<boolean> {
46
+ if (stoppedFor('Jam needs the canvas running')) return false // spec 28 A1.11
46
47
  const id = `ses-${Date.now()}-${Math.random().toString(36).slice(2, 8).padEnd(6, '0')}`
47
48
  // this tab holds the session's microphone (a reload of it takes it back; other tabs never take it) - from
48
49
  // the moment the server has it: the push of it may come before the refresh
@@ -112,6 +113,8 @@ let endingOp = 0
112
113
  * capture recording ends first, and the wrap-up waits for its read-back to close. */
113
114
  export function pressJ() {
114
115
  const ui = useJamUi.getState()
116
+ // 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
115
118
  if (!useJamQueue.getState().session) { ui.setSheet(ui.sheet === 'start' ? null : 'start'); return }
116
119
  if (ui.sheet === 'wrap' || ui.sheet === 'wrap-pending') { ui.setSheet(null); return }
117
120
  if (useJamCapture.getState().current) { useJamCapture.getState().end(); ui.setSheet('wrap-pending'); return }
@@ -132,11 +135,14 @@ export function JamButton({ inPlay }: { inPlay?: boolean }) {
132
135
  // off: no, blocked, no engine - or stopped (another tab has it, the connection went) while you said yes
133
136
  const micOff = voice.choice === 'no' || voice.denied || voice.server === 'unavailable' || (!!session && voice.choice === 'yes' && !voice.live && !recording)
134
137
  const state = recording ? 'rec' : session ? 'live' : 'idle'
135
- const label = session ? <><b>End the session</b><span>J</span></> : <><b>Jam session</b><span>J</span></>
138
+ // the canvas stopped (spec 28 A1.11): quiet, saying why - a capture already recording goes on
139
+ const stopped = useStopped()
140
+ const label = stopped ? <div className="sh-tip-lines"><b>Jam needs the canvas running</b><small>{STOPPED_TIP}</small></div>
141
+ : session ? <><b>End the session</b><span>J</span></> : <><b>Jam session</b><span>J</span></>
136
142
  return (
137
143
  <Tip side="bottom" inv={inPlay} label={label}>
138
- <button className={`sh-pill-btn jm-jam${state !== 'idle' ? ` ${state}` : ''}${sheet === 'start' || sheet === 'wrap' ? ' press' : ''}`}
139
- data-jam-button={state} aria-label={session ? 'End the Jam session' : 'Jam session'} onClick={pressJ}>
144
+ <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}>
140
146
  {/* the whole session reads as on: the dot pulses from start to end, between captures too */}
141
147
  {session || recording ? <i className="jm-live-dot" /> : <WaveformIcon size={16} />}
142
148
  {session && <span className="jm-clock">{minutes}</span>}
@@ -226,7 +232,7 @@ export function WrapSheet({ style }: { style?: CSSProperties }) {
226
232
  const [busy, setBusy] = useState(false)
227
233
  const field = useRef<HTMLTextAreaElement>(null)
228
234
  useEffect(() => {
229
- fetch(`${ROUTE}/api/jam/session`, { headers: { 'x-mv-c': csrf() } }).then((r) => (r.ok ? r.json() : null)).then((b) => { setTalkMin(b?.talkMinutes ?? 0); setTags(b?.tags ?? 0); setFolder(typeof b?.folder === 'string' ? b.folder : null) }, () => {})
235
+ api('jam/session', { headers: { 'x-mv-c': csrf() } }).then((r) => (r.ok ? r.json() : null)).then((b) => { setTalkMin(b?.talkMinutes ?? 0); setTags(b?.tags ?? 0); setFolder(typeof b?.folder === 'string' ? b.folder : null) }, () => {})
230
236
  requestAnimationFrame(() => field.current?.focus())
231
237
  }, [])
232
238
  // the field grows with its words: three lines at least
@@ -309,7 +315,7 @@ export function RecordDetail({ card, agent, more, onMore, onMoreOpen, onGood, on
309
315
  const [rec, setRec] = useState<{ file: string; text: string | null; reply?: string } | null>(null)
310
316
  useEffect(() => {
311
317
  let live = true
312
- fetch(`${ROUTE}/api/jam/record?id=${encodeURIComponent(card.id)}`, { headers: { 'x-mv-c': csrf() } })
318
+ api(`jam/record?id=${encodeURIComponent(card.id)}`, { headers: { 'x-mv-c': csrf() } })
313
319
  .then((r) => (r.ok ? r.json() : null)).then((b) => { if (live && b) setRec(b) }, () => {})
314
320
  return () => { live = false }
315
321
  }, [card.id, card.state, card.rev])
@@ -18,6 +18,7 @@
18
18
  import { create } from 'zustand'
19
19
  import { ROUTE } from '../const.ts'
20
20
  import { CONFIG, useStore } from './store.ts'
21
+ import { api } from './api.ts'
21
22
 
22
23
  export const RATE = 16_000
23
24
  const FINAL_MS = 3_000
@@ -68,20 +69,20 @@ export const useJamVoice = create<VoiceStore>((set, get) => ({
68
69
  },
69
70
  async refresh() {
70
71
  try {
71
- const r = await fetch(`${ROUTE}/api/jam/voice`, { headers: { 'x-mv-c': csrf() } })
72
+ const r = await api('jam/voice', { headers: { 'x-mv-c': csrf() } })
72
73
  if (!r.ok) { set({ server: 'unavailable', reason: 'jam is not running here' }); return }
73
74
  const b = await r.json()
74
75
  set({ server: b.state, reason: b.reason, download: b.download ?? null, mb: b.mb ?? 490 })
75
76
  } catch { set({ server: 'unavailable', reason: 'marver dev did not answer' }) }
76
77
  },
77
78
  async startDownload() {
78
- try { await fetch(`${ROUTE}/api/jam/voice`, { method: 'POST', headers: { 'x-mv-c': csrf(), 'content-type': 'application/json' }, body: JSON.stringify({ download: true }) }) } catch { /* the poll says */ }
79
+ try { await api('jam/voice', { method: 'POST', headers: { 'x-mv-c': csrf(), 'content-type': 'application/json' }, body: JSON.stringify({ download: true }) }) } catch { /* the poll says */ }
79
80
  poll()
80
81
  },
81
82
  async retry() {
82
83
  toldUnavailable = false
83
84
  try {
84
- const r = await fetch(`${ROUTE}/api/jam/voice`, { method: 'POST', headers: { 'x-mv-c': csrf(), 'content-type': 'application/json' }, body: JSON.stringify({ retry: true }) })
85
+ const r = await api('jam/voice', { method: 'POST', headers: { 'x-mv-c': csrf(), 'content-type': 'application/json' }, body: JSON.stringify({ retry: true }) })
85
86
  if (r.ok) { const b = await r.json(); set({ server: b.state, reason: b.reason, download: b.download ?? null, mb: b.mb ?? 490 }); return }
86
87
  } catch { /* below */ }
87
88
  await get().refresh()
@@ -144,8 +145,11 @@ interface Segment {
144
145
  }
145
146
  interface Mic { ctx: AudioContext; stream: MediaStream; node: AudioWorkletNode; seg: Segment | null; closed: boolean }
146
147
  let mic: Mic | null = null
147
- /** A microphone being opened (its permission, its worklet): a newer change cancels it. */
148
- let opening: { cancelled: boolean } | null = null
148
+ /** A microphone being opened (its permission, its worklet, its connection): a newer change cancels it. It holds
149
+ * what it has opened so far, so a cancel stops its track and closes its context in that same turn - an opening
150
+ * can wait on a request that never answers, and a track it holds is live until stopped (A2.14 #13). */
151
+ interface Opening { cancelled: boolean; stream: MediaStream | null; ctx: AudioContext | null }
152
+ let opening: Opening | null = null
149
153
  let segN = 0
150
154
  /** segment -> its owner (the words it brings back belong to it) */
151
155
  const owners = new Map<string, Owner>()
@@ -168,7 +172,8 @@ function socket(reclaim = false): Promise<WebSocket | null> {
168
172
  if (wsOpen) return wsOpen
169
173
  wsOpen = (async () => {
170
174
  try {
171
- const r = await fetch(`${ROUTE}/api/jam/audio-ticket`, { method: 'POST', headers: { 'x-mv-c': csrf() } })
175
+ // the ticket names this canvas's workspace like every request (A1.11); the socket it opens is bound by it
176
+ const r = await api('jam/audio-ticket', { method: 'POST', headers: { 'x-mv-c': csrf() } })
172
177
  if (!r.ok) return null
173
178
  const { ticket } = await r.json()
174
179
  const s = new WebSocket(`${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}${ROUTE}/api/jam/audio?ticket=${encodeURIComponent(ticket)}${reclaim ? '&reclaim=1' : ''}`)
@@ -242,7 +247,7 @@ function takeBackLater() {
242
247
  waitingBack = setInterval(async () => {
243
248
  if (!session || (mic && !mic.closed)) { clearInterval(waitingBack!); waitingBack = null; return }
244
249
  try {
245
- const r = await fetch(`${ROUTE}/api/jam/voice`, { headers: { 'x-mv-c': csrf() } })
250
+ const r = await api('jam/voice', { headers: { 'x-mv-c': csrf() } })
246
251
  const b = r.ok ? await r.json() : null
247
252
  if (b && b.busy === false) { clearInterval(waitingBack!); waitingBack = null; reclaiming = true; void reconcile() }
248
253
  } catch { /* ask again */ }
@@ -314,10 +319,30 @@ function endSegment(s: Segment, at: { start: number; pcm: Int16Array; mark: numb
314
319
  /** Who the microphone should hear now: what runs (a capture, else the session's talk) - if you said yes
315
320
  * and the engine can run. */
316
321
  const wanted = (): Owner | null => {
322
+ if (barred) return null
317
323
  const v = useJamVoice.getState()
318
324
  return v.choice === 'yes' && (v.server === 'ready' || v.server === 'loading') ? target() : null
319
325
  }
320
326
 
327
+ /** The page lost the Mac app's trust while it lives (spec 28 A2.14 #13, `mv:app-state untrusted`): the app can refuse
328
+ * every new microphone request, but only the page can stop a track it already holds. */
329
+ let barred = false
330
+ /** Every microphone track this page holds stops now - the way a lost connection stops it: the words heard so far
331
+ * are kept, marked maybe incomplete - an opening still waiting is cancelled, and nothing opens the microphone again
332
+ * in this document (the next one is proved afresh). */
333
+ export function voiceUntrusted(): void {
334
+ barred = true
335
+ cancelOpening()
336
+ const m = mic
337
+ if (m && !m.closed) {
338
+ if (m.seg) broken.add(m.seg.owner.id)
339
+ closeNow(m)
340
+ if (mic === m) mic = null
341
+ setLive()
342
+ }
343
+ useJamVoice.setState({ asking: false })
344
+ }
345
+
321
346
  /** Bring the microphone to what should be heard NOW. Every change - open, switch, close - is one step in
322
347
  * one chain, so no change overtakes another: a switch ends the current segment and starts the next at
323
348
  * the same worklet mark (nothing lost, nothing heard twice); an opening still waiting gives way to a
@@ -348,19 +373,20 @@ async function step() {
348
373
 
349
374
  /** Open the microphone for `owner` - one step of the chain; a newer state cancels it at its next wait. */
350
375
  async function open(owner: Owner) {
351
- const op = { cancelled: false }
376
+ const op: Opening = { cancelled: false, stream: null, ctx: null }
352
377
  opening = op
353
378
  const stale = () => op.cancelled || wanted()?.id !== owner.id
354
- let stream: MediaStream | null = null
355
- let ctx: AudioContext | null = null
356
- const undo = () => { stream?.getTracks().forEach((t) => t.stop()); void ctx?.close().catch(() => {}) }
379
+ const undo = () => release(op)
357
380
  try {
358
381
  // the microphone first (its permission, its worklet), the connection last: a page never holds the one
359
382
  // audio connection while it is still starting - and a reclaim takes it only if it is free
383
+ let stream: MediaStream
360
384
  try { stream = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true } }) }
361
385
  catch { useJamVoice.setState({ denied: true }); useStore.getState().toast('the microphone is blocked for this page - typed notes only'); return }
386
+ op.stream = stream
362
387
  if (stale()) { undo(); return }
363
- ctx = new AudioContext({ sampleRate: RATE })
388
+ const ctx = new AudioContext({ sampleRate: RATE })
389
+ op.ctx = ctx
364
390
  await ctx.audioWorklet.addModule(URL.createObjectURL(new Blob([WORKLET], { type: 'application/javascript' })))
365
391
  if (stale()) { undo(); return }
366
392
  // a capture is something you just did here: it takes the connection; a session's talk only takes it if it
@@ -373,6 +399,9 @@ async function open(owner: Owner) {
373
399
  const node = new AudioWorkletNode(ctx, 'mv-pcm')
374
400
  ctx.createMediaStreamSource(stream).connect(node)
375
401
  const m: Mic = { ctx, stream, node, seg: null, closed: false }
402
+ // the microphone owns them now: closeNow stops them, never the opening
403
+ op.stream = null
404
+ op.ctx = null
376
405
  mic = m
377
406
  const seg = segmentFor(owner, -1)
378
407
  m.seg = seg
@@ -383,10 +412,21 @@ async function open(owner: Owner) {
383
412
  setLive()
384
413
  } catch {
385
414
  undo()
386
- useStore.getState().toast('the microphone could not start - typed notes only')
415
+ // a cancelled opening whose context closed under its worklet says nothing: nothing failed
416
+ if (!op.cancelled) useStore.getState().toast('the microphone could not start - typed notes only')
387
417
  } finally { if (opening === op) opening = null }
388
418
  }
389
- const cancelOpening = () => { if (opening) opening.cancelled = true }
419
+ /** What an opening holds goes, once: its tracks stopped, its context closed. */
420
+ function release(op: Opening) {
421
+ const { stream, ctx } = op
422
+ op.stream = null
423
+ op.ctx = null
424
+ stream?.getTracks().forEach((t) => t.stop())
425
+ void ctx?.close().catch(() => {})
426
+ }
427
+ /** A newer change, or the app's `untrusted`: the opening goes, and what it already holds stops now - not at its
428
+ * next wait, which may never come. The opening still sees itself cancelled when that wait ends, and opens nothing. */
429
+ const cancelOpening = () => { if (opening) { opening.cancelled = true; release(opening) } }
390
430
  /** The chain settled - but never longer than `ms` (an opening may wait on the browser's permission
391
431
  * question; what the caller needs - the cuts of its segments - is done before it). */
392
432
  const settle = (ms = 2_000) => Promise.race([reconcile(), new Promise<void>((r) => setTimeout(r, ms))])
@@ -476,4 +516,4 @@ export async function voiceSessionEnd(): Promise<void> {
476
516
  await settled(s.id)
477
517
  }
478
518
 
479
- if (typeof window !== 'undefined' && (import.meta as any).env?.DEV) { (window as any).__mvJamVoice = useJamVoice; (window as any).__mvJamVoiceSession = voiceSessionId }
519
+ if (typeof window !== 'undefined' && (import.meta as any).env?.DEV) { (window as any).__mvJamVoice = useJamVoice; (window as any).__mvJamVoiceSession = voiceSessionId; (window as any).__mvJamVoiceTalk = voiceSession }
@@ -17,7 +17,7 @@ import { stableNodeKey } from './keys.ts'
17
17
  import { UNPLACED, type HashState } from './hash.ts'
18
18
  import { ALL_SCENES_KEYS, boardLabel, fetchMembership, PUBLISHED } from './store.ts'
19
19
  import { useComments } from './comments-store.ts'
20
- import { ROUTE } from '../const.ts'
20
+ import { api } from './api.ts'
21
21
 
22
22
  export const isLegacyLink = (h: HashState): boolean => h.board === ALL_SCENES
23
23
 
@@ -44,7 +44,7 @@ export async function landLegacy(h: HashState): Promise<{ hash: HashState; notic
44
44
  const byKey = new Map([...live.map((id) => [stableNodeKey(ALL_SCENES, id, 0), id] as const), ...Object.entries(ALL_SCENES_KEYS)])
45
45
  if (!PUBLISHED) {
46
46
  try {
47
- const leftover = (await (await fetch(`${ROUTE}/api/boards/${ALL_SCENES}`)).json())?.board as { nodes?: { key?: unknown; frame?: unknown }[] } | null
47
+ const leftover = (await (await api(`boards/${ALL_SCENES}`)).json())?.board as { nodes?: { key?: unknown; frame?: unknown }[] } | null
48
48
  for (const node of Array.isArray(leftover?.nodes) ? leftover.nodes : []) if (typeof node?.key === 'string' && typeof node.frame === 'string') byKey.set(node.key, node.frame)
49
49
  } catch { /* no leftover, or not JSON: the minted keys stand */ }
50
50
  }
@@ -1,9 +1,26 @@
1
1
  import { createRoot } from 'react-dom/client'
2
- import { App, ShellBoundary } from './App.tsx'
2
+ // an all-boards-locked build gives LockedApp.tsx in App.tsx's place: what only the canvas uses comes through it
3
+ import { App, ShellBoundary, startPerfRunProbe } from './App.tsx'
3
4
  import { useStore } from './store.ts'
5
+ import { startRecorder } from './recorder.ts'
6
+ import { capturesPending, sealOnLeave } from './jam-capture.ts'
7
+ import { startAppBridge } from './app-bridge.ts'
8
+ import { startAppPerf } from './app-perf.ts'
9
+ import { applyInset } from './inset.ts'
4
10
  import './styles.css'
5
11
 
6
12
  // dev aid: inspectable store (harmless in builds; the canvas is a dev surface)
7
13
  ;(window as any).__sh = useStore
14
+ // what each board load does, from the page (spec 28 A1.7): before the first load; nothing on a published canvas
15
+ startRecorder({ capturesPending, sealCaptures: sealOnLeave })
16
+ // under the Mac app's transparent strip (0.27.2, A3.8 #31): --mv-top on :root before anything is placed; nothing
17
+ // anywhere else (Chrome, a published canvas, app 0.1)
18
+ applyInset()
19
+ // in the Mac app: hello, theme, busy and menu before the first render (spec 28 A2.9); nothing anywhere else
20
+ startAppBridge()
21
+ // in the Mac app 0.2: the recorder's probes and the board's frame count (spec 28 A3.8 #9, #16); nothing anywhere else
22
+ startAppPerf()
23
+ // a headless perf run (spec 28 A3.8 #17): what its driver reads and asks, through CDP - nothing without ?mvperfrun
24
+ startPerfRunProbe()
8
25
 
9
26
  createRoot(document.getElementById('root')!).render(<ShellBoundary><App /></ShellBoundary>)
@@ -3,6 +3,7 @@
3
3
  * carries the state (blue new, orange needs you); the row's one right-hand slot holds what matters
4
4
  * most: a question's numbered bubble, then the row's own count or status, then a frame's dot.
5
5
  */
6
+ import { onScreen } from './inset.ts'
6
7
  import { useEffect, type HTMLAttributes, type ReactNode } from 'react'
7
8
  import { create } from 'zustand'
8
9
  import { useStore, PUBLISHED, shownRev } from './store.ts'
@@ -95,13 +96,14 @@ export function useSeenOnScreen() {
95
96
  } else if (m && !document.hidden && s.scale >= 0.5) {
96
97
  // in view: some of it inside the window and not all of that under the open sidebar
97
98
  const P = document.querySelector('.sh-panel:not(.closed)')?.getBoundingClientRect()
98
- const W = window.innerWidth, H = window.innerHeight
99
99
  for (const n of s.nodes) {
100
100
  if (n.status !== 'ready' || n.stale || !isNew(m, n.frame) || shownRev(n, m) < (m.doc[n.frame] ?? 0)) continue
101
101
  const r = document.querySelector<HTMLElement>(`.sh-node[data-node="${CSS.escape(n.key)}"]`)?.getBoundingClientRect()
102
102
  if (!r) continue
103
- const x0 = Math.max(r.left, 0), x1 = Math.min(r.right, W), y0 = Math.max(r.top, 0), y1 = Math.min(r.bottom, H)
104
- if (x0 >= x1 || y0 >= y1) continue
103
+ // the part on screen below the scroll edge (inset.ts): under the Mac app's strip is not seen
104
+ const on = onScreen(r)
105
+ if (!on) continue
106
+ const x0 = on.left, x1 = on.right, y0 = on.top, y1 = on.bottom
105
107
  if (P && x0 >= P.left && x1 <= P.right && y0 >= P.top && y1 <= P.bottom) continue
106
108
  shown.set(`${n.key}@${m.changed[n.frame] ?? 0}:${n.shown}`, n.key)
107
109
  }