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: hold the iOS playback audio session on the remaining output-only players (#4131)
[._.]/ Adam Eivy25943476a049
diff --git a/.changelog/next/fixed-issue-4131.md b/.changelog/next/fixed-issue-4131.mdnew file mode 100644index 0000000000..eeaf52197d--- /dev/null+++ b/.changelog/next/fixed-issue-4131.md@@ -0,0 +1 @@+- iOS: the chiptune preview, the Morse trainer, and the Security audio monitor now hold the playback audio session while they sound, so the iPhone ring/silent switch can't silence them; the sing-to-score and sing-to-verify capture hooks claim play-and-record around their own microphonediff --git a/client/src/components/meatspace/post/MorseTrainer.jsx b/client/src/components/meatspace/post/MorseTrainer.jsxindex 7b7f27b1a8..0908afa836 100644--- a/client/src/components/meatspace/post/MorseTrainer.jsx+++ b/client/src/components/meatspace/post/MorseTrainer.jsx@@ -1,6 +1,7 @@import { useState, useEffect, useRef, useCallback } from 'react';import { ArrowLeft, Radio, Headphones, Hand, EyeOff, CheckCircle, XCircle, Play, RefreshCw, Volume2, GitBranch, List as ListIcon, Ruler, Eraser } from 'lucide-react';import useDrawerTab from '../../../hooks/useDrawerTab';+import useAudioSessionClaim from '../../../hooks/useAudioSessionClaim.js';import { submitTrainingEntry, getTrainingStats, submitMorseRound, getMorseProgress, updateMorseLevel } from '../../../services/api';import MorseProgressPanel from './MorseProgressPanel';import { streakGlyph } from '../../../lib/streakGlyph.js';@@ -218,6 +219,16 @@ function pickSendPrompt() {function useAudioContext() {const ctxRef = useRef(null);+ // MorseTrainer sounds through a PER-MOUNT AudioContext (it close()s it on+ // unmount, which would kill a shared one for everyone else), so it can't+ // inherit the shared lookahead transport's `audioSession` option — it claims+ // the iOS `playback` session by hand instead. Every tone this component makes+ // is output-only: the copy drill's prompt and the send-mode sidetone, which+ // are never mounted at the same time, so one claim slot is enough. Callers+ // `claim()` before the resume await (the context should come up on the right+ // session) and `release()` when they stop sounding; unmount releases whatever+ // is still held. See the audio-session note in lib/audioContext.js.+ const { claim: claimSession, release: releaseSession } = useAudioSessionClaim('playback');const ensureCtx = useCallback(async () => {if (!ctxRef.current) {const Ctor = window.AudioContext || window.webkitAudioContext;@@ -237,14 +248,14 @@ function useAudioContext() {if (ctxRef.current) ctxRef.current.close();ctxRef.current = null;}, []);- return ensureCtx;+ return { ensureCtx, claimSession, releaseSession };}// `enabled` defaults to false so callers must explicitly opt in to attaching// the global spacebar listener — it's only safe in Send mode. In other modes// it would compete with text input and suppress the voice-widget push-to-talk// hotkey via stopImmediatePropagation.-function useKeyingDecoder({ unitMs, hz, ensureCtx, enabled = false }) {+function useKeyingDecoder({ unitMs, hz, ensureCtx, claimSession, releaseSession, enabled = false }) {const oscRef = useRef(null);const gainRef = useRef(null);const pressStartRef = useRef(0);@@ -271,13 +282,21 @@ function useKeyingDecoder({ unitMs, hz, ensureCtx, enabled = false }) {const startTone = useCallback(async () => {const gen = ++toneGenRef.current;- const ctx = await ensureCtx();+ // Claimed BEFORE the resume await so the context comes up on the `playback`+ // session — the sidetone is output-only and the iPhone's ring/silent switch+ // would otherwise mute the whole send drill. A rejected resume never+ // reaches stopTone, so it hands the claim back on its way out.+ claimSession();+ const ctx = await ensureCtx().catch((err) => { releaseSession(); throw err; });// A fast tap can release (endPress → stopTone), or a newer press can start,// before the first-press-only resume await settles. Bail if the key is no// longer held (`!pressingRef.current`) OR a newer press superseded this one// (`gen !== toneGenRef.current`) — a bare boolean can't distinguish the two,// so two overlapping starts would both create an oscillator and orphan the- // first, leaving it droning with no matching stop.+ // first, leaving it droning with no matching stop. Either bail leaves the+ // session claim alone: a released key already ran stopTone (which releases),+ // and a newer press's claimSession() now owns the slot — releasing here+ // would silence the tone that superseded this one.if (!pressingRef.current || gen !== toneGenRef.current) return;const osc = ctx.createOscillator();const gain = ctx.createGain();@@ -291,9 +310,14 @@ function useKeyingDecoder({ unitMs, hz, ensureCtx, enabled = false }) {gain.gain.linearRampToValueAtTime(TONE_GAIN, now + RAMP_SEC);oscRef.current = osc;gainRef.current = gain;- }, [ensureCtx, hz]);+ }, [ensureCtx, hz, claimSession, releaseSession]);const stopTone = useCallback(() => {+ // Released FIRST, before the early return: a tap short enough to end before+ // startTone's resume await settles has a claim but no oscillator yet, and+ // that claim would otherwise be stranded until unmount. Presses are+ // serialized by `pressingRef`, so this can only ever be releasing our own.+ releaseSession();const osc = oscRef.current;const gain = gainRef.current;if (!osc || !gain) return;@@ -308,7 +332,7 @@ function useKeyingDecoder({ unitMs, hz, ensureCtx, enabled = false }) {osc.onended = () => { osc.disconnect(); gain.disconnect(); };oscRef.current = null;gainRef.current = null;- }, []);+ }, [releaseSession]);const flushLetter = useCallback(() => {const buf = patternRef.current;@@ -424,9 +448,11 @@ export default function MorseTrainer({ mode = null, onSelectMode, onExitMode, on// Bumped after each round submit so the progress panel refetches its trends /// confusion matrix without a manual reload.const [progressRefresh, setProgressRefresh] = useState(0);- const ensureCtx = useAudioContext();+ const { ensureCtx, claimSession, releaseSession } = useAudioContext();const unitMs = 1.2 / prefs.wpm * 1000;- const keying = useKeyingDecoder({ unitMs, hz: prefs.hz, ensureCtx, enabled: mode === 'send' });+ const keying = useKeyingDecoder({+ unitMs, hz: prefs.hz, ensureCtx, claimSession, releaseSession, enabled: mode === 'send',+ });// Head Copy reuses CopyDrill's whole pipeline (Koch pool, round scoring,// level unlock) minus the on-screen morse hints and the reference cheat// sheet — the only meaningful difference the issue asks for.@@ -535,10 +561,10 @@ export default function MorseTrainer({ mode = null, onSelectMode, onExitMode, on<SettingsPanel prefs={prefs} updatePrefs={updatePrefs} onResetProgress={resetProgress} trainingStats={trainingStats} />{!mode && <ModeGrid onPick={onSelectMode} />}{mode === 'copy' && (- <CopyDrill prefs={prefs} updatePrefs={updatePrefs} ensureCtx={ensureCtx} onExit={onExitMode} onContinue={onContinue} onSessionComplete={logTraining} onRoundSubmit={submitRound} />+ <CopyDrill prefs={prefs} updatePrefs={updatePrefs} ensureCtx={ensureCtx} claimSession={claimSession} releaseSession={releaseSession} onExit={onExitMode} onContinue={onContinue} onSessionComplete={logTraining} onRoundSubmit={submitRound} />)}{mode === 'head-copy' && (- <CopyDrill prefs={prefs} updatePrefs={updatePrefs} ensureCtx={ensureCtx} onExit={onExitMode} onContinue={onContinue} onSessionComplete={logTraining} onRoundSubmit={submitRound} headCopy />+ <CopyDrill prefs={prefs} updatePrefs={updatePrefs} ensureCtx={ensureCtx} claimSession={claimSession} releaseSession={releaseSession} onExit={onExitMode} onContinue={onContinue} onSessionComplete={logTraining} onRoundSubmit={submitRound} headCopy />)}{mode === 'send' && (<SendDrill keying={keying} onExit={onExitMode} onContinue={onContinue} onSessionComplete={logTraining} onRoundSubmit={submitRound} />@@ -876,7 +902,7 @@ export function resultsToItems(results) {return items;}-function CopyDrill({ prefs, updatePrefs, ensureCtx, onExit, onContinue, onSessionComplete, onRoundSubmit, headCopy = false }) {+function CopyDrill({ prefs, updatePrefs, ensureCtx, claimSession, releaseSession, onExit, onContinue, onSessionComplete, onRoundSubmit, headCopy = false }) {const [prompt, setPrompt] = useState('');const [input, setInput] = useState('');const [results, setResults] = useState([]);@@ -910,7 +936,13 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, onExit, onContinue, onSessioasync function playPrompt(isNew) {if (playingRef.current) return;playingRef.current = true;- const ctx = await ensureCtx();+ // Claimed BEFORE the resume await so the context comes up on the iOS+ // `playback` session — this drill is pure synth with no media element, so+ // on the default `auto` session the ring/silent switch mutes the prompt+ // while the UI still says "playing...". A rejected resume never reaches the+ // release below, so it hands the claim back on its way out.+ claimSession();+ const ctx = await ensureCtx().catch((err) => { releaseSession(); throw err; });const text = isNew ? pickKochPrompt(prefs.kochLevel) : prompt;if (isNew) {setPrompt(text);@@ -919,6 +951,7 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, onExit, onContinue, onSessio}setPlaying(true);await playMorse(ctx, text, prefs);+ releaseSession();setPlaying(false);playingRef.current = false;questionStartRef.current = Date.now();diff --git a/client/src/components/meatspace/post/MorseTrainer.test.jsx b/client/src/components/meatspace/post/MorseTrainer.test.jsxindex c23366ad03..14a102e95d 100644--- a/client/src/components/meatspace/post/MorseTrainer.test.jsx+++ b/client/src/components/meatspace/post/MorseTrainer.test.jsx@@ -36,7 +36,11 @@ class MockOscillator {constructor(context = { currentTime: 0 }) { this.onended = null; this.frequency = { value: 0 }; this.context = context; }connect() { return this; }start() {}- stop() { if (this.onended) setTimeout(() => this.onended(), 0); }+ // Scheduled unconditionally, then null-checked when it fires: playMorse calls+ // stop() BEFORE it assigns onended (the handler lives in the Promise executor+ // it returns), so an `if (this.onended)` gate here never fires and its promise+ // never resolves — which silently hid every post-playback assertion.+ stop() { setTimeout(() => this.onended?.(), 0); }disconnect() {}}class MockGainNode {@@ -465,3 +469,64 @@ describe('isNodeOnPath (live keying highlight gate)', () => {expect(isNodeOnPath(t, '..')).toEqual({ matched: false, onPath: false });});});++// The trainer sounds through its OWN per-mount AudioContext (it close()s it on+// unmount), so it can't inherit the shared lookahead transport's `audioSession`+// option — it claims the iOS `playback` session by hand. Without the claim the+// iPhone's ring/silent switch mutes a pure-synth drill that still says+// "playing..." on screen. jsdom has no `navigator.audioSession`, so these stub+// the shape Safari 16.4+ exposes and read the declared type back off it (#4131).+describe('MorseTrainer iOS audio session', () => {+ beforeEach(() => {+ window.AudioContext = MockAudioContext;+ navigator.audioSession = { type: 'auto' };+ });+ afterEach(() => {+ delete window.AudioContext;+ delete navigator.audioSession;+ });++ it('claims playback while a copy prompt sounds and hands it back after', async () => {+ await renderMorse({ mode: 'copy', onSelectMode: vi.fn(), onExitMode: vi.fn() });+ fireEvent.click(await screen.findByRole('button', { name: /Start Round/i }));+ // The claim is taken synchronously, before the resume await, so the context+ // comes up on the right session.+ expect(navigator.audioSession.type).toBe('playback');++ // playMorse resolves off the oscillator's `onended`, so the release lands a+ // tick after the prompt stops sounding.+ await waitFor(() => expect(navigator.audioSession.type).toBe('auto'));+ });++ it('claims playback while the send sidetone is keyed and hands it back on release', async () => {+ await renderMorse({ mode: 'send', onSelectMode: vi.fn(), onExitMode: vi.fn() });+ await act(async () => { fireEvent.keyDown(window, { code: 'Space' }); });+ expect(navigator.audioSession.type).toBe('playback');++ await act(async () => { fireEvent.keyUp(window, { code: 'Space' }); });+ expect(navigator.audioSession.type).toBe('auto');+ });++ // A tap short enough to end before the resume await settles has a claim but no+ // oscillator yet — stopTone releases before its no-oscillator early return, or+ // the document stays pinned output-only with no release left to call.+ it('releases a claim taken by a press that ended before the audio unlocked', async () => {+ // Resume parks until flushed, reproducing the iOS unlock window.+ let unlock;+ class SlowAudioContext extends MockAudioContext {+ constructor() { super(); this.state = 'suspended'; }+ resume() { return new Promise((r) => { unlock = () => { this.state = 'running'; r(); }; }); }+ }+ window.AudioContext = SlowAudioContext;+ await renderMorse({ mode: 'send', onSelectMode: vi.fn(), onExitMode: vi.fn() });++ fireEvent.keyDown(window, { code: 'Space' });+ expect(navigator.audioSession.type).toBe('playback');+ fireEvent.keyUp(window, { code: 'Space' });+ expect(navigator.audioSession.type).toBe('auto');++ await act(async () => { unlock(); });+ // The superseded startTone must not re-declare on its way out.+ expect(navigator.audioSession.type).toBe('auto');+ });+});diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex f51131730d..e9370e588b 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -124,6 +124,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useValidTab` | Resolve the active tab from the `:tab` URL param against a TABS list, falling back to a default on invalid/missing. | Any tabbed page whose tab lives in the URL — don't re-roll the `new Set(TABS.map(...))` guard. || `useAsyncAction` | `running` state + toast-on-error. | Buttons that await an async action. || `useAutoscroll` | rAF autoscroll for a scrollable container: advances `scrollTop` by `pxPerSec`, auto-stops at the bottom, pauses on user wheel/touchmove, live speed changes via ref. `fitToDuration(sec)` solves the speed for a target run time from the measured scroll travel (returns the applied px/s, or `null` when there is nothing to scroll). Returns `{ playing, toggle, stop, pxPerSec, setPxPerSec, fitToDuration }`. | SongBook play view; any teleprompter-style surface. |+| `useAudioSessionClaim` | `useAudioSessionClaim(type)` → `{ claim, release }` — one arbitrated `acquireAudioSession(type)` slot with a React lifecycle: `claim()` drops this instance's previous claim before taking a fresh one, `release()` is idempotent, and unmount releases whatever is still held. | A surface owning its OWN `AudioContext` (MorseTrainer, the Security monitor) or `getUserMedia` stream (`useSingToScore`/`useSingToVerify`) needs the iOS session. An output-only player on the shared transport passes `audioSession: 'playback'` to `createLookaheadTransport` instead — don't hand-roll either. || `useWakeLock` | Holds a screen wake lock (`navigator.wakeLock`) while `active` is true; releases on unmount/inactive, re-acquires on visibilitychange; no-op where unsupported. | Hands-free surfaces that must keep the screen on (SongBook autoscroll). |## Storage & persistencediff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 51e21981c2..5a622670be 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -9,6 +9,7 @@// === Default-exporting hooks (re-exported as named) ===export { default as useAnchorReveal } from './useAnchorReveal.js';+export { default as useAudioSessionClaim } from './useAudioSessionClaim.js';export { default as useAutoscroll } from './useAutoscroll.js';export { default as useCityAudio } from './useCityAudio.js';export { default as useClonedGltf } from './useClonedGltf.jsx';diff --git a/client/src/hooks/useAudioSessionClaim.js b/client/src/hooks/useAudioSessionClaim.jsnew file mode 100644index 0000000000..a4867f44ef--- /dev/null+++ b/client/src/hooks/useAudioSessionClaim.js@@ -0,0 +1,50 @@+// useAudioSessionClaim — hold the document's iOS audio session for a surface+// that owns its OWN AudioContext or `getUserMedia` stream, rather than driving+// the shared lookahead transport (output-only players get the same behavior for+// free by passing `audioSession: 'playback'` to `createLookaheadTransport`).+//+// What the session is and why it is arbitrated rather than assigned is in the+// audio-session note in `lib/audioContext.js`. This hook is just the React+// lifecycle around one `acquireAudioSession` claim:+//+// - ONE claim slot per hook instance. `claim()` hands back whatever this+// instance was already holding before taking a fresh one, so a re-entered+// play/capture can't strand a holder in the arbiter and pin the document.+// - `release()` is idempotent, so every teardown path can call it without+// coordinating (the same contract `acquireAudioSession`'s release has).+// - The claim is released on UNMOUNT too. That is the backstop for a lifecycle+// that ends without its normal teardown — a per-mount AudioContext close()d+// out from under an in-flight play never fires the `onended` that would+// otherwise release, and a stranded holder pins the page output-only (or+// record-capable) for the rest of the SPA session.+//+// Both callbacks are referentially stable, so they are safe in an effect dep+// list and in a `useCallback` that must not re-create per render.++import { useCallback, useEffect, useRef } from 'react';+import { acquireAudioSession } from '../lib/audioContext.js';++/**+ * @param {'playback'|'play-and-record'} type — `'playback'` for an output-only+ * surface (the iPhone ring/silent switch can't mute it, but it REFUSES+ * capture); `'play-and-record'` for the window a mic stream is open.+ * @returns {{ claim: () => void, release: () => void }}+ */+export default function useAudioSessionClaim(type) {+ const releaseRef = useRef(null);++ const release = useCallback(() => {+ releaseRef.current?.();+ releaseRef.current = null;+ }, []);++ const claim = useCallback(() => {+ release();+ releaseRef.current = acquireAudioSession(type);+ }, [release, type]);++ // `release` is stable, so this cleanup runs exactly once, on unmount.+ useEffect(() => release, [release]);++ return { claim, release };+}diff --git a/client/src/hooks/useAudioSessionClaim.test.js b/client/src/hooks/useAudioSessionClaim.test.jsnew file mode 100644index 0000000000..285477668c--- /dev/null+++ b/client/src/hooks/useAudioSessionClaim.test.js@@ -0,0 +1,74 @@+// The React lifecycle around one arbitrated iOS audio-session claim. jsdom has+// no `navigator.audioSession`, so the tests stub the shape Safari 16.4+ exposes+// and read the declared type back off it — the same seam the drum/score player+// suites use.+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { renderHook, act } from '@testing-library/react';+import { acquireAudioSession } from '../lib/audioContext.js';+import useAudioSessionClaim from './useAudioSessionClaim.js';++const sessionType = () => globalThis.navigator.audioSession.type;++describe('useAudioSessionClaim', () => {+ beforeEach(() => { vi.stubGlobal('navigator', { audioSession: { type: 'auto' } }); });+ afterEach(() => { vi.unstubAllGlobals(); });++ it('declares the type on claim and goes back to auto on release', () => {+ const { result } = renderHook(() => useAudioSessionClaim('playback'));+ expect(sessionType()).toBe('auto');++ act(() => { result.current.claim(); });+ expect(sessionType()).toBe('playback');++ act(() => { result.current.release(); });+ expect(sessionType()).toBe('auto');+ });++ it('is idempotent on release, so every teardown path can call it', () => {+ const { result } = renderHook(() => useAudioSessionClaim('play-and-record'));+ act(() => { result.current.claim(); });+ act(() => { result.current.release(); result.current.release(); });+ expect(sessionType()).toBe('auto');+ });++ // One slot per instance: a re-entered play/capture that claims again must not+ // strand the previous holder in the arbiter — a stranded holder pins the+ // document for the rest of the SPA session, with no release left to call.+ it('drops its previous claim when it claims again', () => {+ const { result } = renderHook(() => useAudioSessionClaim('playback'));+ act(() => { result.current.claim(); result.current.claim(); });+ act(() => { result.current.release(); });+ expect(sessionType()).toBe('auto');+ });++ // The backstop for a lifecycle that ends without its normal teardown — a+ // per-mount AudioContext close()d out from under an in-flight play never+ // fires the `onended` that would otherwise release.+ it('releases a still-held claim on unmount', () => {+ const { result, unmount } = renderHook(() => useAudioSessionClaim('playback'));+ act(() => { result.current.claim(); });+ expect(sessionType()).toBe('playback');+ unmount();+ expect(sessionType()).toBe('auto');+ });++ // Two instances hold independently — the arbiter tracks holders, not a count+ // per type — and capture outranks playback while both are live.+ it('yields to a play-and-record holder and takes playback back on its release', () => {+ const { result } = renderHook(() => useAudioSessionClaim('playback'));+ act(() => { result.current.claim(); });+ const releaseMic = acquireAudioSession('play-and-record');+ expect(sessionType()).toBe('play-and-record');+ releaseMic();+ expect(sessionType()).toBe('playback');+ act(() => { result.current.release(); });+ expect(sessionType()).toBe('auto');+ });++ it('is a no-op where navigator.audioSession does not exist', () => {+ vi.stubGlobal('navigator', {});+ const { result, unmount } = renderHook(() => useAudioSessionClaim('playback'));+ act(() => { result.current.claim(); result.current.release(); });+ expect(() => unmount()).not.toThrow();+ });+});diff --git a/client/src/hooks/useSingToScore.js b/client/src/hooks/useSingToScore.jsindex 4b62206ba6..b863c6675f 100644--- a/client/src/hooks/useSingToScore.js+++ b/client/src/hooks/useSingToScore.js@@ -17,6 +17,7 @@ import { createStreamAnalyser } from '../lib/audioRecorder.js';import { createPitchTracker } from '../lib/pitchDetect.js';import { createMetronome, clampBpm, timeSignatureFromScore, DEFAULT_BPM } from '../lib/metronome.js';import { transcribePitchTrack } from '../lib/singToScore.js';+import useAudioSessionClaim from './useAudioSessionClaim.js';import useMounted from './useMounted.js';// Phases the UI renders distinct states for.@@ -61,6 +62,13 @@ export default function useSingToScore({ tempo, score = '', musicKey = 'C' } = {const captureStartRef = useRef(0); // performance.now() at first music beatconst capturingRef = useRef(false); // gate frames until the count-in completes+ // Held for exactly the window our own mic stream is open, symmetric with+ // `voiceClient` / `audioRecorder`. Sing-to-score is safe on `auto` only+ // because no `playback` claimant happens to share its route today — an+ // accident of routing, not an invariant, and `playback` REFUSES capture. See+ // the audio-session note in lib/audioContext.js.+ const { claim: claimSession, release: releaseSession } = useAudioSessionClaim('play-and-record');+const bpm = clampBpm(tempo) ?? DEFAULT_BPM;const timeSig = timeSignatureFromScore(score);@@ -70,8 +78,9 @@ export default function useSingToScore({ tempo, score = '', musicKey = 'C' } = {if (trackerRef.current) { trackerRef.current.stop(); trackerRef.current = null; }if (analyserRef.current) { analyserRef.current.close(); analyserRef.current = null; }if (streamRef.current) { streamRef.current.getTracks().forEach((t) => t.stop()); streamRef.current = null; }+ releaseSession();capturingRef.current = false;- }, []);+ }, [releaseSession]);// Finalize: stop everything, run the transcription over the captured track.const finish = useCallback(() => {@@ -100,12 +109,18 @@ export default function useSingToScore({ tempo, score = '', musicKey = 'C' } = {setResult(null);trackRef.current = [];+ // Claimed BEFORE getUserMedia — an output-only `playback` session held by a+ // player elsewhere on the page would refuse the request outright — and+ // handed back on every path that never reaches teardown() (the unmount bail+ // below is belt-and-suspenders: the hook already releases on unmount).+ claimSession();const src = await navigator.mediaDevices.getUserMedia({ audio: true }).catch((err) => {+ releaseSession();if (mountedRef.current) setError(err?.message || 'Microphone access denied');return null;});if (!src) return;- if (!mountedRef.current) { src.getTracks().forEach((t) => t.stop()); return; }+ if (!mountedRef.current) { src.getTracks().forEach((t) => t.stop()); releaseSession(); return; }streamRef.current = src;const graph = createStreamAnalyser(src);@@ -153,7 +168,7 @@ export default function useSingToScore({ tempo, score = '', musicKey = 'C' } = {teardown();if (mountedRef.current) setPhase(SING_IDLE);});- }, [phase, bpm, timeSig.beats, timeSig.beatValue, teardown, mountedRef]);+ }, [phase, bpm, timeSig.beats, timeSig.beatValue, teardown, mountedRef, claimSession, releaseSession]);// Clear a produced result (after the user inserts or discards it).const reset = useCallback(() => {diff --git a/client/src/hooks/useSingToScore.test.js b/client/src/hooks/useSingToScore.test.jsindex 902d5a709b..f42f42ed81 100644--- a/client/src/hooks/useSingToScore.test.js+++ b/client/src/hooks/useSingToScore.test.js@@ -47,10 +47,13 @@ describe('useSingToScore', () => {trackerOnUpdate = null;metroOpts = null;global.navigator.mediaDevices = { getUserMedia: vi.fn(async () => fakeStream()) };+ // Safari 16.4+ only — jsdom has no `navigator.audioSession`, so the iOS+ // session tests below stub the shape the arbiter writes to.+ global.navigator.audioSession = { type: 'auto' };global.performance = { now: () => 1000 };});- afterEach(() => { vi.clearAllMocks(); });+ afterEach(() => { vi.clearAllMocks(); delete global.navigator.audioSession; });it('walks idle → count-in → recording → idle and transcribes on stop', async () => {const { result } = renderHook(() => useSingToScore({ tempo: 120, score: 'time: 4/4', musicKey: 'C' }));@@ -101,4 +104,34 @@ describe('useSingToScore', () => {expect(analyserClose).toHaveBeenCalled();expect(trackStop).toHaveBeenCalled();});++ // `playback` REFUSES capture on iOS, and the transport-driven players declare+ // it document-wide, so this hook has to claim `play-and-record` around its own+ // getUserMedia rather than relying on nothing else having claimed first (#4131).+ describe('iOS audio session', () => {+ it('claims play-and-record for the mic window and hands it back on stop', async () => {+ const { result } = renderHook(() => useSingToScore({ tempo: 120, score: 'time: 4/4' }));+ await act(async () => { await result.current.start(); });+ expect(navigator.audioSession.type).toBe('play-and-record');++ act(() => { result.current.stop(); });+ expect(navigator.audioSession.type).toBe('auto');+ });++ it('hands the session back when the mic is denied', async () => {+ global.navigator.mediaDevices.getUserMedia = vi.fn(async () => { throw new Error('Permission denied'); });+ const { result } = renderHook(() => useSingToScore({ tempo: 120 }));+ await act(async () => { await result.current.start(); });+ // A denied mic never reaches teardown(), so the claim has to be released+ // on the rejection path or the page stays pinned record-capable.+ expect(navigator.audioSession.type).toBe('auto');+ });++ it('hands the session back on unmount mid-capture', async () => {+ const { result, unmount } = renderHook(() => useSingToScore({ tempo: 120, score: 'time: 4/4' }));+ await act(async () => { await result.current.start(); });+ unmount();+ expect(navigator.audioSession.type).toBe('auto');+ });+ });});diff --git a/client/src/hooks/useSingToVerify.js b/client/src/hooks/useSingToVerify.jsindex a8e6e12d77..4e102d9eff 100644--- a/client/src/hooks/useSingToVerify.js+++ b/client/src/hooks/useSingToVerify.js@@ -7,6 +7,7 @@ import { createMetronome, clampBpm, DEFAULT_BPM } from '../lib/metronome.js';import { createPitchTracker } from '../lib/pitchDetect.js';import { parseScore } from '../lib/scoreNotation.js';import { alignSingToVerify } from '../lib/singToVerify.js';+import useAudioSessionClaim from './useAudioSessionClaim.js';import useMounted from './useMounted.js';export const VERIFY_IDLE = 'idle';@@ -37,6 +38,11 @@ export default function useSingToVerify({ score: scoreText = '', tempo } = {}) {const bpm = clampBpm(tempo ?? score.tempo) ?? DEFAULT_BPM;+ // Held for exactly the window our own mic stream is open, symmetric with+ // `voiceClient` / `audioRecorder` — see the audio-session note in+ // lib/audioContext.js.+ const { claim: claimSession, release: releaseSession } = useAudioSessionClaim('play-and-record');+const teardown = useCallback(() => {if (metronomeRef.current) { metronomeRef.current.stop(); metronomeRef.current = null; }if (trackerRef.current) { trackerRef.current.stop(); trackerRef.current = null; }@@ -45,8 +51,9 @@ export default function useSingToVerify({ score: scoreText = '', tempo } = {}) {streamRef.current.getTracks().forEach((track) => track.stop());streamRef.current = null;}+ releaseSession();capturingRef.current = false;- }, []);+ }, [releaseSession]);const cancel = useCallback(() => {requestGenerationRef.current += 1;@@ -90,9 +97,18 @@ export default function useSingToVerify({ score: scoreText = '', tempo } = {}) {if (mountedRef.current) setError('Microphone access requires a secure browser connection');return;}+ // Claimed BEFORE getUserMedia — an output-only `playback` session held by a+ // player elsewhere on the page would refuse the request outright — and+ // handed back on every path that never reaches teardown(). The release is+ // gated on this request still being the current one for the same reason the+ // state updates are: a `cancel()` (or unmount) already ran teardown, and a+ // newer start()'s own claim now owns the slot, so releasing from a+ // superseded request would drop THAT claim instead of ours.+ claimSession();const stream = await getUserMedia({ audio: true }).catch((err) => {if (requestGeneration === requestGenerationRef.current) {startPendingRef.current = false;+ releaseSession();if (mountedRef.current) setError(err?.message || 'Microphone access denied');}return null;@@ -100,6 +116,7 @@ export default function useSingToVerify({ score: scoreText = '', tempo } = {}) {if (!stream) return;if (!mountedRef.current || requestGeneration !== requestGenerationRef.current) {stream.getTracks().forEach((track) => track.stop());+ if (requestGeneration === requestGenerationRef.current) releaseSession();return;}startPendingRef.current = false;@@ -143,7 +160,7 @@ export default function useSingToVerify({ score: scoreText = '', tempo } = {}) {teardown();if (mountedRef.current) setPhase(VERIFY_IDLE);});- }, [phase, bpm, score.time.beats, score.time.beatValue, teardown, mountedRef]);+ }, [phase, bpm, score.time.beats, score.time.beatValue, teardown, mountedRef, claimSession, releaseSession]);const reset = useCallback(() => {setRows([]);diff --git a/client/src/hooks/useSingToVerify.test.js b/client/src/hooks/useSingToVerify.test.jsindex dc0bf0907c..7cc34621ef 100644--- a/client/src/hooks/useSingToVerify.test.js+++ b/client/src/hooks/useSingToVerify.test.js@@ -54,9 +54,12 @@ describe('useSingToVerify', () => {clock = 1000;global.performance = { now: () => clock };global.navigator.mediaDevices = { getUserMedia: vi.fn(async () => fakeStream()) };+ // Safari 16.4+ only — jsdom has no `navigator.audioSession`, so the iOS+ // session tests below stub the shape the arbiter writes to.+ global.navigator.audioSession = { type: 'auto' };});- afterEach(() => vi.clearAllMocks());+ afterEach(() => { vi.clearAllMocks(); delete global.navigator.audioSession; });it('captures from the selected start bar and aligns rows on stop', async () => {const { result } = renderHook(() => useSingToVerify({@@ -171,4 +174,66 @@ describe('useSingToVerify', () => {expect(trackStop).toHaveBeenCalledOnce();expect(result.current.phase).toBe(VERIFY_IDLE);});++ // `playback` REFUSES capture on iOS, and the transport-driven players declare+ // it document-wide, so this hook has to claim `play-and-record` around its own+ // getUserMedia rather than relying on nothing else having claimed first (#4131).+ describe('iOS audio session', () => {+ const opts = { tempo: 120, score: 'time: 4/4\n| C4q |' };++ it('claims play-and-record for the mic window and hands it back on stop', async () => {+ const { result } = renderHook(() => useSingToVerify(opts));+ await act(async () => { await result.current.start(1); });+ expect(navigator.audioSession.type).toBe('play-and-record');++ act(() => result.current.stop());+ expect(navigator.audioSession.type).toBe('auto');+ });++ it('hands the session back on cancel', async () => {+ const { result } = renderHook(() => useSingToVerify(opts));+ await act(async () => { await result.current.start(1); });+ act(() => result.current.cancel());+ expect(navigator.audioSession.type).toBe('auto');+ });++ it('hands the session back when the mic is denied', async () => {+ navigator.mediaDevices.getUserMedia = vi.fn(async () => { throw new Error('Permission denied'); });+ const { result } = renderHook(() => useSingToVerify(opts));+ await act(async () => { await result.current.start(1); });+ expect(result.current.error).toBe('Permission denied');+ expect(navigator.audioSession.type).toBe('auto');+ });++ // A cancel during the permission prompt, then a fresh start: the superseded+ // request must NOT release on its way out — cancel() already released its+ // claim, and the slot now belongs to the newer start, which is still live.+ it('keeps the newer start\'s claim when a superseded request settles', async () => {+ let resolveStream;+ navigator.mediaDevices.getUserMedia = vi.fn(() => new Promise((resolve) => { resolveStream = resolve; }));+ const { result } = renderHook(() => useSingToVerify(opts));++ let stalePromise;+ act(() => { stalePromise = result.current.start(1); });+ act(() => result.current.cancel());+ expect(navigator.audioSession.type).toBe('auto');++ navigator.mediaDevices.getUserMedia = vi.fn(async () => fakeStream());+ await act(async () => { await result.current.start(1); });+ expect(navigator.audioSession.type).toBe('play-and-record');++ await act(async () => { resolveStream(fakeStream()); await stalePromise; });+ expect(navigator.audioSession.type).toBe('play-and-record');++ act(() => result.current.stop());+ expect(navigator.audioSession.type).toBe('auto');+ });++ it('hands the session back on unmount mid-capture', async () => {+ const { result, unmount } = renderHook(() => useSingToVerify(opts));+ await act(async () => { await result.current.start(1); });+ unmount();+ expect(navigator.audioSession.type).toBe('auto');+ });+ });});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex f8589b4541..1d56056218 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -129,7 +129,7 @@ grep -i "what you want to do" client/src/lib/README.md| Module | Purpose ||---|---|-| `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. |+| `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; a React surface owning its own context/stream uses `hooks/useAudioSessionClaim.js`, which adds the release-on-unmount backstop. 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. || `chordPlayback.js` | Chord-sheet play-along for the SongBook `tab`/`chordpro` formats (#4104) — the chord-sheet sibling of `drumPlayback.js` and the fourth consumer of `lookaheadTransport.js`. `sheetChordOccurrences(lines)` flattens `parseTabSheet(text).lines` into the ordered chord tokens, each addressed `{ lineIndex, chordIndex }` so `<TabSheetView>` can light exactly the token that is sounding; `chordMidiNotes(name)` voices one chord (bass note + chord tones, via `chordShapes.chordTones`); `buildChordSchedule(lines, { bpm, beatsPerBar, countInBars })` is the PURE chord→`[{ index, name, lineIndex, chordIndex, midis, startSec, durSec, rest }]` mapping (a chord sheet writes no rhythm, so ONE chord token = ONE bar, and a dash-joined "Am-Am7" splits its bar between its segments) plus the count-in clicks; `resolveChordPlayhead(schedule, posSec)` converts an audio-clock position to `{ countIn, index, beat }`; `createChordPlayer(lines, …)` strums it through `scorePlayback`'s `scheduleTone` with a live metronome toggle. || `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`. `chordTones(name)` returns the instrument-free half — the parse plus `semitones` above the root — so `chordPlayback.js` sounds a sheet without re-typing the interval tables. 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. |diff --git a/client/src/lib/audioContext.js b/client/src/lib/audioContext.jsindex 1a9f9fda51..dc3cfbb107 100644--- a/client/src/lib/audioContext.js+++ b/client/src/lib/audioContext.js@@ -7,9 +7,13 @@//// Known holdouts, on purpose: components/city/audio/cityAudioEngine.js keeps// its own context (it owns a persistent gain graph and its own — differently-// contracted — getAudioContext export), and MorseTrainer creates a per-mount+// contracted — getAudioContext export); MorseTrainer creates a per-mount// context it close()s on unmount, which would kill a shared one for everyone-// else. Migrate those only with their graphs/lifecycles in mind.+// else; and pages/Security.jsx builds one per stream around a+// createMediaElementSource graph it tears down with the stream. Migrate those+// only with their graphs/lifecycles in mind. They are holdouts on the CONTEXT+// only — each now claims the iOS audio session below via `useAudioSessionClaim`,+// so none of them is a holdout on the session any more.//// The constructor is resolved lazily so importing this module never touches// audio APIs at load time (node-env test runs import it cleanly). Tests@@ -48,7 +52,10 @@ let sharedCtx = null;// 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.+// around the window their `getUserMedia` stream is open. A React surface that+// owns its own context or stream (so neither of those applies) uses+// `hooks/useAudioSessionClaim.js`, which wraps one claim with the+// release-on-unmount backstop rather than hand-rolling the ref dance.//// Safari 16.4+ only; `navigator.audioSession` is absent everywhere else and// those browsers need nothing. Assignment is guarded because it runs from thediff --git a/client/src/lib/chiptunePlayback.js b/client/src/lib/chiptunePlayback.jsindex 653423045f..f658069b1c 100644--- a/client/src/lib/chiptunePlayback.js+++ b/client/src/lib/chiptunePlayback.js@@ -211,6 +211,10 @@ export function createChiptunePlayer(getScore, { onLoop } = {}) {}},seekCursors: () => { cursor = { idx: 0, loopStartSec: 0, loops: 0 }; },+ // Output-only preview: hold the iOS `playback` session while it loops, or+ // the iPhone's ring/silent switch mutes a page that looks like it is+ // playing. Claimed on play and released on teardown by the transport.+ audioSession: 'playback',onTeardown: () => {if (master) { try { master.disconnect(); } catch { /* already gone */ } master = null; }},diff --git a/client/src/lib/chiptunePlayback.test.js b/client/src/lib/chiptunePlayback.test.jsindex 72a011b787..e886686b08 100644--- a/client/src/lib/chiptunePlayback.test.js+++ b/client/src/lib/chiptunePlayback.test.js@@ -1,9 +1,13 @@-// Pure-schedule tests for the chiptune preview (#2911). Only the Web-Audio-free-// exports are exercised (buildChiptuneSchedule / parseChiptunePitch); the-// timing semantics here MUST agree with server/lib/chiptuneScore.test.js —-// the two flatteners are mirrors of the same contract.-import { describe, expect, it } from 'vitest';-import { buildChiptuneSchedule, parseChiptunePitch } from './chiptunePlayback.js';+// Schedule + audio-session tests for the chiptune preview (#2911). Most of this+// file exercises the Web-Audio-free exports (buildChiptuneSchedule /+// parseChiptunePitch); the timing semantics there MUST agree with+// server/lib/chiptuneScore.test.js — the two flatteners are mirrors of the same+// contract. The last block drives the real player over the shared Web Audio+// fake, purely to pin the iOS audio-session claim (#4131).+import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';+import { buildChiptuneSchedule, parseChiptunePitch, createChiptunePlayer } from './chiptunePlayback.js';+import { acquireAudioSession } from './audioContext.js';+import { createFakeAudio } from '../test/fakeAudioContext.js';const score = () => ({version: 1,@@ -72,3 +76,60 @@ describe('buildChiptuneSchedule', () => {expect(buildChiptuneSchedule({ channels: [], order: [] }).totalSec).toBe(0);});});++// The preview is pure synth with no media element, so on iOS the document's+// default `auto` session behaves as *ambient* — the hardware ring/silent switch+// silences it while the panel's playhead keeps scrolling, with nothing on screen+// to explain the silence. The player opts into `playback` through the shared+// transport; these pin that it claims while sounding and hands it back.+describe('createChiptunePlayer on iOS Safari', () => {+ const { FakeAudioContext, audio } = createFakeAudio();++ beforeEach(() => {+ audio.reset();+ vi.stubGlobal('AudioContext', FakeAudioContext);+ vi.stubGlobal('navigator', { audioSession: { type: 'auto' } });+ vi.useFakeTimers();+ });+ afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); });++ const player = () => createChiptunePlayer(() => score());++ it('holds the playback session while looping so the silent switch cannot mute it', async () => {+ const p = player();+ await p.play();+ expect(p.isPlaying()).toBe(true);+ expect(globalThis.navigator.audioSession.type).toBe('playback');+ p.stop();+ });++ it('hands the session back on stop', async () => {+ const p = player();+ await p.play();+ p.stop();+ expect(globalThis.navigator.audioSession.type).toBe('auto');+ });++ // The VoiceWidget is mounted on every page (Layout.jsx), so push-to-talk can+ // open the mic mid-preview. `playback` REFUSES capture, so the arbiter has to+ // promote — otherwise fixing the silence here would kill the mic instead.+ it('yields to a mic opened mid-preview, then takes playback back', async () => {+ const p = player();+ await p.play();+ const releaseMic = acquireAudioSession('play-and-record');+ expect(globalThis.navigator.audioSession.type).toBe('play-and-record');+ releaseMic();+ expect(globalThis.navigator.audioSession.type).toBe('playback');+ p.stop();+ expect(globalThis.navigator.audioSession.type).toBe('auto');+ });++ // An empty/garbage score aborts in prepare() and never sounds a note, so it+ // must not leave the document pinned output-only either.+ it('does not keep the session when there is nothing to play', async () => {+ const p = createChiptunePlayer(() => null);+ await p.play();+ expect(p.isPlaying()).toBe(false);+ expect(globalThis.navigator.audioSession.type).toBe('auto');+ });+});diff --git a/client/src/pages/Security.jsx b/client/src/pages/Security.jsxindex bef4cd82f1..0d948ca3fa 100644--- a/client/src/pages/Security.jsx+++ b/client/src/pages/Security.jsx@@ -5,6 +5,7 @@ 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';+import useAudioSessionClaim from '../hooks/useAudioSessionClaim.js';const MEDIA_CONSTRAINTS_KEY = 'portos-media-constraints';@@ -16,6 +17,16 @@ export default function Security() {const animationFrameRef = useRef(null);const deviceRestartTimerRef = useRef(null);+ // The monitor routes the host's microphone stream through its OWN+ // AudioContext to the speakers, so it can't inherit the shared lookahead+ // transport's `audioSession` option — it claims the iOS `playback` session by+ // hand for exactly as long as that graph is live. Everything this page sounds+ // is output-only (the capture happens on the server, not in the browser), and+ // without the claim the iPhone's ring/silent switch mutes a remote listen-in+ // that shows a moving level meter the whole time. See the audio-session note+ // in lib/audioContext.js.+ const { claim: claimAudioSession, release: releaseAudioSession } = useAudioSessionClaim('playback');+const [streaming, setStreaming] = useState(false);const [videoEnabled, setVideoEnabled] = useState(true);const [audioEnabled, setAudioEnabled] = useState(true);@@ -75,6 +86,11 @@ export default function Security() {cancelAnimationFrame(animationFrameRef.current);}+ // Claimed BEFORE the resume so the context comes up on the right session.+ // One slot: a re-setup (device switch, stream restart) replaces the previous+ // claim rather than stranding it.+ claimAudioSession();+const audioContext = new (window.AudioContext || window.webkitAudioContext)();// Bring the context up if it isn't running (browser autoplay policy, or@@ -110,7 +126,7 @@ export default function Security() {};updateLevel();- }, []);+ }, [claimAudioSession]);// Enable audio with user interaction (for mobile browsers)const enableAudio = useCallback(async () => {@@ -189,9 +205,13 @@ export default function Security() {if (animationFrameRef.current) {cancelAnimationFrame(animationFrameRef.current);}+ // Nothing is sounding any more, so hand the session back — holding it would+ // follow the user (SPA, no reload) onto every other page and refuse the+ // globally-mounted VoiceWidget's microphone.+ releaseAudioSession();setStreaming(false);setAudioLevel(0);- }, []);+ }, [releaseAudioSession]);// Toggle videoconst toggleVideo = useCallback(() => {diff --git a/client/src/pages/Security.test.jsx b/client/src/pages/Security.test.jsxnew file mode 100644index 0000000000..3540d658dc--- /dev/null+++ b/client/src/pages/Security.test.jsx@@ -0,0 +1,83 @@+// The Security monitor pipes the host's microphone stream through its own+// AudioContext to the speakers. On iOS the document's default `auto` session is+// silenced by the hardware ring/silent switch, so a remote listen-in goes quiet+// while the level meter keeps moving — the page has to claim `playback` for as+// long as that graph is live, and hand it back the moment it isn't (#4131).+//+// jsdom has neither Web Audio nor a working HTMLMediaElement, so both are+// stubbed; the assertions read the declared session type off the stubbed+// `navigator.audioSession` the arbiter writes to.+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { render, screen, fireEvent, act, waitFor } from '@testing-library/react';++vi.mock('../services/api', () => ({+ default: {+ get: vi.fn(async () => ({ data: { video: [{ id: 'cam-1', name: 'Camera 1' }], audio: [{ id: 'mic-1', name: 'Mic 1' }] } })),+ post: vi.fn(async () => ({ data: {} })),+ },+}));++import Security from './Security.jsx';++class FakeAnalyser {+ constructor() { this.fftSize = 256; }+ getByteTimeDomainData() {}+ connect() { return this; }+}++class FakeAudioContext {+ constructor() { this.state = 'running'; this.destination = {}; this.closed = false; }+ createAnalyser() { return new FakeAnalyser(); }+ createMediaElementSource() { return { connect() { return this; } }; }+ resume() { return Promise.resolve(); }+ close() { this.closed = true; }+}++const sessionType = () => navigator.audioSession.type;++// Render, settle the mount-time device fetch, then start the stream — which is+// what builds the AudioContext graph the claim is scoped to.+const startMonitor = async () => {+ const view = render(<Security />);+ await act(async () => {});+ fireEvent.click(screen.getByRole('button', { name: /Start Media/i }));+ await waitFor(() => expect(sessionType()).toBe('playback'));+ return view;+};++describe('Security monitor iOS audio session', () => {+ beforeEach(() => {+ window.AudioContext = FakeAudioContext;+ navigator.audioSession = { type: 'auto' };+ // The level meter's rAF loop would otherwise run forever under jsdom.+ vi.stubGlobal('requestAnimationFrame', vi.fn(() => 1));+ vi.stubGlobal('cancelAnimationFrame', vi.fn());+ window.HTMLMediaElement.prototype.play = vi.fn(async () => {});+ window.HTMLMediaElement.prototype.pause = vi.fn(() => {});+ });++ afterEach(() => {+ delete window.AudioContext;+ delete navigator.audioSession;+ vi.unstubAllGlobals();+ });++ it('claims playback once the monitor graph is live', async () => {+ await startMonitor();+ expect(sessionType()).toBe('playback');+ });++ // Holding it would follow the user (SPA, no reload) onto every other page and+ // refuse the globally-mounted VoiceWidget's microphone.+ it('hands the session back when the stream is stopped', async () => {+ await startMonitor();+ fireEvent.click(screen.getByRole('button', { name: /Stop Media/i }));+ await waitFor(() => expect(sessionType()).toBe('auto'));+ });++ it('hands the session back when the page unmounts while streaming', async () => {+ const { unmount } = await startMonitor();+ unmount();+ expect(sessionType()).toBe('auto');+ });+});diff --git a/client/src/test/fakeAudioContext.js b/client/src/test/fakeAudioContext.jsindex 6f17f0204b..2fb448a9f2 100644--- a/client/src/test/fakeAudioContext.js+++ b/client/src/test/fakeAudioContext.js@@ -102,7 +102,9 @@ export const createFakeAudio = ({ state: initialState = 'running' } = {}) => {createOscillator() {const osc = {type: '', frequency: fakeParam(), onended: null, started: null, stopped: null,+ periodicWave: null,...connectable(), start(t) { this.started = t; }, stop(t) { this.stopped = t; },+ setPeriodicWave(w) { this.periodicWave = w; },};audio.oscillators.push(osc);return osc;@@ -132,6 +134,12 @@ export const createFakeAudio = ({ state: initialState = 'running' } = {}) => {audio.filters.push(filter);return filter;},+ // Band-limited pulse waves (chiptune's non-50%-duty channels). Only the+ // identity matters to a test — the players just hand it back to+ // setPeriodicWave — so the harmonic arrays are recorded, not modelled.+ createPeriodicWave(real, imag, options) {+ return { periodicWave: true, real, imag, options };+ },createWaveShaper() {const shaper = { curve: null, oversample: 'none', ...connectable() };audio.shapers.push(shaper);