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: reuse Security page AudioContext across stream restarts (#8425)

[._.]/ Adam Eivybad06da2d1f5
diff --git a/client/src/pages/Security.jsx b/client/src/pages/Security.jsx
index e94930602c..e51dc05f5f 100644
--- a/client/src/pages/Security.jsx
+++ b/client/src/pages/Security.jsx
@@ -13,6 +13,7 @@ export default function Security() {
const videoRef = useRef(null);
const audioRef = useRef(null);
const audioContextRef = useRef(null);
+ const mediaSourceRef = useRef(null);
const analyserRef = useRef(null);
const animationFrameRef = useRef(null);
const deviceRestartTimerRef = useRef(null);
@@ -76,31 +77,42 @@ export default function Security() {
}
}, [selectedVideo, selectedAudio]);
- // Set up audio level monitoring from audio element
+ // Set up audio level monitoring from audio element. An HTMLMediaElement can be
+ // attached to only one MediaElementAudioSourceNode for its lifetime (Web Audio
+ // spec) — the <audio> element here is never remounted, so the AudioContext and
+ // its source node are built ONCE per element and reused across every stream
+ // restart. A restart only resumes the existing context and restarts the meter
+ // loop; the context itself is closed exclusively on unmount (see the cleanup
+ // effect below).
const setupAudioAnalyser = useCallback(async (audioElement) => {
- // Clean up existing audio context
- if (audioContextRef.current) {
- audioContextRef.current.close();
- }
if (animationFrameRef.current) {
cancelAnimationFrame(animationFrameRef.current);
+ animationFrameRef.current = null;
}
- 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
+ let audioContext = audioContextRef.current;
+ let analyser = analyserRef.current;
+
+ if (!audioContext || !mediaSourceRef.current) {
+ // 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.
+ audioContext = new (window.AudioContext || window.webkitAudioContext)();
+ analyser = audioContext.createAnalyser();
+ const source = audioContext.createMediaElementSource(audioElement);
+
+ analyser.fftSize = 256;
+ source.connect(analyser);
+ source.connect(audioContext.destination); // Connect to speakers
+
+ audioContextRef.current = audioContext;
+ mediaSourceRef.current = source;
+ analyserRef.current = analyser;
+ }
// One slot: a re-setup (device switch, stream restart) replaces the previous
// claim rather than stranding it.
@@ -112,9 +124,6 @@ export default function Security() {
setAudioNeedsInteraction(true);
});
- audioContextRef.current = audioContext;
- analyserRef.current = analyser;
-
// Use time-domain data for better audio level detection
const dataArray = new Uint8Array(analyser.fftSize);
@@ -149,18 +158,25 @@ export default function Security() {
}
}, []);
- // Start media stream from server
- const startMedia = useCallback(async () => {
+ // Start media stream from server. `overrides` lets a caller (toggleVideo /
+ // toggleAudio) post the value it JUST computed instead of the state var,
+ // which a `useCallback` closes over from the render that created it — a
+ // stale-closure restart would tell the server to keep streaming the OLD
+ // enabled/disabled flag for one more round-trip.
+ const startMedia = useCallback(async (overrides = {}) => {
setIsLoading(true);
setError(null);
setAudioNeedsInteraction(false);
+ const video = overrides.video !== undefined ? overrides.video : videoEnabled;
+ const audio = overrides.audio !== undefined ? overrides.audio : audioEnabled;
+
// Start streaming on server
await api.post('/media/start', {
videoDeviceId: selectedVideo,
audioDeviceId: selectedAudio,
- video: videoEnabled,
- audio: audioEnabled
+ video,
+ audio
});
setStreaming(true);
@@ -190,12 +206,12 @@ export default function Security() {
audioRef.current.src = `/api/media/audio?t=${timestamp}`;
audioRef.current.play().then(() => {
- if (active) setupAudioAnalyser(audioRef.current);
+ if (active) setupAudioAnalyser(audioRef.current).catch(() => {});
}).catch(() => {
if (!active) return;
// On mobile browsers, autoplay is often blocked - show interaction prompt
setAudioNeedsInteraction(true);
- setupAudioAnalyser(audioRef.current); // Set up analyser anyway for when user enables
+ setupAudioAnalyser(audioRef.current).catch(() => {}); // Set up analyser anyway for when user enables
});
}
@@ -215,11 +231,15 @@ export default function Security() {
audioRef.current.src = '';
}
if (audioContextRef.current) {
- audioContextRef.current.close();
- audioContextRef.current = null;
+ // Suspend, don't close — the context and its MediaElementSourceNode are
+ // scoped to the <audio> element's lifetime (it can only ever be wired to
+ // ONE source node), so they're reused on the next start. Only the
+ // unmount cleanup effect below closes the context.
+ audioContextRef.current.suspend?.()?.catch(() => {});
}
if (animationFrameRef.current) {
cancelAnimationFrame(animationFrameRef.current);
+ animationFrameRef.current = null;
}
// 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
@@ -235,8 +255,9 @@ export default function Security() {
setVideoEnabled(newValue);
if (streaming) {
- // Restart stream with new video setting
- startMedia();
+ // Restart stream with the NEW setting — startMedia's own closure over
+ // videoEnabled is still the pre-toggle value in this render.
+ startMedia({ video: newValue });
}
}, [videoEnabled, streaming, startMedia]);
@@ -246,8 +267,8 @@ export default function Security() {
setAudioEnabled(newValue);
if (streaming) {
- // Restart stream with new audio setting
- startMedia();
+ // Restart stream with the NEW setting — same stale-closure reason as above.
+ startMedia({ audio: newValue });
}
}, [audioEnabled, streaming, startMedia]);
@@ -267,6 +288,21 @@ export default function Security() {
};
}, [streaming, stopMedia]);
+ // The AudioContext and its MediaElementSourceNode are scoped to the <audio>
+ // element's lifetime (setupAudioAnalyser builds them once and reuses them
+ // across restarts), so they're closed only here — the element itself is
+ // never remounted while this component is mounted.
+ useEffect(() => {
+ return () => {
+ if (audioContextRef.current) {
+ audioContextRef.current.close?.()?.catch(() => {});
+ audioContextRef.current = null;
+ }
+ mediaSourceRef.current = null;
+ analyserRef.current = null;
+ };
+ }, []);
+
// Handle device change
const handleDeviceChange = useCallback(async (type, deviceId) => {
if (type === 'video') {
diff --git a/client/src/pages/Security.test.jsx b/client/src/pages/Security.test.jsx
index 3aa42e06f5..b24308946c 100644
--- a/client/src/pages/Security.test.jsx
+++ b/client/src/pages/Security.test.jsx
@@ -30,12 +30,21 @@ class FakeAnalyser {
// stray continuation re-claimed.
let contextsBuilt = 0;
+// Counted so a test can assert createMediaElementSource is never called twice
+// against the same <audio> element — the Web Audio spec throws InvalidStateError
+// on a second attach, which is the root cause this issue fixes.
+let sourcesCreated = 0;
+
class FakeAudioContext {
constructor() { contextsBuilt += 1; 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; }
+ createMediaElementSource() {
+ sourcesCreated += 1;
+ return { connect() { return this; } };
+ }
+ resume() { this.state = 'running'; return Promise.resolve(); }
+ suspend() { this.state = 'suspended'; return Promise.resolve(); }
+ close() { this.closed = true; this.state = 'closed'; return Promise.resolve(); }
}
const sessionType = () => navigator.audioSession.type;
@@ -53,6 +62,7 @@ const startMonitor = async () => {
describe('Security monitor iOS audio session', () => {
beforeEach(() => {
contextsBuilt = 0;
+ sourcesCreated = 0;
window.AudioContext = FakeAudioContext;
navigator.audioSession = { type: 'auto' };
// The level meter's rAF loop would otherwise run forever under jsdom.
@@ -111,3 +121,104 @@ describe('Security monitor iOS audio session', () => {
expect(sessionType()).toBe('auto');
});
});
+
+describe('Security monitor audio graph lifetime across restarts', () => {
+ beforeEach(() => {
+ contextsBuilt = 0;
+ sourcesCreated = 0;
+ window.AudioContext = FakeAudioContext;
+ navigator.audioSession = { type: 'auto' };
+ 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();
+ });
+
+ // The <audio> element is never remounted, and per the Web Audio spec it can
+ // only ever be attached to one MediaElementAudioSourceNode. Stopping and
+ // restarting the stream must reuse the same AudioContext/source instead of
+ // building a second one, which would throw InvalidStateError, go silent,
+ // and leak the never-stored new context (#8425).
+ it('reuses the same AudioContext and source node across a stop/start restart', async () => {
+ render(<Security />);
+ await act(async () => {});
+
+ fireEvent.click(screen.getByRole('button', { name: /Start Media/i }));
+ await waitFor(() => expect(sessionType()).toBe('playback'));
+ expect(contextsBuilt).toBe(1);
+ expect(sourcesCreated).toBe(1);
+
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: /Stop Media/i })); });
+ await waitFor(() => expect(sessionType()).toBe('auto'));
+
+ fireEvent.click(screen.getByRole('button', { name: /Start Media/i }));
+ await waitFor(() => expect(sessionType()).toBe('playback'));
+
+ // Still exactly one context and one source — the restart resumed the
+ // existing graph instead of rebuilding it.
+ expect(contextsBuilt).toBe(1);
+ expect(sourcesCreated).toBe(1);
+ });
+
+ // Unmount is the only path that should ever close the context — a restart
+ // must not close it, or the next start rejects (resuming a closed context).
+ it('closes the AudioContext only on unmount', async () => {
+ const { unmount } = render(<Security />);
+ await act(async () => {});
+ fireEvent.click(screen.getByRole('button', { name: /Start Media/i }));
+ await waitFor(() => expect(sessionType()).toBe('playback'));
+
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: /Stop Media/i })); });
+ await waitFor(() => expect(sessionType()).toBe('auto'));
+
+ unmount();
+ // No direct handle on the FakeAudioContext instance from here, but a
+ // second mount reusing a stale closed-context ref would throw when
+ // resuming it — the earlier restart test already proves resume/suspend
+ // stay healthy across stop/start, so this test only proves unmount runs
+ // cleanly without throwing (the close() cleanup effect fires).
+ });
+});
+
+describe('Security monitor toggle posts the new flag value', () => {
+ beforeEach(() => {
+ contextsBuilt = 0;
+ sourcesCreated = 0;
+ window.AudioContext = FakeAudioContext;
+ navigator.audioSession = { type: 'auto' };
+ 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('posts /media/start with the NEW audio flag when toggling while streaming', async () => {
+ const api = (await import('../services/api')).default;
+ render(<Security />);
+ await act(async () => {});
+
+ fireEvent.click(screen.getByRole('button', { name: /Start Media/i }));
+ await waitFor(() => expect(sessionType()).toBe('playback'));
+
+ api.post.mockClear();
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: /Mute microphone/i }));
+ });
+
+ await waitFor(() => expect(api.post).toHaveBeenCalledWith('/media/start', expect.objectContaining({
+ audio: false,
+ })));
+ });
+});