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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: unmute the SongBook drum play-along on iPhone Safari
[._.]/ Adam Eivy9d01ad2aed4d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 8cc9ccfa7f..5e67c39c11 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -16,6 +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.## Changeddiff --git a/PLAN.md b/PLAN.mdindex f359783b3e..3f9bee54ca 100644--- a/PLAN.md+++ b/PLAN.md@@ -330,3 +330,7 @@ is not reliably announced.### Share one beat-pulse indicator between the Metronome and the drum transport- [ ] `client/src/components/songs/Metronome.jsx:109-129` and `client/src/components/songbook/DrumTransportBar.jsx` (`BeatDots`) draw the same widget twice: a dot per notated beat, the current one lit, count-in dots in `bg-port-warning`, unlit dots `bg-port-border`, with a "Count-in… / bar N" readout beside it. The Metronome's copy is inline JSX, not an exported component, so the drum transport couldn't call it — and the two have already drifted (the drum one uses `bg-port-accent` where the Metronome uses `bg-port-success`, and sizes the lit dot differently). Extract one `<BeatPulse beatsPerBar beat countingIn />` (`client/src/components/ui/`, catalogued + barrelled) and render it from both, picking whichever lit-dot color/size reads better and applying it to each. Deferred from the drum continuous-strip change: extracting from `Metronome.jsx` means editing an unrelated feature's component, which was outside that diff. Surfaced by the /simplify reuse review.++### 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.diff --git a/client/src/components/meatspace/post/MorseTrainer.jsx b/client/src/components/meatspace/post/MorseTrainer.jsxindex 212b15fb11..7b7f27b1a8 100644--- a/client/src/components/meatspace/post/MorseTrainer.jsx+++ b/client/src/components/meatspace/post/MorseTrainer.jsx@@ -5,6 +5,7 @@ import { submitTrainingEntry, getTrainingStats, submitMorseRound, getMorseProgreimport MorseProgressPanel from './MorseProgressPanel';import { streakGlyph } from '../../../lib/streakGlyph.js';import { safeReadJsonStorage, safeWriteStorage } from '../../../lib/safeStorage';+import { resumeAudioContext } from '../../../lib/audioContext.js';import PostCompletionActions from './PostCompletionActions';import { startRetryableSaves } from './completionSave';@@ -225,9 +226,11 @@ function useAudioContext() {// Autoplay policy starts the context suspended until a user gesture — and on// iOS Safari resume() is async, so we MUST await it before scheduling any// oscillator. Firing resume() without awaiting (the old behavior) laid tones- // down against a still-suspended clock: silent on mobile Safari. Mirrors the- // await-resume idiom in metronome.js / scorePlayback.js / songPlayback.js.- if (ctxRef.current.state === 'suspended') await ctxRef.current.resume();+ // down against a still-suspended clock: silent on mobile Safari. The shared+ // helper is the one gate every playback entry point uses (it also covers+ // iOS's `'interrupted'`), and it no-ops on the closed context this component+ // leaves behind on unmount.+ await resumeAudioContext(ctxRef.current);return ctxRef.current;}, []);useEffect(() => () => {diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 079f207926..e7b3cc2222 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()` + `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. 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)` + `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. || `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 suspended-context resume with the teardown-race guard, `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` 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`. || `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.jsindex f0032c0632..764eac5ae3 100644--- a/client/src/lib/audioContext.js+++ b/client/src/lib/audioContext.js@@ -18,9 +18,57 @@let sharedCtx = null;+// --- iOS audio session ------------------------------------------------------+//+// iOS puts a page's Web Audio on the `auto` session, which behaves as *ambient*+// while no media element is playing — and an ambient session is SILENCED by the+// hardware ring/silent switch. A pure-synth page therefore looks like it is+// playing (the clock runs, the playhead scrolls) while the phone makes no sound+// at all, with nothing on screen to explain why. Declaring `playback` is the+// 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.+//+// 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.++const setAudioSessionType = (type) => {+ const session = globalThis.navigator?.audioSession;+ if (!session) return;+ try { session.type = type; } catch { /* older/partial WebKit */ }+};++/** Declare this document's iOS audio session (e.g. `'playback'`). */+export function declareAudioSession(type) {+ setAudioSessionType(type);+}++/**+ * 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.+ */+export function releaseAudioSession() {+ setAudioSessionType('auto');+}+/*** The shared AudioContext. Autoplay policies start it suspended until a user- * gesture — callers resume() it on play, not here.+ * gesture — callers `resumeAudioContext()` it on play, not here.*/export function getAudioContext() {if (!sharedCtx) {@@ -30,6 +78,26 @@ export function getAudioContext() {return sharedCtx;}+/**+ * Bring `c` to `running`, awaited so the caller can schedule against a live+ * clock. Call it from a user gesture (autoplay policy) — every playback entry+ * point should go through this rather than resuming by hand.+ *+ * Gated on `state !== 'running'`, NOT on `state === 'suspended'`: iOS Safari+ * also parks a context in the non-standard `'interrupted'` state — a phone+ * call, Siri, the screen locking, another tab or app taking the audio session.+ * A suspended-only check leaves an interrupted context exactly where it is, so+ * the transport arms its scheduler against a clock that never advances and+ * "plays" in silence until the page is reloaded.+ *+ * `'closed'` is excluded on purpose: resuming a closed context rejects, and a+ * per-mount context that has already been close()d has nothing to bring back.+ */+export async function resumeAudioContext(c) {+ if (!c || c.state === 'running' || c.state === 'closed') return;+ await c.resume?.();+}+// One second of white noise, shared by every synth that needs a noise source// (chiptune drums, the drum-kit snare/hats/cymbals). It lives beside the shared// context for the same reason the context does: each copy is a megabyte ofdiff --git a/client/src/lib/audioContext.test.js b/client/src/lib/audioContext.test.jsnew file mode 100644index 0000000000..73feb3392b--- /dev/null+++ b/client/src/lib/audioContext.test.js@@ -0,0 +1,95 @@+// The shared-context helpers, with an emphasis on the two iOS Safari failures+// they exist for: a context parked in `'interrupted'` and an audio session left+// ambient (silenced by the hardware ring/silent switch).++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { declareAudioSession, releaseAudioSession, resumeAudioContext } from './audioContext.js';++const stubNavigator = (audioSession) => {+ vi.stubGlobal('navigator', audioSession ? { audioSession } : {});+};++// A local stub rather than `createFakeAudio`: that one binds a single starting+// state per module instance (it backs a memoized shared context), and these+// tests need a different state per case.+const fakeCtx = (state) => {+ const c = { state, resumeCalls: 0 };+ c.resume = () => { c.resumeCalls += 1; c.state = 'running'; return Promise.resolve(); };+ return c;+};++describe('audio session', () => {+ beforeEach(() => { vi.unstubAllGlobals(); });+ afterEach(() => { vi.unstubAllGlobals(); });++ it('declares the requested session so the silent switch cannot mute the synth', () => {+ const audioSession = { type: 'auto' };+ stubNavigator(audioSession);+ declareAudioSession('playback');+ expect(audioSession.type).toBe('playback');+ });++ it('releases back to auto, so an output-only declaration cannot follow the user', () => {+ const audioSession = { type: 'playback' };+ stubNavigator(audioSession);+ releaseAudioSession();+ 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();+ });++ 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();+ });+});++describe('resumeAudioContext', () => {+ beforeEach(() => { vi.unstubAllGlobals(); });+ afterEach(() => { vi.unstubAllGlobals(); });++ it('resumes a suspended context (autoplay policy)', async () => {+ const c = fakeCtx('suspended');+ await resumeAudioContext(c);+ expect(c.resumeCalls).toBe(1);+ expect(c.state).toBe('running');+ });++ // The regression this whole helper exists for: iOS Safari parks the context in+ // `'interrupted'` after a call / Siri / the screen locking, and a gate written+ // as `state === 'suspended'` leaves it there — playback then runs silently.+ it("resumes an iOS-Safari 'interrupted' context", async () => {+ const c = fakeCtx('interrupted');+ await resumeAudioContext(c);+ expect(c.resumeCalls).toBe(1);+ expect(c.state).toBe('running');+ });++ it('leaves a running context alone', async () => {+ const c = fakeCtx('running');+ await resumeAudioContext(c);+ expect(c.resumeCalls).toBe(0);+ });++ it('never resumes a closed context (resume() would reject)', async () => {+ const c = fakeCtx('closed');+ await resumeAudioContext(c);+ expect(c.resumeCalls).toBe(0);+ expect(c.state).toBe('closed');+ });++ // The session declaration is document-wide and marks the page output-only, so+ // the shared resume must NOT make it for everyone — a capture page (sing-to-+ // score, the voice client) would lose its microphone. Output-only players opt+ // in through the transport's `audioSession` option instead.+ it('does not declare an audio session — that stays opt-in per player', async () => {+ const audioSession = { type: 'auto' };+ stubNavigator(audioSession);+ await resumeAudioContext(fakeCtx('interrupted'));+ expect(audioSession.type).toBe('auto');+ });+});diff --git a/client/src/lib/audioRecorder.js b/client/src/lib/audioRecorder.jsindex f9520d7b07..2acf5c8948 100644--- a/client/src/lib/audioRecorder.js+++ b/client/src/lib/audioRecorder.js@@ -6,6 +6,8 @@// 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';+const TARGET_SAMPLE_RATE = 16000;// Pick a MediaRecorder mime the browser supports; Safari lands on mp4, others@@ -95,8 +97,10 @@ export function arrayBufferToBase64(buffer) {export function createStreamAnalyser(stream, { fftSize = 2048 } = {}) {const context = new (window.AudioContext || window.webkitAudioContext)();// A context created outside a user gesture (e.g. in a render-driven effect)- // can start `suspended`; resume so frame reads aren't browser-dependent.- if (context.state === 'suspended') context.resume().catch(() => {});+ // can start `suspended` — or, on iOS, `'interrupted'`; resume so frame reads+ // aren't browser-dependent. Fire-and-forget: the analyser is read per frame,+ // so a late resume just means the first frames read zeros.+ resumeAudioContext(context).catch(() => {});const source = context.createMediaStreamSource(stream);const analyser = context.createAnalyser();analyser.fftSize = fftSize;diff --git a/client/src/lib/drumPlayback.js b/client/src/lib/drumPlayback.jsindex fe5afcb18e..1aca19e006 100644--- a/client/src/lib/drumPlayback.js+++ b/client/src/lib/drumPlayback.js@@ -565,6 +565,13 @@ export const createDrumPlayer = (chart, options = {}) => {};const transport = createLookaheadTransport({+ // A play-along is output-only — there is no capture anywhere on the SongBook+ // — so it holds the iOS `playback` session while it sounds. Without it iOS+ // leaves the page on the ambient session and the hardware ring/silent switch+ // mutes the whole kit AND the metronome: the transport counts, the playhead+ // scrolls, and the phone makes no sound. The transport releases it on+ // teardown, so the declaration can't follow the user to a page that records.+ audioSession: 'playback',// A LOOPING player never "ends" on its own, so the transport's end check must// not finish it — unbounded until stop(). But `canLoop()` is the same gate the// scheduler uses: when a selected range holds no music (a rest-only bar) therediff --git a/client/src/lib/drumPlayer.test.js b/client/src/lib/drumPlayer.test.jsindex 0ae70a6f38..f45dd605c9 100644--- a/client/src/lib/drumPlayer.test.js+++ b/client/src/lib/drumPlayer.test.js@@ -1,6 +1,8 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { parseDrumChart } from './drumNotation.js';import { createDrumPlayer } from './drumPlayback.js';+import { parseScore } from './scoreNotation.js';+import { createScorePlayer } from './scorePlayback.js';import { createFakeAudio } from '../test/fakeAudioContext.js';// The AUDIBLE half of drumPlayback.js — buildDrumSchedule's pure math is covered@@ -401,4 +403,72 @@ describe('createDrumPlayer', () => {expect(ended).toHaveBeenCalledTimes(1);expect(player.isPlaying()).toBe(false);});++ // The two iOS Safari failures that made the whole play-along silent on an+ // iPhone while the transport counted and the playhead scrolled.+ describe('on iOS Safari', () => {+ beforeEach(() => { vi.stubGlobal('navigator', { audioSession: { type: 'auto' } }); });++ it("resumes an 'interrupted' context instead of playing against a dead clock", async () => {+ // A call / Siri / the screen locking parks the context here. The old gate+ // read `state === 'suspended'`, walked past this, and armed the scheduler+ // against a clock that never advanced.+ audio.state = 'interrupted';+ const player = createDrumPlayer(CHART, {});+ const playing = player.play(); // parks on ctx.resume()+ expect(audio.resumeCalls).toBe(1);+ audio.flushResume();+ await playing;++ expect(player.isPlaying()).toBe(true);+ drive(1.5);+ expect(audio.oscillators.length).toBeGreaterThan(0);+ player.stop();+ });++ it('holds the playback audio session while sounding so the silent switch cannot mute it', async () => {+ const player = createDrumPlayer(CHART, {});+ await player.play();+ expect(globalThis.navigator.audioSession.type).toBe('playback');+ player.stop();+ });++ // The declaration is document-wide and marks the page output-only, so+ // holding it past playback would follow the user (SPA — no reload) onto the+ // Songs training views and kill their microphone.+ it('hands the session back on stop', async () => {+ const player = createDrumPlayer(CHART, {});+ await player.play();+ 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();+ drive(3); // CHART is 2s — runs to its natural end+ expect(player.isPlaying()).toBe(false);+ expect(globalThis.navigator.audioSession.type).toBe('auto');+ });+ });+});++// Players hosted on pages that ALSO record must not declare an output-only+// session — the mic would go dead. Only a player that opts in via the+// transport's `audioSession` option touches it.+describe('players that do not opt into an audio session', () => {+ beforeEach(() => {+ audio.reset();+ vi.stubGlobal('AudioContext', FakeAudioContext);+ vi.stubGlobal('navigator', { audioSession: { type: 'auto' } });+ vi.useFakeTimers();+ });+ afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); });++ it('leaves the document audio session alone', async () => {+ const player = createScorePlayer(parseScore('tempo: 120\n| C4q D4q |'), { bpm: 120 });+ await player.play();+ expect(globalThis.navigator.audioSession.type).toBe('auto');+ player.stop();+ });});diff --git a/client/src/lib/lookaheadTransport.js b/client/src/lib/lookaheadTransport.jsindex f15c150193..b032e351d0 100644--- a/client/src/lib/lookaheadTransport.js+++ b/client/src/lib/lookaheadTransport.js@@ -12,7 +12,9 @@// 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 } from './audioContext.js';+import {+ getAudioContext as ctx, resumeAudioContext, declareAudioSession, releaseAudioSession,+} 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@@ -55,6 +57,12 @@ const { LEAD, LOOKAHEAD_MS } = SYNTH_TIMING;* @param {() => void} [hooks.onTeardown] — extra teardown after the live nodes* are stopped on pause/stop/finish (e.g. drop the master-bus ref). NOT called* on seek, which reuses the same bus to keep scheduling.+ * @param {string} [hooks.audioSession] — the iOS audio session type to hold+ * 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.* @returns {{ play, pause, stop, seek, position, isPlaying, track }}*/export const createLookaheadTransport = ({@@ -65,13 +73,20 @@ export const createLookaheadTransport = ({onStop,onEnded,onTeardown,+ audioSession,}) => {const noop = () => {};const doPrepare = prepare || (() => true);const doSeekCursors = seekCursors || noop;const doStop = onStop || noop;const doEnded = onEnded || noop;- const doTeardown = onTeardown || 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.+ const doTeardown = () => {+ if (onTeardown) onTeardown();+ if (audioSession) releaseAudioSession();+ };let playing = false;let interval = null;@@ -129,9 +144,20 @@ export const createLookaheadTransport = ({if (playing) return;const c = ctx();const token = ++playToken;- if (c.state === 'suspended' && c.resume) await c.resume();- if (token !== playToken) return; // a stop/pause landed during the resume await- if (doPrepare() === false) return; // empty schedule — prepare fired onEnded+ // 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);+ // Covers iOS Safari's `'interrupted'` state, not just `'suspended'`.+ await resumeAudioContext(c);+ // A stop/pause landing during the resume await already ran the teardown, so+ // it has handed the session back; an empty schedule never sounds, so it hands+ // it back here rather than holding a document-wide declaration for nothing.+ if (token !== playToken) return;+ if (doPrepare() === false) { // empty schedule — prepare fired onEnded+ if (audioSession) releaseAudioSession();+ return;+ }playing = true;startTime = c.currentTime + LEAD - offsetSec;doSeekCursors(offsetSec, offsetSec > 0, startTime, track);diff --git a/client/src/lib/metronome.js b/client/src/lib/metronome.jsindex 28c29ce5a7..ec968354d4 100644--- a/client/src/lib/metronome.js+++ b/client/src/lib/metronome.js@@ -15,7 +15,7 @@// same grid. Pure-ish: no React; the <Metronome> component wraps it for UI.import { parseScore } from './scoreNotation.js';-import { getAudioContext as audioContext } from './audioContext.js';+import { getAudioContext as audioContext, resumeAudioContext } from './audioContext.js';// BPM band — mirrors the server `tempo` validation (services/rounds.js// TEMPO_MIN / TEMPO_MAX, also enforced by the Zod schema in routes/rounds.js).@@ -165,8 +165,9 @@ export function createMetronome({const start = async () => {if (running) return;const c = audioContext();- // Autoplay policy starts the context suspended until a user gesture.- if (c.state === 'suspended') await c.resume();+ // Autoplay policy starts the context suspended until a user gesture, and on+ // iOS it can also come back `'interrupted'` — see lib/audioContext.js.+ await resumeAudioContext(c);running = true;tickIndex = 0;nextNoteTime = c.currentTime + START_LEAD_S;diff --git a/client/src/lib/scorePlayback.race.test.js b/client/src/lib/scorePlayback.race.test.jsindex 87b9b71460..458041246e 100644--- a/client/src/lib/scorePlayback.race.test.js+++ b/client/src/lib/scorePlayback.race.test.js@@ -8,12 +8,12 @@ import { parseScore } from './scoreNotation.js';import { createScorePlayer, createMultiScorePlayer } from './scorePlayback.js';import { createFakeAudio } from '../test/fakeAudioContext.js';-// The shared fake in suspended mode starts the context suspended and only-// resolves resume() when we call audio.flushResume() — so a test can interleave-// a stop()/pause() between play()'s `await ctx.resume()` and its continuation,-// reproducing the teardown-during-await race the playToken guard fixes. One-// pair for the whole file (lib/audioContext.js caches the context).-const { FakeAudioContext, audio } = createFakeAudio({ suspended: true });+// The shared fake started suspended only resolves resume() when we call+// audio.flushResume() — so a test can interleave a stop()/pause() between+// play()'s `await ctx.resume()` and its continuation, reproducing the+// teardown-during-await race the playToken guard fixes. One pair for the whole+// file (lib/audioContext.js caches the context).+const { FakeAudioContext, audio } = createFakeAudio({ state: 'suspended' });describe('resume-window teardown race', () => {beforeEach(() => {diff --git a/client/src/lib/songPlayback.js b/client/src/lib/songPlayback.jsindex 8947d47e71..414aa045f9 100644--- a/client/src/lib/songPlayback.js+++ b/client/src/lib/songPlayback.js@@ -12,7 +12,7 @@// The app-wide shared AudioContext (see audioContext.js) — reusing one keeps// every layer on the same clock. Resumed on demand because autoplay policies// start it suspended until a user gesture.-import { getAudioContext as ctx } from './audioContext.js';+import { getAudioContext as ctx, resumeAudioContext } from './audioContext.js';// Decode one recording URL into an AudioBuffer. Cached per-URL on the returned// mixer (not globally) so a re-open re-fetches at most once per session.@@ -62,7 +62,7 @@ export function createLayeredPlayer(takes = []) {const play = async () => {stop();const c = ctx();- if (c.state === 'suspended') await c.resume();+ await resumeAudioContext(c);// Decode any not-yet-decoded buffers (parallel). Muted layers are skipped —// no point paying decode cost for something we won't hear this round.diff --git a/client/src/pages/Security.jsx b/client/src/pages/Security.jsxindex e36399d32f..f0268b96b0 100644--- a/client/src/pages/Security.jsx+++ b/client/src/pages/Security.jsx@@ -4,6 +4,7 @@ import api from '../services/api';import Banner from '../components/ui/Banner';import { FormField } from '../components/ui/FormField';import { safeReadStorage, safeReadJsonStorage, safeWriteStorage, safeRemoveStorage } from '../lib/safeStorage';+import { resumeAudioContext } from '../lib/audioContext.js';const MEDIA_CONSTRAINTS_KEY = 'portos-media-constraints';@@ -76,12 +77,11 @@ export default function Security() {const audioContext = new (window.AudioContext || window.webkitAudioContext)();- // Resume AudioContext if suspended (browser autoplay policy)- if (audioContext.state === 'suspended') {- await audioContext.resume().catch(() => {- setAudioNeedsInteraction(true);- });- }+ // Bring the context up if it isn't running (browser autoplay policy, or+ // iOS's `'interrupted'` after a call/lock) — see lib/audioContext.js.+ await resumeAudioContext(audioContext).catch(() => {+ setAudioNeedsInteraction(true);+ });const analyser = audioContext.createAnalyser();const source = audioContext.createMediaElementSource(audioElement);@@ -115,10 +115,9 @@ export default function Security() {// Enable audio with user interaction (for mobile browsers)const enableAudio = useCallback(async () => {if (audioRef.current && audioContextRef.current) {- // Resume AudioContext- if (audioContextRef.current.state === 'suspended') {- await audioContextRef.current.resume();- }+ // Resume AudioContext — the whole point of this button, so it has to cover+ // every non-running state, not just `'suspended'`.+ await resumeAudioContext(audioContextRef.current);// Play audio elementawait audioRef.current.play();diff --git a/client/src/services/voiceClient.js b/client/src/services/voiceClient.jsindex 839aa22d80..3e464a7a35 100644--- a/client/src/services/voiceClient.js+++ b/client/src/services/voiceClient.js@@ -8,6 +8,7 @@import socket from './socket';import { subscribeVisibility } from '../hooks/useVisibilityEvent.js';import { sleep } from '../utils/sleep.js';+import { resumeAudioContext } from '../lib/audioContext.js';let stream = null;let recorder = null;@@ -42,7 +43,9 @@ const ensureCtx = () => {const Ctor = window.AudioContext || window.webkitAudioContext;audioCtx = new Ctor();}- if (audioCtx.state === 'suspended') audioCtx.resume();+ // Fire-and-forget so ensureCtx stays sync — TTS playback schedules against the+ // context a beat later. Covers iOS's `'interrupted'`, not just `'suspended'`.+ resumeAudioContext(audioCtx).catch(() => {});return audioCtx;};@@ -951,7 +954,7 @@ export const startContinuous = async (callbacks = {}) => {const Ctor = window.AudioContext || window.webkitAudioContext;continuousCtx = new Ctor();- if (continuousCtx.state === 'suspended') await continuousCtx.resume();+ await resumeAudioContext(continuousCtx);// Inline worklet module so we don't need a separate file in the buildconst blobUrl = URL.createObjectURL(new Blob([WORKLET_SOURCE], { type: 'application/javascript' }));diff --git a/client/src/test/fakeAudioContext.js b/client/src/test/fakeAudioContext.jsindex 8b4c56dddc..4af4709f92 100644--- a/client/src/test/fakeAudioContext.js+++ b/client/src/test/fakeAudioContext.js@@ -7,18 +7,27 @@// scorePlayback.race.test.js use — new audio tests should import this instead// of copying another one.//-// Pass { suspended: true } to model a context that starts suspended and only-// resumes when the test calls `audio.flushResume()` — this reproduces the-// teardown-during-await race the players' playToken guard fixes, letting a test+// Pass { state } for a context that doesn't start running: `'suspended'` (the+// autoplay policy) or iOS Safari's non-standard `'interrupted'` (a call / Siri /+// the screen locking parks it there, and a resume gate written as+// `state === 'suspended'` walks straight past it). Either way resume() parks+// until the test calls `audio.flushResume()`, which reproduces the+// teardown-during-await race the players' playToken guard fixes — a test can// interleave a stop()/pause() between play()'s `await ctx.resume()` and its-// continuation.+// continuation. `audio.state` is live (flipped to `'running'` by flushResume, so+// the fake models the real state machine) and `audio.resumeCalls` counts the+// resume() attempts.-export const createFakeAudio = ({ suspended = false } = {}) => {- // Pending resolver for a suspended context's in-flight resume() (null until+export const createFakeAudio = ({ state: initialState = 'running' } = {}) => {+ // Pending resolver for a non-running context's in-flight resume() (null until// a resume() is awaiting, cleared once flushed).let resolveResume = null;const audio = {now: 0,+ // Live context state — flips to 'running' once a pending resume resolves,+ // so a test can assert the transport actually brought the clock up.+ state: initialState,+ resumeCalls: 0,oscillators: [],gains: [],// Bandpassed noise voices (createBufferSource + createBiquadFilter) — the@@ -32,14 +41,23 @@ export const createFakeAudio = ({ suspended = false } = {}) => {shapers: [],reset() {this.now = 0;+ this.state = initialState;+ this.resumeCalls = 0;this.oscillators.length = 0;this.gains.length = 0;this.filters.length = 0;this.shapers.length = 0;resolveResume = null;},- // Resolve a suspended context's pending resume() so play()'s await continues.- flushResume() { const r = resolveResume; resolveResume = null; if (r) r(); },+ // Resolve a pending resume() so play()'s await continues, bringing the+ // context up exactly as a real one does.+ flushResume() {+ const r = resolveResume;+ resolveResume = null;+ if (!r) return;+ this.state = 'running';+ r();+ },};// Every node records what it was connected TO, so a test can assert ROUTING// ("the kick's oscillator feeds a drive shaper") rather than inferring it from@@ -62,10 +80,12 @@ export const createFakeAudio = ({ suspended = false } = {}) => {};function FakeAudioContext() {return {- state: suspended ? 'suspended' : 'running',- resume: suspended- ? () => new Promise((r) => { resolveResume = r; })- : () => Promise.resolve(),+ get state() { return audio.state; },+ resume: () => {+ audio.resumeCalls += 1;+ if (audio.state === 'running') return Promise.resolve();+ return new Promise((r) => { resolveResume = r; });+ },get currentTime() { return audio.now; },destination: { id: 'destination' },createOscillator() {