Skip to content

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

fix: close the claim-leak paths the review found around the new audio-session claims (#4131)

[._.]/ Adam Eivy51bdba68bafe
diff --git a/client/src/components/meatspace/post/MorseTrainer.jsx b/client/src/components/meatspace/post/MorseTrainer.jsx
index 0908afa836..31c8c12b32 100644
--- a/client/src/components/meatspace/post/MorseTrainer.jsx
+++ b/client/src/components/meatspace/post/MorseTrainer.jsx
@@ -943,6 +943,11 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, claimSession, releaseSession
// release below, so it hands the claim back on its way out.
claimSession();
const ctx = await ensureCtx().catch((err) => { releaseSession(); throw err; });
+ // The per-mount context is close()d and nulled on unmount, so a play that
+ // was still inside the iOS unlock window when the trainer went away has
+ // nothing left to sound into. Bail rather than throwing into playMorse — and
+ // hand the claim back, since no teardown will run for this play.
+ if (!ctx) { releaseSession(); playingRef.current = false; return; }
const text = isNew ? pickKochPrompt(prefs.kochLevel) : prompt;
if (isNew) {
setPrompt(text);
@@ -950,10 +955,14 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, claimSession, releaseSession
setFeedback(null);
}
setPlaying(true);
- await playMorse(ctx, text, prefs);
- releaseSession();
- setPlaying(false);
- playingRef.current = false;
+ // `finally`, not a plain sequence: a scheduling failure that rejects here
+ // would otherwise strand the session claim AND leave `playingRef` true,
+ // which silently blocks every later Start Round / replay for the session.
+ await playMorse(ctx, text, prefs).finally(() => {
+ releaseSession();
+ setPlaying(false);
+ playingRef.current = false;
+ });
questionStartRef.current = Date.now();
setTimeout(() => inputRef.current?.focus(), 50);
}
diff --git a/client/src/components/meatspace/post/MorseTrainer.test.jsx b/client/src/components/meatspace/post/MorseTrainer.test.jsx
index 14a102e95d..a1931cb0d9 100644
--- a/client/src/components/meatspace/post/MorseTrainer.test.jsx
+++ b/client/src/components/meatspace/post/MorseTrainer.test.jsx
@@ -529,4 +529,25 @@ describe('MorseTrainer iOS audio session', () => {
// The superseded startTone must not re-declare on its way out.
expect(navigator.audioSession.type).toBe('auto');
});
+
+ // Unmounting inside the unlock window close()s and nulls the per-mount
+ // context, so the parked playPrompt resumes with nothing to sound into. It
+ // must bail rather than throw into playMorse, and the claim must be gone.
+ it('releases and bails when the trainer unmounts inside the unlock window', async () => {
+ let unlock;
+ class SlowAudioContext extends MockAudioContext {
+ constructor() { super(); this.state = 'suspended'; }
+ resume() { return new Promise((r) => { unlock = () => { this.state = 'running'; r(); }; }); }
+ }
+ window.AudioContext = SlowAudioContext;
+ const { unmount } = await renderMorse({ mode: 'copy', onSelectMode: vi.fn(), onExitMode: vi.fn() });
+
+ fireEvent.click(await screen.findByRole('button', { name: /Start Round/i }));
+ expect(navigator.audioSession.type).toBe('playback');
+
+ unmount();
+ expect(navigator.audioSession.type).toBe('auto');
+ await act(async () => { unlock(); });
+ expect(navigator.audioSession.type).toBe('auto');
+ });
});
diff --git a/client/src/hooks/useSingToScore.js b/client/src/hooks/useSingToScore.js
index b863c6675f..dc14a35c32 100644
--- a/client/src/hooks/useSingToScore.js
+++ b/client/src/hooks/useSingToScore.js
@@ -109,12 +109,22 @@ export default function useSingToScore({ tempo, score = '', musicKey = 'C' } = {
setResult(null);
trackRef.current = [];
+ // Resolved (and null-checked) BEFORE the claim: on an insecure origin
+ // `navigator.mediaDevices` is undefined, and reaching through it throws
+ // synchronously — past a claim, that leaves the document pinned
+ // record-capable with no release left to call. Mirrors useSingToVerify.
+ const getUserMedia = navigator.mediaDevices?.getUserMedia?.bind(navigator.mediaDevices);
+ if (!getUserMedia) {
+ 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 unmount bail
// below is belt-and-suspenders: the hook already releases on unmount).
claimSession();
- const src = await navigator.mediaDevices.getUserMedia({ audio: true }).catch((err) => {
+ const src = await getUserMedia({ audio: true }).catch((err) => {
releaseSession();
if (mountedRef.current) setError(err?.message || 'Microphone access denied');
return null;
diff --git a/client/src/hooks/useSingToVerify.js b/client/src/hooks/useSingToVerify.js
index 4e102d9eff..56fb678383 100644
--- a/client/src/hooks/useSingToVerify.js
+++ b/client/src/hooks/useSingToVerify.js
@@ -156,6 +156,11 @@ export default function useSingToVerify({ score: scoreText = '', tempo } = {}) {
});
metronomeRef.current = metronome;
await metronome.start().catch((err) => {
+ // Same generation gate as the getUserMedia paths above, for the same
+ // reason: a cancel()/restart during this await already tore THIS request
+ // down, so an ungated teardown() here would stop the newer request's mic
+ // stream and release the session claim it now holds.
+ if (requestGeneration !== requestGenerationRef.current) return;
if (mountedRef.current) setError(err?.message || 'Could not start audio');
teardown();
if (mountedRef.current) setPhase(VERIFY_IDLE);
diff --git a/client/src/pages/Security.jsx b/client/src/pages/Security.jsx
index 0d948ca3fa..fb1698ac3d 100644
--- a/client/src/pages/Security.jsx
+++ b/client/src/pages/Security.jsx
@@ -86,26 +86,32 @@ export default function Security() {
cancelAnimationFrame(animationFrameRef.current);
}
- // Claimed BEFORE the resume so the context comes up on the right session.
+ const audioContext = new (window.AudioContext || window.webkitAudioContext)();
+
+ // The graph is built BEFORE the session claim, on purpose: node
+ // construction can throw (createMediaElementSource refuses an element that
+ // is already wired to another source node), and a throw past the claim
+ // would leave the document pinned output-only with no release left to call.
+ // Building against a not-yet-resumed context is fine — only the resume has
+ // to happen with the claim in force, so the context comes up on the right
+ // session.
+ const analyser = audioContext.createAnalyser();
+ const source = audioContext.createMediaElementSource(audioElement);
+
+ analyser.fftSize = 256;
+ source.connect(analyser);
+ source.connect(audioContext.destination); // Connect to speakers
+
// 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
// 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);
-
- analyser.fftSize = 256;
- source.connect(analyser);
- source.connect(audioContext.destination); // Connect to speakers
-
audioContextRef.current = audioContext;
analyserRef.current = analyser;