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: release the iOS audio session when pause cancels a play mid-resume
[._.]/ Adam Eivy0977fdd2d348
diff --git a/client/src/lib/audioContext.js b/client/src/lib/audioContext.jsindex 764eac5ae3..dd611f213d 100644--- a/client/src/lib/audioContext.js+++ b/client/src/lib/audioContext.js@@ -44,15 +44,11 @@ let sharedCtx = null;// play handler — a partial WebKit implementation rejecting the value must not// take playback down with it.-const setAudioSessionType = (type) => {+/** Declare this document's iOS audio session (e.g. `'playback'`). */+export function declareAudioSession(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);}/**@@ -63,7 +59,7 @@ export function declareAudioSession(type) {* feature happened to declare.*/export function releaseAudioSession() {- setAudioSessionType('auto');+ declareAudioSession('auto');}/**diff --git a/client/src/lib/lookaheadTransport.js b/client/src/lib/lookaheadTransport.jsindex b032e351d0..2634acc949 100644--- a/client/src/lib/lookaheadTransport.js+++ b/client/src/lib/lookaheadTransport.js@@ -1,8 +1,8 @@// Shared lookahead-transport for the synth players (#2493). The three players —// createScorePlayer + createMultiScorePlayer (scorePlayback.js) and// createMidiPlayer (midiPlayback.js) — all drive a Web Audio OscillatorNode-// graph through the same lookahead-scheduler state machine: a suspended-context-// resume with a teardown-race guard, an interval that hands due tones to the+// graph through the same lookahead-scheduler state machine: a not-yet-running+// context resume with a teardown-race guard, an interval that hands due tones to the// audio clock, live-node teardown, and pause/stop/finish/seek sequences that// only differ in WHAT they schedule and WHAT the UI is told. This module owns// that transport (the clock + node lifecycle); each player supplies the@@ -150,10 +150,13 @@ export const createLookaheadTransport = ({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.+ // Bail WITHOUT releasing the session: whatever bumped the token (stop, pause,+ // or a newer play) owns it now. A stop/pause has already handed it back, and+ // a newer play has re-declared it — releasing here would silence that one.if (token !== playToken) return;+ // An empty schedule never sounds, so it hands the session back rather than+ // holding a document-wide declaration for nothing. No await runs between the+ // token check and here, so no newer play() can have taken it over.if (doPrepare() === false) { // empty schedule — prepare fired onEndedif (audioSession) releaseAudioSession();return;@@ -168,7 +171,15 @@ export const createLookaheadTransport = ({// Pause — stop sounding, remember position, keep the cursor for resume.const pause = () => {playToken++; // abort an in-flight play() still awaiting ctx.resume()- if (!playing) return;+ if (!playing) {+ // The token bump above just cancelled a play() that is still awaiting its+ // resume — and that play() already declared the session. Nothing is+ // sounding and no teardown will run for it, so hand the session back here+ // or a play-then-immediately-pause leaves the document pinned output-only.+ // (`stop()` needs no such branch: it runs the teardown unconditionally.)+ if (audioSession) releaseAudioSession();+ return;+ }offsetSec = Math.min(Math.max(0, ctx().currentTime - startTime), getTotalSec());clearTick();stopNodes();diff --git a/client/src/lib/scorePlayback.race.test.js b/client/src/lib/scorePlayback.race.test.jsindex 458041246e..d8fd0355ba 100644--- a/client/src/lib/scorePlayback.race.test.js+++ b/client/src/lib/scorePlayback.race.test.js@@ -6,6 +6,7 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { parseScore } from './scoreNotation.js';import { createScorePlayer, createMultiScorePlayer } from './scorePlayback.js';+import { createLookaheadTransport } from './lookaheadTransport.js';import { createFakeAudio } from '../test/fakeAudioContext.js';// The shared fake started suspended only resolves resume() when we call@@ -47,3 +48,48 @@ describe('resume-window teardown race', () => {expect(audio.oscillators).toHaveLength(0);});});++// The audio-session declaration rides the same resume window, and the document+// is shared with the views that open the microphone — so a declaration that+// outlives the sound it was made for is a dead mic, not just a stray flag.+describe('audio session across the resume window', () => {+ beforeEach(() => {+ audio.reset();+ vi.stubGlobal('AudioContext', FakeAudioContext);+ vi.stubGlobal('navigator', { audioSession: { type: 'auto' } });+ vi.useFakeTimers();+ });+ afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); });++ const transport = () => createLookaheadTransport({+ getTotalSec: () => 10, scheduleWindow: () => {}, audioSession: 'playback',+ });++ it('releases when pause() cancels a play still awaiting its resume', async () => {+ // pause() short-circuits on `!playing`, so no teardown runs for the play it+ // just cancelled — without an explicit release there, tapping Play then Pause+ // leaves the whole document pinned output-only.+ const t = transport();+ const playing = t.play();+ expect(globalThis.navigator.audioSession.type).toBe('playback');+ t.pause();+ audio.flushResume();+ await playing;+ expect(t.isPlaying()).toBe(false);+ expect(globalThis.navigator.audioSession.type).toBe('auto');+ });++ it('does not release out from under a newer play that took over mid-await', async () => {+ // The superseded play() must bail WITHOUT releasing: the newer one already+ // re-declared the session and is about to sound against it.+ const t = transport();+ const first = t.play();+ const second = t.play(); // supersedes the first (playing is still false)+ audio.flushResume();+ await Promise.all([first, second]);+ expect(t.isPlaying()).toBe(true);+ expect(globalThis.navigator.audioSession.type).toBe('playback');+ t.stop();+ expect(globalThis.navigator.audioSession.type).toBe('auto');+ });+});diff --git a/client/src/test/fakeAudioContext.js b/client/src/test/fakeAudioContext.jsindex 4af4709f92..e5eb27ffa4 100644--- a/client/src/test/fakeAudioContext.js+++ b/client/src/test/fakeAudioContext.js@@ -19,9 +19,12 @@// resume() attempts.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;+ // Pending resolvers for in-flight resume() calls. A LIST, not a single slot:+ // two overlapping play()s (the second superseding the first mid-await) each+ // park their own resume, and a single slot would drop the first one's resolver+ // so its continuation never ran — the superseded play would hang instead of+ // reaching its stale-token bail.+ let resumeResolvers = [];const audio = {now: 0,// Live context state — flips to 'running' once a pending resume resolves,@@ -47,16 +50,16 @@ export const createFakeAudio = ({ state: initialState = 'running' } = {}) => {this.gains.length = 0;this.filters.length = 0;this.shapers.length = 0;- resolveResume = null;+ resumeResolvers = [];},- // Resolve a pending resume() so play()'s await continues, bringing the+ // Resolve every pending resume() so the parked play()s continue, bringing the// context up exactly as a real one does.flushResume() {- const r = resolveResume;- resolveResume = null;- if (!r) return;+ const pending = resumeResolvers;+ resumeResolvers = [];+ if (!pending.length) return;this.state = 'running';- r();+ for (const r of pending) r();},};// Every node records what it was connected TO, so a test can assert ROUTING@@ -84,7 +87,7 @@ export const createFakeAudio = ({ state: initialState = 'running' } = {}) => {resume: () => {audio.resumeCalls += 1;if (audio.state === 'running') return Promise.resolve();- return new Promise((r) => { resolveResume = r; });+ return new Promise((r) => { resumeResolvers.push(r); });},get currentTime() { return audio.now; },destination: { id: 'destination' },