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: prevent pending sing-to-score mic leaks (#4236)

[._.]/ Adam Eivy06684ac297da
diff --git a/.changelog/next/fixed-issue-4236.md b/.changelog/next/fixed-issue-4236.md
new file mode 100644
index 0000000000..6188bc283f
--- /dev/null
+++ b/.changelog/next/fixed-issue-4236.md
@@ -0,0 +1 @@
+- Sing-to-score now closes a microphone stream that resolves after its permission prompt has been cancelled.
diff --git a/client/src/hooks/useSingToScore.js b/client/src/hooks/useSingToScore.js
index dc14a35c32..0e11c17072 100644
--- a/client/src/hooks/useSingToScore.js
+++ b/client/src/hooks/useSingToScore.js
@@ -61,6 +61,8 @@ export default function useSingToScore({ tempo, score = '', musicKey = 'C' } = {
const trackRef = useRef([]); // accumulated { tMs, hz, clarity } frames
const captureStartRef = useRef(0); // performance.now() at first music beat
const capturingRef = useRef(false); // gate frames until the count-in completes
+ const startPendingRef = useRef(false);
+ const requestGenerationRef = useRef(0);
// Held for exactly the window our own mic stream is open, symmetric with
// `voiceClient` / `audioRecorder`. Sing-to-score is safe on `auto` only
@@ -82,6 +84,19 @@ export default function useSingToScore({ tempo, score = '', musicKey = 'C' } = {
capturingRef.current = false;
}, [releaseSession]);
+ // Invalidate an in-flight permission request before tearing down. A browser
+ // can resolve getUserMedia after this hook unmounts; that continuation owns
+ // its stream until it sees this generation change and stops it itself.
+ const cancel = useCallback(() => {
+ requestGenerationRef.current += 1;
+ startPendingRef.current = false;
+ teardown();
+ trackRef.current = [];
+ if (!mountedRef.current) return;
+ setPhase(SING_IDLE);
+ setBeat(null);
+ }, [teardown, mountedRef]);
+
// Finalize: stop everything, run the transcription over the captured track.
const finish = useCallback(() => {
teardown();
@@ -104,7 +119,9 @@ export default function useSingToScore({ tempo, score = '', musicKey = 'C' } = {
}, [phase, finish]);
const start = useCallback(async () => {
- if (phase !== SING_IDLE) return;
+ if (phase !== SING_IDLE || startPendingRef.current) return;
+ startPendingRef.current = true;
+ const requestGeneration = ++requestGenerationRef.current;
setError(null);
setResult(null);
trackRef.current = [];
@@ -115,6 +132,7 @@ export default function useSingToScore({ tempo, score = '', musicKey = 'C' } = {
// record-capable with no release left to call. Mirrors useSingToVerify.
const getUserMedia = navigator.mediaDevices?.getUserMedia?.bind(navigator.mediaDevices);
if (!getUserMedia) {
+ startPendingRef.current = false;
if (mountedRef.current) setError('Microphone access requires a secure browser connection');
return;
}
@@ -125,12 +143,20 @@ export default function useSingToScore({ tempo, score = '', musicKey = 'C' } = {
// below is belt-and-suspenders: the hook already releases on unmount).
claimSession();
const src = await getUserMedia({ audio: true }).catch((err) => {
- releaseSession();
- if (mountedRef.current) setError(err?.message || 'Microphone access denied');
+ if (requestGeneration === requestGenerationRef.current) {
+ startPendingRef.current = false;
+ releaseSession();
+ if (mountedRef.current) setError(err?.message || 'Microphone access denied');
+ }
return null;
});
if (!src) return;
- if (!mountedRef.current) { src.getTracks().forEach((t) => t.stop()); releaseSession(); return; }
+ if (!mountedRef.current || requestGeneration !== requestGenerationRef.current) {
+ src.getTracks().forEach((track) => track.stop());
+ if (requestGeneration === requestGenerationRef.current) releaseSession();
+ return;
+ }
+ startPendingRef.current = false;
streamRef.current = src;
const graph = createStreamAnalyser(src);
@@ -174,6 +200,9 @@ export default function useSingToScore({ tempo, score = '', musicKey = 'C' } = {
});
metronomeRef.current = metro;
await metro.start().catch((err) => {
+ // A cancellation or fresh request may have already torn this capture
+ // down. Do not let its late failure tear down a newer session.
+ if (requestGeneration !== requestGenerationRef.current) return;
if (mountedRef.current) setError(err?.message || 'Could not start audio');
teardown();
if (mountedRef.current) setPhase(SING_IDLE);
@@ -186,13 +215,13 @@ export default function useSingToScore({ tempo, score = '', musicKey = 'C' } = {
setError(null);
}, []);
- // Belt-and-suspenders: tear everything down on unmount so a navigation-away
- // mid-capture can't leave the mic open or a loop running. A ref keeps the
- // effect's dep list empty (run cleanup exactly once on unmount) while still
- // calling the latest `teardown`.
- const teardownRef = useRef(teardown);
- teardownRef.current = teardown;
- useEffect(() => () => teardownRef.current(), []);
+ // Belt-and-suspenders: cancel everything on unmount so a navigation-away
+ // mid-permission or mid-capture can't leave the mic open or a loop running.
+ // A ref keeps the effect's dep list empty (run cleanup exactly once on
+ // unmount) while still calling the latest cancellation callback.
+ const cancelRef = useRef(cancel);
+ cancelRef.current = cancel;
+ useEffect(() => () => cancelRef.current(), []);
return { phase, beat, result, error, start, stop, reset };
}
diff --git a/client/src/hooks/useSingToScore.test.js b/client/src/hooks/useSingToScore.test.js
index f42f42ed81..d02d701fa3 100644
--- a/client/src/hooks/useSingToScore.test.js
+++ b/client/src/hooks/useSingToScore.test.js
@@ -93,6 +93,10 @@ describe('useSingToScore', () => {
await act(async () => { await result.current.start(); });
expect(result.current.phase).toBe(SING_IDLE);
expect(result.current.error).toBe('Permission denied');
+
+ global.navigator.mediaDevices.getUserMedia = vi.fn(async () => fakeStream());
+ await act(async () => { await result.current.start(); });
+ expect(result.current.phase).toBe(SING_COUNT_IN);
});
it('tears down mic, analyser, tracker, and metronome on unmount', async () => {
@@ -105,6 +109,45 @@ describe('useSingToScore', () => {
expect(trackStop).toHaveBeenCalled();
});
+ it('allows only one microphone request while permission is pending', async () => {
+ let resolveStream;
+ navigator.mediaDevices.getUserMedia = vi.fn(() => new Promise((resolve) => {
+ resolveStream = resolve;
+ }));
+ const { result } = renderHook(() => useSingToScore({ tempo: 120, score: 'time: 4/4' }));
+
+ let firstStart;
+ act(() => {
+ firstStart = result.current.start();
+ result.current.start();
+ });
+ expect(navigator.mediaDevices.getUserMedia).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ resolveStream(fakeStream());
+ await firstStart;
+ });
+ expect(result.current.phase).toBe(SING_COUNT_IN);
+ });
+
+ it('stops a permission-pending stream when capture is cancelled', async () => {
+ let resolveStream;
+ navigator.mediaDevices.getUserMedia = vi.fn(() => new Promise((resolve) => {
+ resolveStream = resolve;
+ }));
+ const { result, unmount } = renderHook(() => useSingToScore({ tempo: 120, score: 'time: 4/4' }));
+
+ let startPromise;
+ act(() => { startPromise = result.current.start(); });
+ unmount();
+ await act(async () => {
+ resolveStream(fakeStream());
+ await startPromise;
+ });
+
+ expect(trackStop).toHaveBeenCalledOnce();
+ });
+
// `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).