Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

address review (codex): arbitrate the iOS audio session instead of assigning it

[._.]/ Adam Eivyad8e0c3e0598
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 5e67c39c11..bce756d302 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -16,7 +16,7 @@
- **[issue-3407] Stacker News sync works again.** Stacker News renamed its territory listing route from `/recent` to `/new`, so every browser-transport sync was refused with "landed on a different page than the one requested" — the redirect guard correctly caught the rename. Syncs now request the new route directly; the guard stays strict.
- **A completed TUI agent could be recorded as failed by a duplicate finalize.** `cleanupOrphanedAgents` runs every 15 minutes and calls `syncRunnerAgents`, which only checked `runnerAgents` for "already tracked" — but a runner-backed TUI agent is owned by the live `spawnTuiAgent` closure, which registers in `activeAgents` and never in `runnerAgents`. Any TUI run outliving one health-check tick was therefore hoisted into `runnerAgents` mid-flight, so the `agent:completed` event the runner emits when the TUI spawner's own `finish()` kills the session slipped past the `if (!agent) return` guard and ran a *second* `finalizeAgent`. That overwrote a sentinel-signalled success with `success: false, exitCode: 143` plus a bogus `startup-failure` analysis (computed from an output buffer that path can't read — a TUI writes `output.txt` under the dated run dir, not `AGENTS_DIR/<id>`), which in turn flipped the agent card to Failed and requeued the already-finished task as `pending`. Observed on a 55-minute release-check run that had already published v2.37.0 and merged all three of its PRs.
- **`completeAgent` is now idempotent, so the caller-level guard is no longer the only line of defense.** Six call sites funnel every terminal agent write through `completeAgent`, and each carried the same latent "I might be second" assumption. A duplicate call re-recorded `result` (success verdict, exit code, error analysis) and re-ran the completed-agent directory move; the guards that caught the TUI double-finalize above read the record *outside* the state lock, so they narrowed the race rather than closing it. `completeAgent` now returns an already-`completed` record unmutated from inside the lock it already holds — and skips the budget-ledger charge and the second `agent:completed` emit that would otherwise re-run the scheduler hand-off. `paused` records are still completable, so a resumed agent can't wedge. The one thing a duplicate *does* still do is finish a half-written archive: `archiveCompletedAgent` is now idempotent (the directory move is skipped once the date bucket exists, the index write always re-runs because `saveAgentIndex` swallows its own errors), and the cross-filesystem copy fallback rolls back a partially-copied target instead of leaving a directory that every later attempt mistakes for a finished archive.
-- **The SongBook drum play-along makes sound on iPhone Safari again — kit and metronome both.** Two iOS-only failures stacked into total silence while the transport counted and the playhead scrolled, so nothing on screen explained it. First, iOS leaves a page's Web Audio on the *ambient* audio session unless it says otherwise, and an ambient session is muted by the hardware ring/silent switch — a pure-synth play-along has no media element to lift it out of one. `createLookaheadTransport` gained an `audioSession` option, and the drum player passes `'playback'` (Safari 16.4+): the transport declares it before the context resumes and hands it back on teardown. Scoped that way on purpose — the session belongs to the DOCUMENT, not the context, and `playback` marks the page output-only, so in a single-page app a declaration that is never released follows the user to the Songs training views, `audioRecorder` and the voice client and kills the microphone they all open. Holding it only while a transport is sounding is what makes it safe, and it stays a per-player capability rather than a transport default because `scorePlayback`/`midiPlayback`/`metronome` share pages with those capture surfaces. Second, every resume gate in the app read `state === 'suspended'`, and iOS Safari also parks a context in the non-standard `'interrupted'` (a call, Siri, the screen locking, another tab taking the session) — so a page returned to after any of those armed its scheduler against a clock that never advanced and "played" in silence until reload. The shared `resumeAudioContext(c)` now gates on `state !== 'running'` (skipping only `'closed'`, whose resume would reject), and all ten resume sites route through it: the lookahead transport (drums, score, MIDI, chiptune), the metronome, layered song playback, the Morse trainer, the stream analyser, the voice client's playback and capture contexts, and the Security page's meter plus its "Enable audio" button — which could previously rescue a suspended context but not an interrupted one.
+- **The SongBook drum play-along makes sound on iPhone Safari again — kit and metronome both.** Two iOS-only failures stacked into total silence while the transport counted and the playhead scrolled, so nothing on screen explained it. First, iOS leaves a page's Web Audio on the *ambient* audio session unless it says otherwise, and an ambient session is muted by the hardware ring/silent switch — a pure-synth play-along has no media element to lift it out of one. `createLookaheadTransport` gained an `audioSession` option, and the drum player passes `'playback'` (Safari 16.4+). That session is **arbitrated, not assigned**, because it belongs to the DOCUMENT rather than the context and `playback` marks the page output-only — it *refuses* capture. PortOS is a single-page app with a globally-mounted VoiceWidget, so a naive "set it when you start playing" breaks twice: it outlives the route that set it, and it collides with a mic that can open on any page at any moment — either way trading this silence for a dead microphone on voice, `audioRecorder`, and the Songs training views. So `acquireAudioSession(type)` hands out claims with idempotent releases and declares the union of what's live: capture always wins, since `play-and-record` satisfies both sides (it ignores the ring/silent switch too, so the play-along stays audible through a voice turn). The transport claims on play and releases on teardown — including the paths where nothing ever sounds: a `pause()` that cancels a play still awaiting its resume, a rejected resume, and an empty schedule. It stays a per-player capability rather than a transport default because `scorePlayback`/`midiPlayback`/`metronome` share pages with those capture surfaces and have no silent-switch problem to solve. Second, every resume gate in the app read `state === 'suspended'`, and iOS Safari also parks a context in the non-standard `'interrupted'` (a call, Siri, the screen locking, another tab taking the session) — so a page returned to after any of those armed its scheduler against a clock that never advanced and "played" in silence until reload. The shared `resumeAudioContext(c)` now gates on `state !== 'running'` (skipping only `'closed'`, whose resume would reject), and all ten resume sites route through it: the lookahead transport (drums, score, MIDI, chiptune), the metronome, layered song playback, the Morse trainer, the stream analyser, the voice client's playback and capture contexts, and the Security page's meter plus its "Enable audio" button — which could previously rescue a suspended context but not an interrupted one.
## Changed
diff --git a/PLAN.md b/PLAN.md
index 3f9bee54ca..4650c70a7b 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -333,4 +333,4 @@ is not reliably announced.
### Hold the iOS `playback` audio session on the other output-only players too
-- [ ] The SongBook drum play-along now passes `audioSession: 'playback'` to `createLookaheadTransport` so the iPhone ring/silent switch can't mute it (declared on play, released on teardown — see the audio-session note in `client/src/lib/audioContext.js`). The same silence still applies to every other output-only surface that never records: `client/src/lib/chiptunePlayback.js` (drives the same transport from `ChiptunePanel`, so it is a one-key change), `client/src/components/meatspace/post/MorseTrainer.jsx` (own per-mount context — needs the `declareAudioSession`/`releaseAudioSession` pair around its own lifecycle, not the transport option), and `client/src/pages/Security.jsx`'s alert tones. The players NOT to touch are `scorePlayback` / `midiPlayback` / `metronome`: they run on the Songs training views beside `useSingToScore` / `useSingToVerify`, and the session declaration is document-wide, so pinning `playback` there would silence the mic those views depend on — that's the whole reason the option is per-player rather than baked into the transport. Each needs an actual iPhone with the ringer switch OFF to verify; a jsdom test can only pin the declare/release calls (as `drumPlayer.test.js` does). Deferred from the drums fix, which was scoped to the reported page. Surfaced by the /simplify altitude review.
+- [ ] The SongBook drum play-along now passes `audioSession: 'playback'` to `createLookaheadTransport` so the iPhone ring/silent switch can't mute it (claimed on play, released on teardown, arbitrated against live mic claims — see the audio-session note in `client/src/lib/audioContext.js`). The same silence still applies to every other output-only surface: `client/src/lib/chiptunePlayback.js` (drives the same transport from `ChiptunePanel`, so it is a one-key change), `client/src/components/meatspace/post/MorseTrainer.jsx` (own per-mount context — needs an `acquireAudioSession('playback')` claim around its own play lifecycle, not the transport option), and `client/src/pages/Security.jsx`'s alert tones. The players NOT to touch are `scorePlayback` / `midiPlayback` / `metronome`: they run on the Songs training views beside `useSingToScore` / `useSingToVerify`, and while the arbiter would now keep those mics working, claiming `playback` there buys nothing those views asked for — that's why the option is per-player rather than baked into the transport. While you're there, claim `play-and-record` in `useSingToScore` / `useSingToVerify` around their own `getUserMedia` for symmetry with `voiceClient` / `audioRecorder`: they are safe today only because no `playback` claimant shares their route, which is an accident of routing rather than an invariant. Each needs an actual iPhone with the ringer switch OFF to verify; a jsdom test can only pin the claim/release calls (as `drumPlayer.test.js` does). Deferred from the drums fix, which was scoped to the reported page. Surfaced by the /simplify altitude review and the codex review pass.
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index e7b3cc2222..97bd987663 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -120,7 +120,7 @@ grep -i "what you want to do" client/src/lib/README.md
| Module | Purpose |
|---|---|
-| `audioContext.js` | `getAudioContext()` + `resumeAudioContext(c)` + `declareAudioSession(type)` / `releaseAudioSession()` + `getNoiseBuffer(c)` (the app-wide 1s white-noise buffer every noise voice loops over — chiptune drums, the drum kit's snare/hats/cymbals; don't grow a third copy) — the ONE app-wide lazy Web Audio `AudioContext` singleton every playback feature shares (`songPlayback`, `scorePlayback`, `metronome`, `midiPlayback`). Browsers cap live contexts and one context = one sample clock, so simultaneous features stay aligned. **Every playback entry point resumes via `resumeAudioContext(c)`, never by hand** (it takes any context, so per-mount ones use it too) — it gates on `state !== 'running'`, not `state === 'suspended'`, because iOS Safari also parks a context in the non-standard `'interrupted'` (a call/Siri/screen lock) which a suspended-only check walks past into silent "playback". The audio-session pair sets `navigator.audioSession.type` so the hardware ring/silent switch can't mute a pure-synth page — but the session is **document-wide** and `playback` marks the page output-only, so in an SPA it must be **held only while sounding**, or it follows the user onto a route that records and kills the mic. Don't call the pair directly: an output-only player passes `audioSession: 'playback'` to `createLookaheadTransport`, which declares on play and releases on teardown. Constructor resolved lazily (`window` → `globalThis`) so node-env test runs import cleanly; tests inject a fake via `vi.stubGlobal('AudioContext', …)` before first call. |
+| `audioContext.js` | `getAudioContext()` + `resumeAudioContext(c)` + `acquireAudioSession(type)` + `getNoiseBuffer(c)` (the app-wide 1s white-noise buffer every noise voice loops over — chiptune drums, the drum kit's snare/hats/cymbals; don't grow a third copy) — the ONE app-wide lazy Web Audio `AudioContext` singleton every playback feature shares (`songPlayback`, `scorePlayback`, `metronome`, `midiPlayback`). Browsers cap live contexts and one context = one sample clock, so simultaneous features stay aligned. **Every playback entry point resumes via `resumeAudioContext(c)`, never by hand** (it takes any context, so per-mount ones use it too) — it gates on `state !== 'running'`, not `state === 'suspended'`, because iOS Safari also parks a context in the non-standard `'interrupted'` (a call/Siri/screen lock) which a suspended-only check walks past into silent "playback". **`acquireAudioSession(type)` ARBITRATES `navigator.audioSession.type`, which is document-wide, and returns an idempotent release** — `playback` keeps the hardware ring/silent switch from muting a pure-synth page but REFUSES capture, and the VoiceWidget is mounted on every page, so a last-writer-wins assignment trades one platform's silence for a dead mic. Each feature claims for exactly as long as it needs (`play-and-record` while a `getUserMedia` stream is open, `playback` while a player sounds) and the arbiter declares the union — capture always wins, since `play-and-record` also ignores the silent switch. Output-only players don't call it directly: pass `audioSession: 'playback'` to `createLookaheadTransport`, which claims on play and releases on teardown. Constructor resolved lazily (`window` → `globalThis`) so node-env test runs import cleanly; tests inject a fake via `vi.stubGlobal('AudioContext', …)` before first call. |
| `cityPlaybackFrame.js` | Map a recorded CyberCity snapshot frame onto the prop shape CityScene/CityHud consume for the timeline scrubber (`mergeFrameIntoCityProps`, `buildPlaybackApps`, `buildPlaybackAgentMap`, `isPlayableFrame`). Honors `schemaVersion` and the capture-side null sentinels; returns only snapshot-backed props so unfed landmarks stay live. |
| `chordShapes.js` | Chord-name → per-instrument voicing derivation for the SongBook viewer's instrument-view toggle (#2656). `getChordVoicing(name, instrument)` → guitar `{ frets: [6 × (-1/0/n)], baseFret, bass }`, ukulele (4-string GCEA, exact lowest-position search), or piano `{ notes: ['A','C','E'], bass }` with letter-accurate degree spelling (the 3rd of E is G#, never Ab); guitar shapes come from a curated first-position table + movable E-/A-form barre templates offset by `baseFret` (aug/dim7 exploit shape symmetry). Slash chords voice the base chord and carry `bass` separately. `parseChordName(name)`, `splitJoinedChords('Am-Am7')`, `toVoicingInstrument(songInstrument)`, `VOICING_INSTRUMENTS`. Reuses `tabNotation.js`'s `CHORD_TOKEN_RE`/`NOTE_TO_PC`/`spellPitchClass` (exported from there for this module) instead of duplicating the tables. Unknown/unparseable chords → null, never throws. |
| `canvasRoll.js` | Shared canvas helpers for the two piano-roll renderers (`<PianoRoll>` falling-note + `<MidiPianoRoll>` DAW-style, #2477). `layerColor(index)` — the per-layer/track palette (8 hues, wraps both directions) used by note bars, keyboards, and legends; `roundRect(ctx, x, y, w, h, r)` — rounded-rect path with `ctx.roundRect` feature-detect and arcTo fallback; `rollPalette()` — resolves the theme-following `{ bg, accent, accentRgb }` from `--port-accent` via `getComputedStyle` (canvas can't read CSS vars); `ROLL_BG` — the shared near-black bg literal. Pure canvas math/palette, no React. |
@@ -133,7 +133,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `drumKits.js` | The three selectable synth kits for the SongBook drum play-along — `DRUM_KIT_LIST` (the one ordered source of truth, first entry = default; the picker renders it directly) plus the derived `DRUM_KITS` / `DRUM_KIT_IDS` / `DEFAULT_DRUM_KIT` (`909` punchy, `808` deep-sub, `acoustic`), `resolveDrumKit(id)` (unknown/stale id → the default, never silence), `kitVoiceLayers(kit, sound)` (unmapped piece → the snare, never silence) and the kit-independent `CLICK_VOICE`. Pure DATA: each voice is a list of LAYERS — `tone` (`wave, from, to, pitchDecay, drive`), `noise` (`filter`), or `metal` (N square `partials` summed into one filter+envelope) — that `drumPlayback.js` realizes in Web Audio. Three properties carry the kit's punch and are easy to undo by accident: `pitchDecay` is INDEPENDENT of the amplitude `decay` (a membrane snaps to its fundamental in ~30–60ms then holds while the tail runs on — coupling the two is what made the original kick sound weak), `drive` tanh-saturates a layer so a sub-50 Hz kick generates the harmonics a phone/laptop speaker can actually reproduce, and a `metal` layer's high-pass cutoffs are far LOWER (and gains far higher) than the noise voices beside them because a square's harmonics fall off 6 dB/octave — see the calibration warning in the file before "harmonizing" those numbers. |
| `drumNotation.js` | Parser for the PortOS drum-kit notation (#3115) — a dependency-free GRID DSL (`HH: x x x x`) for the SongBook `drum` content format, drawn by `<DrumSheetView>` (hand-rolled SVG, no engraving lib). `parseDrumChart(text)` → `{ time, tempo, subdivision, stepsPerBar, bars:[{index,label,repeat,repeatPass,rows:[{piece,cells}]}], pieces, errors }` — `key: value` headers (`time`/`tempo`/`subdivision`/`kit` row-order override), blank-line-separated bar blocks with a `# label x2` repeat suffix expanded into real bars, nine kit pieces (`CR RD HH T1 T2 S FT K HF`, long aliases accepted), six cell glyphs (`-` rest, `x` normal, `X` accent, `o` open, `g` ghost, `f` flam) with spacing optional. Forgiving: short rows pad with rests, over-long rows truncate, unknown pieces/cells collect into `errors` — never throws. Plus `KIT_PIECES` (label / GM `midi` / synth `sound` / `glyph`), `kitPiece(id)`, `CELL_GLYPHS` (per-glyph velocity + flags), `isDrumNotation(text)` (import-page format sniff, runs BEFORE `tabNotation.detectFormat`), `drumChartHasMusic(text)` and its already-parsed twin `chartHasMusic(chart)`. Also the plain-language explainers the sheet's tap-a-note readout and Legend panel read — `describeDrumCell(pieceId, cell)` → `{ pieceLabel, char, articulation, detail, technique, velocityPercent, rest }` (piece-aware: `o` is "Open" on a hi-hat/cymbal but a normal hit on a drum; a null/unknown cell describes as a rest, an unknown piece returns null), `describeDrumPosition(bar, step, subdivision)` → `bar 6, count “2 e”` (count-along syllables, exact `+n/N` fallback for an unconventional subdivision), `drumGlyphLegend(pieceIds)` (all six cell characters, with the `o` row resolved for the pieces a chart uses — a fixed row would tell a crash-only chart to work the hi-hat pedal; a mixed kit gets every applicable reading) and each `KIT_PIECES` row's `technique` (how that piece is struck). Only the hi-hat voice sustains an `o` in playback, so the `open` wording follows the piece's `sound`, not its glyph shape. NOT the lead-sheet parser (`scoreNotation.js`). |
| `drumPlayback.js` | Synthesized drum-kit play-along for the SongBook `drum` format (#3115) — the third consumer of `lookaheadTransport.js` alongside `scorePlayback`/`midiPlayback`. `buildDrumSchedule(chart, { bpm, loop, countInBars })` is the PURE chart→`[{ bar, step, piece, sound, velocity, startSec, durSec, countIn }]` mapping (one notated beat = `60/bpm`, one grid step = beat/`subdivision`; per-glyph velocity; a looped bar range is sliced and rebased while keeping the CHART's bar numbers for the playhead) — unit-tested with no Web Audio; `resolveLoopRange(barCount, loop)` clamps/normalizes a 1-based inclusive bar range; the count-in is scheduled as real `countIn: true` events on the same clock so there is no second timer. `createDrumPlayer(chart, { bpm, countInBars, loopBars, clickEnabled, clickVolume, kit, onStep, onEnded })` sounds it on the shared `AudioContext` from a SYNTHESIZED kit (no shipped samples — recipes in `drumKits.js`, realized here as per-layer oscillator/noise + optional tanh drive + optional filter into a soft-clipped master bus; open-hat tail, flam grace note) with an optional layered metronome click, loops the range scheduler-exactly (count-in only on the first pass), and reports `onStep({ bar, step, countIn })` for the `<DrumSheetView>` playhead. The metronome — the through-music click AND the count-in, which both sound `CLICK_VOICE`, never a kit piece — rides its OWN gain bus into the master, so `setClickVolume(0–1)` moves clicks already queued in the lookahead window instead of only the next ones (a level of 0 additionally schedules no click voice at all — the level persists, so a silenced click must not keep building a voice per beat forever) (`clampClickVolume` returns null for an unset/garbled level so a caller can tell "never chosen" from a stored `DEFAULT_CLICK_VOLUME`-vs-silence). `setKit(id)`, `setClick(enabled)` and `setClickVolume(level)` apply LIVE (they touch no timing, unlike `setBpm`/`setLoop`/`setCountIn`, which only rebuild while idle). Pure (no React) — `SongBookViewer` owns the transport UI. |
-| `lookaheadTransport.js` | Shared lookahead-transport state machine for the synth players (#2493) — `createLookaheadTransport({ getTotalSec, scheduleWindow, prepare?, seekCursors?, onStop?, onEnded?, onTeardown? })` owns the Web Audio clock + live-node lifecycle (playing / interval / startTime / offsetSec / nodes / playToken, the `resumeAudioContext()` call with the teardown-race guard, the optional `audioSession` declaration held for exactly as long as the transport sounds, `track()` node pruning, and the play / pause / stop / seek / position transitions); each player supplies only the scheduling + notify callbacks and stays a thin scheduler over it, so a fix to the token-guard race or teardown lands in one place. Also the single source of the `SYNTH_TIMING` lookahead constants (`LEAD`/`LOOKAHEAD_MS`/`SCHEDULE_AHEAD`) `scorePlayback`/`midiPlayback` share. No React, no score/MIDI concepts — imports only the shared `AudioContext`. |
+| `lookaheadTransport.js` | Shared lookahead-transport state machine for the synth players (#2493) — `createLookaheadTransport({ getTotalSec, scheduleWindow, prepare?, seekCursors?, onStop?, onEnded?, onTeardown? })` owns the Web Audio clock + live-node lifecycle (playing / interval / startTime / offsetSec / nodes / playToken, the `resumeAudioContext()` call with the teardown-race guard, the optional `audioSession` claim held for exactly as long as the transport sounds, `track()` node pruning, and the play / pause / stop / seek / position transitions); each player supplies only the scheduling + notify callbacks and stays a thin scheduler over it, so a fix to the token-guard race or teardown lands in one place. Also the single source of the `SYNTH_TIMING` lookahead constants (`LEAD`/`LOOKAHEAD_MS`/`SCHEDULE_AHEAD`) `scorePlayback`/`midiPlayback` share. No React, no score/MIDI concepts — imports only the shared `AudioContext`. |
| `lossSparkline.js` | `lossSparklineGeometry(series, box)` — projects an unbounded training-loss series (`{step,loss}[]`) into SVG polyline coords, normalized to its own min/max (unlike `editorialHealth.sparklineGeometry`'s fixed 0–100 axis). Returns `{ points, coords, last, min, max }`. Drives the Render Queue's training-row loss curve (#1408). No React. |
| `metronome.js` | Sample-accurate Web Audio metronome — the shared timing grid for the song system and first consumer of the song `tempo` field. `createMetronome({ bpm, beatsPerBar, countInBars, onBeat, onCountInComplete })` lookahead-schedules accented click tones on the shared `AudioContext` clock (same pattern as `songPlayback.js`), emits `{ beat, bar, accent, countIn, whenAudioTime }` per beat (the beat-clock callback color-match/sing-to-score subscribe to), and tears down all timers on `stop()`. Plus `clampBpm` (20–320), `secondsPerBeat`, `timeSignatureFromScore`, `beatDescriptor`. |
| `midiChords.js` | Chord detection for the MIDI visualization UI (#2477). `detectChordWindows(notes, { minWindowSec })` sweeps the normalized note list for maximal spans where ≥2 distinct pitch classes sound simultaneously → `[{ startSec, endSec, label, midis }]` (adjacent same-label windows merged); `nameChord(pcs, bassPc)` maps a pitch-class set to a compact symbol (maj/min/dim/aug triads, maj7/7/m7/m7b5/dim7, sus2/sus4/add9, slash-chord inversions) and falls back to sorted pitch-class names (`C E G#`) rather than guessing wrong; `chordNoteNames(midis)` for tooltips. Pure — no canvas/React. |
diff --git a/client/src/lib/audioContext.js b/client/src/lib/audioContext.js
index dd611f213d..1a9f9fda51 100644
--- a/client/src/lib/audioContext.js
+++ b/client/src/lib/audioContext.js
@@ -28,38 +28,69 @@ let sharedCtx = null;
// fix: that session ignores the switch, which is what every other platform
// already does for a backing track or a metronome.
//
-// The catch, and the reason this is a SCOPED pair rather than a one-way switch:
-// the session belongs to the DOCUMENT, not to an AudioContext, and `playback`
-// declares the page output-only. PortOS is a single-page app, so a document
-// outlives every route — declare it on the SongBook drum page and never release
-// it and the Songs training views, `audioRecorder` and the voice client, all of
-// which `getUserMedia` on the same document, inherit an output-only session and
-// lose the microphone. So a feature holds the declaration only while it is
-// actually sounding: `createLookaheadTransport`'s `audioSession` option declares
-// on play and releases on teardown, which is where every caller should get this
-// from rather than calling these two by hand.
+// The catch: the session belongs to the DOCUMENT, not to an AudioContext, and
+// `playback` declares the page output-only — it REFUSES capture. PortOS is a
+// single-page app with a globally-mounted VoiceWidget (`Layout.jsx`), so the
+// naive "set it when you start playing" is wrong twice over: it outlives the
+// route that set it, and it collides head-on with a mic that can open at any
+// moment on any page. Either way the user loses `getUserMedia` — voice, the
+// Songs training views, `audioRecorder` — with nothing to explain it.
+//
+// So the session is ARBITRATED, not assigned. Each feature acquires the session
+// it needs for exactly as long as it needs it, and the arbiter declares the
+// union: a live capture always wins, because `play-and-record` satisfies BOTH
+// sides (it ignores the ring/silent switch just like `playback`, so a play-along
+// stays audible through it) while `playback` satisfies only one. When the last
+// holder releases, the document goes back to `auto` — the platform default,
+// deliberately not a remembered previous value, which would just re-pin whatever
+// the last feature happened to want.
+//
+// Callers rarely reach for this directly: an output-only player passes
+// `audioSession: 'playback'` to `createLookaheadTransport`, which acquires on
+// play and releases on teardown. Capture surfaces acquire `'play-and-record'`
+// around the window their `getUserMedia` stream is open.
//
// Safari 16.4+ only; `navigator.audioSession` is absent everywhere else and
// those browsers need nothing. Assignment is guarded because it runs from the
// play handler — a partial WebKit implementation rejecting the value must not
// take playback down with it.
-/** Declare this document's iOS audio session (e.g. `'playback'`). */
-export function declareAudioSession(type) {
+// Most-capable first: the first type any live holder wants is what gets declared.
+const SESSION_PRECEDENCE = ['play-and-record', 'playback'];
+
+// Live holders, one per un-released acquire. A LIST rather than a count per type
+// because two features can hold the same type independently (push-to-talk over
+// hands-free listening) and each must be able to release only its own claim.
+const sessionHolders = [];
+
+const declareSession = (type) => {
const session = globalThis.navigator?.audioSession;
if (!session) return;
try { session.type = type; } catch { /* older/partial WebKit */ }
-}
+};
+
+const applyEffectiveSession = () => {
+ declareSession(SESSION_PRECEDENCE.find(
+ (type) => sessionHolders.some((h) => h.type === type),
+ ) || 'auto');
+};
/**
- * Hand the document's audio session back to the platform default. `'auto'` — not
- * a remembered previous value — because `auto` is what lets WebKit pick per
- * activity, including promoting to a record-capable session when a later view
- * opens the mic. Restoring a captured value would just re-pin whatever the last
- * feature happened to declare.
+ * Claim the document's iOS audio session as `type` (`'playback'` for output-only,
+ * `'play-and-record'` while a mic stream is open) until the returned release
+ * function is called. Release is idempotent, so a caller with several teardown
+ * paths can call it from all of them.
*/
-export function releaseAudioSession() {
- declareAudioSession('auto');
+export function acquireAudioSession(type) {
+ const holder = { type };
+ sessionHolders.push(holder);
+ applyEffectiveSession();
+ return () => {
+ const i = sessionHolders.indexOf(holder);
+ if (i < 0) return; // already released
+ sessionHolders.splice(i, 1);
+ applyEffectiveSession();
+ };
}
/**
diff --git a/client/src/lib/audioContext.test.js b/client/src/lib/audioContext.test.js
index 73feb3392b..25e2945c92 100644
--- a/client/src/lib/audioContext.test.js
+++ b/client/src/lib/audioContext.test.js
@@ -3,7 +3,7 @@
// ambient (silenced by the hardware ring/silent switch).
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
-import { declareAudioSession, releaseAudioSession, resumeAudioContext } from './audioContext.js';
+import { acquireAudioSession, resumeAudioContext } from './audioContext.js';
const stubNavigator = (audioSession) => {
vi.stubGlobal('navigator', audioSession ? { audioSession } : {});
@@ -18,33 +18,99 @@ const fakeCtx = (state) => {
return c;
};
-describe('audio session', () => {
- beforeEach(() => { vi.unstubAllGlobals(); });
- afterEach(() => { vi.unstubAllGlobals(); });
+describe('audio session arbiter', () => {
+ // The arbiter's holder list is module state that outlives a test — by design,
+ // since the session it tracks belongs to the document. So every claim a test
+ // takes has to be handed back, or the next test starts with a stale holder
+ // pinning the session. `acquire` records the releases; afterEach drains them.
+ let releases = [];
+ const acquire = (type) => {
+ const release = acquireAudioSession(type);
+ releases.push(release);
+ return release;
+ };
+
+ beforeEach(() => { vi.unstubAllGlobals(); releases = []; });
+ afterEach(() => {
+ for (const release of releases) release();
+ vi.unstubAllGlobals();
+ });
- it('declares the requested session so the silent switch cannot mute the synth', () => {
+ it('declares the claimed session so the silent switch cannot mute the synth', () => {
const audioSession = { type: 'auto' };
stubNavigator(audioSession);
- declareAudioSession('playback');
+ acquire('playback');
expect(audioSession.type).toBe('playback');
});
- it('releases back to auto, so an output-only declaration cannot follow the user', () => {
- const audioSession = { type: 'playback' };
+ it('goes back to auto when the last holder releases', () => {
+ const audioSession = { type: 'auto' };
+ stubNavigator(audioSession);
+ const release = acquire('playback');
+ release();
+ expect(audioSession.type).toBe('auto');
+ });
+
+ // The whole reason this is arbitrated: the VoiceWidget is mounted on every
+ // page, so a mic can open while a play-along is sounding. `playback` REFUSES
+ // capture, so a naive last-writer-wins would kill the mic — `play-and-record`
+ // satisfies both (it ignores the ring/silent switch too).
+ it('lets a live capture outrank a play-along holding playback', () => {
+ const audioSession = { type: 'auto' };
stubNavigator(audioSession);
- releaseAudioSession();
+ const releasePlayer = acquire('playback');
+ const releaseMic = acquire('play-and-record');
+ expect(audioSession.type).toBe('play-and-record');
+ // The play-along stopping must not drop the still-open mic to a weaker session.
+ releasePlayer();
+ expect(audioSession.type).toBe('play-and-record');
+ releaseMic();
+ expect(audioSession.type).toBe('auto');
+ });
+
+ it('keeps playback while a player is still sounding after the mic closes', () => {
+ const audioSession = { type: 'auto' };
+ stubNavigator(audioSession);
+ const releasePlayer = acquire('playback');
+ acquire('play-and-record')();
+ expect(audioSession.type).toBe('playback');
+ releasePlayer();
+ expect(audioSession.type).toBe('auto');
+ });
+
+ // Push-to-talk over hands-free listening: two independent claims of the same
+ // type, so a count would be wrong and the first release must not free both.
+ it('tracks same-type holders independently', () => {
+ const audioSession = { type: 'auto' };
+ stubNavigator(audioSession);
+ const releaseA = acquire('play-and-record');
+ const releaseB = acquire('play-and-record');
+ releaseA();
+ expect(audioSession.type).toBe('play-and-record');
+ releaseB();
+ expect(audioSession.type).toBe('auto');
+ });
+
+ it("ignores a double release rather than freeing someone else's claim", () => {
+ const audioSession = { type: 'auto' };
+ stubNavigator(audioSession);
+ const releaseA = acquire('playback');
+ releaseA();
+ const releaseB = acquire('playback');
+ releaseA(); // idempotent — must not drop B's claim
+ expect(audioSession.type).toBe('playback');
+ releaseB();
expect(audioSession.type).toBe('auto');
});
it('is a no-op where navigator.audioSession does not exist (every non-Safari browser)', () => {
stubNavigator(null);
- expect(() => declareAudioSession('playback')).not.toThrow();
- expect(() => releaseAudioSession()).not.toThrow();
+ expect(() => acquire('playback')()).not.toThrow();
});
it('swallows a throwing setter — a partial WebKit must not take playback down', () => {
stubNavigator({ set type(_v) { throw new TypeError('unsupported'); } });
- expect(() => declareAudioSession('playback')).not.toThrow();
+ expect(() => acquire('playback')()).not.toThrow();
});
});
diff --git a/client/src/lib/audioRecorder.js b/client/src/lib/audioRecorder.js
index 2acf5c8948..3e8a1deb02 100644
--- a/client/src/lib/audioRecorder.js
+++ b/client/src/lib/audioRecorder.js
@@ -6,7 +6,7 @@
// recorder is wired to the live voice-agent socket pipeline (echo gating, VAD,
// streaming TTS). This is a standalone "record a clip, get a WAV" helper.
-import { resumeAudioContext } from './audioContext.js';
+import { resumeAudioContext, acquireAudioSession } from './audioContext.js';
const TARGET_SAMPLE_RATE = 16000;
@@ -125,7 +125,13 @@ export function createStreamAnalyser(stream, { fftSize = 2048 } = {}) {
* discard). Throws if mic access is denied.
*/
export async function startMemoRecording() {
- const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
+ // Claimed BEFORE getUserMedia — an output-only `playback` session held by a
+ // play-along elsewhere on the page would refuse the request outright — and
+ // handed back if the mic is denied, since neither stop() nor cancel() runs
+ // when this throws. See the audio-session note in audioContext.js.
+ const releaseSession = acquireAudioSession('play-and-record');
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
+ .catch((err) => { releaseSession(); throw err; });
const mimeType = pickRecordingMimeType();
const recorder = new MediaRecorder(stream, { mimeType });
const chunks = [];
@@ -133,7 +139,11 @@ export async function startMemoRecording() {
recorder.ondataavailable = (e) => { if (e.data && e.data.size > 0) chunks.push(e.data); };
recorder.start();
- const teardown = () => stream.getTracks().forEach((t) => t.stop());
+ // Both exit paths (stop and cancel) run this, and the release is idempotent.
+ const teardown = () => {
+ stream.getTracks().forEach((t) => t.stop());
+ releaseSession();
+ };
return {
stream,
diff --git a/client/src/lib/drumPlayer.test.js b/client/src/lib/drumPlayer.test.js
index f45dd605c9..3a35cc49f2 100644
--- a/client/src/lib/drumPlayer.test.js
+++ b/client/src/lib/drumPlayer.test.js
@@ -3,6 +3,7 @@ import { parseDrumChart } from './drumNotation.js';
import { createDrumPlayer } from './drumPlayback.js';
import { parseScore } from './scoreNotation.js';
import { createScorePlayer } from './scorePlayback.js';
+import { acquireAudioSession } from './audioContext.js';
import { createFakeAudio } from '../test/fakeAudioContext.js';
// The AUDIBLE half of drumPlayback.js — buildDrumSchedule's pure math is covered
@@ -443,6 +444,21 @@ describe('createDrumPlayer', () => {
expect(globalThis.navigator.audioSession.type).toBe('auto');
});
+ // The VoiceWidget is mounted on every page (Layout.jsx), so push-to-talk can
+ // open the mic while a chart is playing. `playback` REFUSES capture, so the
+ // arbiter has to promote — otherwise the fix for this page's silence would
+ // have made the mic dead on it instead.
+ it('yields to a mic opened mid-playback, then takes playback back', async () => {
+ const player = createDrumPlayer(CHART, {});
+ await player.play();
+ const releaseMic = acquireAudioSession('play-and-record');
+ expect(globalThis.navigator.audioSession.type).toBe('play-and-record');
+ releaseMic();
+ expect(globalThis.navigator.audioSession.type).toBe('playback');
+ player.stop();
+ expect(globalThis.navigator.audioSession.type).toBe('auto');
+ });
+
it('hands the session back when the chart ends on its own', async () => {
const player = createDrumPlayer(CHART, {});
await player.play();
diff --git a/client/src/lib/lookaheadTransport.js b/client/src/lib/lookaheadTransport.js
index e310fa42ea..a5518982f9 100644
--- a/client/src/lib/lookaheadTransport.js
+++ b/client/src/lib/lookaheadTransport.js
@@ -12,9 +12,7 @@
// Pure of any player specifics — no React, no score/MIDI concepts. Imports only
// the shared AudioContext; players import createLookaheadTransport from here.
-import {
- getAudioContext as ctx, resumeAudioContext, declareAudioSession, releaseAudioSession,
-} from './audioContext.js';
+import { getAudioContext as ctx, resumeAudioContext, acquireAudioSession } from './audioContext.js';
// Shared lookahead-scheduler timing — one definition so every synth player
// can't drift apart on feel. Lives here (not in scorePlayback.js) so the
@@ -61,8 +59,9 @@ const { LEAD, LOOKAHEAD_MS } = SYNTH_TIMING;
* WHILE this transport sounds, released on teardown. Only output-only players
* set it, and only to `'playback'`: that is what stops the iPhone's ring/silent
* switch from muting a pure-synth page. It is a capability of the player rather
- * than something the transport assumes, because the declaration is
- * document-wide — see the audio-session note in audioContext.js.
+ * than something the transport assumes, because the session is document-wide
+ * and shared with whatever else is making sound — see the audio-session note in
+ * audioContext.js (a live mic still wins; the arbiter handles that).
* @returns {{ play, pause, stop, seek, position, isPlaying, track }}
*/
export const createLookaheadTransport = ({
@@ -80,12 +79,27 @@ export const createLookaheadTransport = ({
const doSeekCursors = seekCursors || noop;
const doStop = onStop || noop;
const doEnded = onEnded || noop;
- // The player's own teardown, plus handing back any audio session this
- // transport declared — so an output-only player holds the document-wide
- // `playback` session only while it is actually sounding.
+ // The audio-session claim this transport currently holds, if any (see the
+ // `audioSession` option). One claim at a time: re-acquiring on a fresh play
+ // drops the previous one, so a play → play can't strand a holder in the
+ // arbiter and pin the document forever.
+ let releaseSession = null;
+ const dropSession = () => {
+ if (!releaseSession) return;
+ releaseSession();
+ releaseSession = null;
+ };
+ const takeSession = () => {
+ if (!audioSession) return;
+ dropSession();
+ releaseSession = acquireAudioSession(audioSession);
+ };
+
+ // The player's own teardown, plus handing back the audio session — so an
+ // output-only player holds its claim only while it is actually sounding.
const doTeardown = () => {
if (onTeardown) onTeardown();
- if (audioSession) releaseAudioSession();
+ dropSession();
};
let playing = false;
@@ -144,28 +158,27 @@ export const createLookaheadTransport = ({
if (playing) return;
const c = ctx();
const token = ++playToken;
- // Declared BEFORE the resume so the context comes up on the right session,
- // and re-declared every play because another view on this document may have
- // released it since (see the audio-session note in audioContext.js).
- if (audioSession) declareAudioSession(audioSession);
+ // Claimed BEFORE the resume so the context comes up on the right session.
+ takeSession();
// Covers iOS Safari's `'interrupted'` state, not just `'suspended'`. A
// rejection here (autoplay policy, or a session iOS won't hand back) leaves
- // play() before any teardown can run, so the session goes back on the way
- // out — unless a newer play() already took it over. The rejection still
+ // play() before any teardown can run, so the claim goes back on the way out
+ // — unless a newer play() already replaced it. The rejection still
// propagates: the caller resets its Play button on it.
await resumeAudioContext(c).catch((err) => {
- if (audioSession && token === playToken) releaseAudioSession();
+ if (token === playToken) dropSession();
throw err;
});
- // Bail WITHOUT releasing the session: whatever bumped the token (stop, pause,
- // or a newer play) owns it now. A stop/pause has already handed it back, and
- // a newer play has re-declared it — releasing here would silence that one.
+ // Bail WITHOUT dropping the claim: whatever bumped the token (stop, pause, or
+ // a newer play) owns it now. A stop/pause already handed it back, and a newer
+ // play's takeSession() already replaced it — dropping here would silence that
+ // one.
if (token !== playToken) return;
- // An empty schedule never sounds, so it hands the session back rather than
- // holding a document-wide declaration for nothing. No await runs between the
- // token check and here, so no newer play() can have taken it over.
+ // An empty schedule never sounds, so it hands the claim back rather than
+ // holding the document's session for nothing. No await runs between the token
+ // check and here, so no newer play() can have taken over in between.
if (doPrepare() === false) { // empty schedule — prepare fired onEnded
- if (audioSession) releaseAudioSession();
+ dropSession();
return;
}
playing = true;
@@ -180,11 +193,11 @@ export const createLookaheadTransport = ({
playToken++; // abort an in-flight play() still awaiting ctx.resume()
if (!playing) {
// The token bump above just cancelled a play() that is still awaiting its
- // resume — and that play() already declared the session. Nothing is
- // sounding and no teardown will run for it, so hand the session back here
- // or a play-then-immediately-pause leaves the document pinned output-only.
+ // resume — and that play() already claimed the session. Nothing is
+ // sounding and no teardown will run for it, so hand the claim back here or
+ // a play-then-immediately-pause leaves the document pinned output-only.
// (`stop()` needs no such branch: it runs the teardown unconditionally.)
- if (audioSession) releaseAudioSession();
+ dropSession();
return;
}
offsetSec = Math.min(Math.max(0, ctx().currentTime - startTime), getTotalSec());
diff --git a/client/src/services/voiceClient.js b/client/src/services/voiceClient.js
index 3e464a7a35..0d24dc76ab 100644
--- a/client/src/services/voiceClient.js
+++ b/client/src/services/voiceClient.js
@@ -8,7 +8,17 @@
import socket from './socket';
import { subscribeVisibility } from '../hooks/useVisibilityEvent.js';
import { sleep } from '../utils/sleep.js';
-import { resumeAudioContext } from '../lib/audioContext.js';
+import { resumeAudioContext, acquireAudioSession } from '../lib/audioContext.js';
+
+// iOS audio-session claims held while a mic stream is open — one per capture
+// mode, because push-to-talk and hands-free listening can overlap. `getUserMedia`
+// is refused under the output-only `playback` session a play-along holds (the
+// VoiceWidget is mounted on EVERY page, so that overlap is routine on the
+// SongBook drum pages); claiming `play-and-record` wins the arbiter and keeps
+// both working — that session ignores the ring/silent switch too, so whatever is
+// playing stays audible. See the audio-session note in lib/audioContext.js.
+let releaseCaptureSession = null;
+let releaseContinuousSession = null;
let stream = null;
let recorder = null;
@@ -461,6 +471,11 @@ export const startCapture = async () => {
socket.emit('voice:interrupt');
stopPlayback();
+ // Claimed BEFORE getUserMedia — an output-only session already in force would
+ // refuse the request outright.
+ releaseCaptureSession?.();
+ releaseCaptureSession = acquireAudioSession('play-and-record');
+
// autoGainControl is critical — without it, quiet mics record near-silent audio
// that whisper transcribes as [BLANK_AUDIO].
stream = await navigator.mediaDevices.getUserMedia({
@@ -469,6 +484,13 @@ export const startCapture = async () => {
noiseSuppression: true,
autoGainControl: true,
},
+ }).catch((err) => {
+ // A denied/failed mic never reaches stopCapture (`recorder` is still null),
+ // so the claim is handed back here or it pins the document record-capable
+ // for the rest of the session.
+ releaseCaptureSession?.();
+ releaseCaptureSession = null;
+ throw err;
});
// Run after permission is granted — `enumerateDevices` only returns
// device labels post-grant, and the headset heuristic relies on labels.
@@ -492,6 +514,8 @@ export const stopCapture = async ({ submit = true } = {}) => {
});
stream?.getTracks().forEach((t) => t.stop());
stream = null;
+ releaseCaptureSession?.();
+ releaseCaptureSession = null;
const blob = new Blob(chunks, { type: rec.mimeType });
chunks = [];
@@ -941,6 +965,12 @@ export const startContinuous = async (callbacks = {}) => {
if (continuousCtx) return;
continuousCallbacks = callbacks;
+ // Claimed BEFORE getUserMedia — an output-only session already in force would
+ // refuse the request outright — and handed back on failure, since a denied mic
+ // never reaches stopContinuous (`continuousCtx` is still null).
+ releaseContinuousSession?.();
+ releaseContinuousSession = acquireAudioSession('play-and-record');
+
// AGC is intentionally OFF here — it boosts silence to maintain a target
// output level, which destroys the energy-difference signal the VAD needs.
continuousStream = await navigator.mediaDevices.getUserMedia({
@@ -949,6 +979,10 @@ export const startContinuous = async (callbacks = {}) => {
noiseSuppression: true,
autoGainControl: false,
},
+ }).catch((err) => {
+ releaseContinuousSession?.();
+ releaseContinuousSession = null;
+ throw err;
});
detectAudioRoute(continuousStream).catch(() => {});
@@ -998,6 +1032,8 @@ export const stopContinuous = async () => {
} catch { /* ignore teardown errors */ }
continuousStream?.getTracks().forEach((t) => t.stop());
await continuousCtx.close().catch(() => {});
+ releaseContinuousSession?.();
+ releaseContinuousSession = null;
continuousCtx = null;
continuousStream = null;
continuousWorkletNode = null;