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: Release call-host lock and capture on failed attach (#8093)

[._.]/ Adam Eivyf822f82216e8
diff --git a/client/src/pages/VoiceCallHost.jsx b/client/src/pages/VoiceCallHost.jsx
index 6d93bf77ee..c01facb40b 100644
--- a/client/src/pages/VoiceCallHost.jsx
+++ b/client/src/pages/VoiceCallHost.jsx
@@ -80,6 +80,12 @@ export default function VoiceCallHost() {
const [notice, setNotice] = useState(null);
const audio = useRef({ context: null, stream: null, node: null, source: null, playing: new Set(), outputId: null, pending: [] });
const lockRelease = useRef(null);
+ const startGenRef = useRef(0);
+
+ const releaseLock = useCallback(() => {
+ lockRelease.current?.();
+ lockRelease.current = null;
+ }, []);
const teardown = useCallback(() => {
const current = audio.current;
@@ -120,6 +126,7 @@ export default function VoiceCallHost() {
}, []);
const start = useCallback(async () => {
+ const generation = startGenRef.current;
setNotice(null);
const missing = missingCallHostApis(window);
if (missing.length) {
@@ -146,6 +153,10 @@ export default function VoiceCallHost() {
return new Promise((release) => { lockRelease.current = release; });
}).catch(() => resolve(false));
});
+ if (generation !== startGenRef.current) {
+ if (granted) releaseLock();
+ return;
+ }
if (!granted) {
setBlocked('Another tab owns the call host. Close it, or use that tab instead.');
return;
@@ -153,6 +164,10 @@ export default function VoiceCallHost() {
const currentMode = modeRef.current;
const devices = await navigator.mediaDevices.enumerateDevices().catch(() => null);
+ if (generation !== startGenRef.current) {
+ releaseLock();
+ return;
+ }
const problem = describeDeviceProblem(devices, {
inputLabel: DEFAULT_INPUT_LABEL,
// Capture only listens — it never plays a reply back, so it has no
@@ -161,6 +176,7 @@ export default function VoiceCallHost() {
});
if (problem) {
setBlocked(problem);
+ releaseLock();
return;
}
const input = devices.find((device) => device.label === DEFAULT_INPUT_LABEL && device.kind === 'audioinput');
@@ -183,19 +199,45 @@ export default function VoiceCallHost() {
},
});
} catch (error) {
- setBlocked(`Could not open ${DEFAULT_INPUT_LABEL}: ${error.message}`);
+ if (generation === startGenRef.current) setBlocked(`Could not open ${DEFAULT_INPUT_LABEL}: ${error.message}`);
+ releaseLock();
return;
}
- const context = new AudioContext();
- const url = URL.createObjectURL(new Blob([WORKLET_SOURCE], { type: 'application/javascript' }));
+ if (generation !== startGenRef.current) {
+ stream.getTracks().forEach((track) => track.stop());
+ releaseLock();
+ return;
+ }
+
+ let context;
+ let node;
+ let source;
try {
- await context.audioWorklet.addModule(url);
+ context = new AudioContext();
+ const url = URL.createObjectURL(new Blob([WORKLET_SOURCE], { type: 'application/javascript' }));
+ try {
+ await context.audioWorklet.addModule(url);
+ } finally {
+ URL.revokeObjectURL(url);
+ }
+ if (generation !== startGenRef.current) return;
+ source = context.createMediaStreamSource(stream);
+ node = new AudioWorkletNode(context, 'portos-call-tap');
+ source.connect(node);
+ } catch (error) {
+ if (generation === startGenRef.current) setBlocked(`Could not start call audio: ${error.message}`);
+ return;
} finally {
- URL.revokeObjectURL(url);
+ if (generation !== startGenRef.current || !node) {
+ node?.port?.close?.();
+ node?.disconnect?.();
+ source?.disconnect?.();
+ stream.getTracks().forEach((track) => track.stop());
+ context?.close?.();
+ releaseLock();
+ }
}
- const source = context.createMediaStreamSource(stream);
- const node = new AudioWorkletNode(context, 'portos-call-tap');
let carry = [];
node.port.onmessage = (event) => {
const mono = downmixToMono(event.data);
@@ -212,8 +254,6 @@ export default function VoiceCallHost() {
socket.emit('voice:call:audio', { pcm: pcm.buffer });
}
};
- source.connect(node);
-
audio.current = { context, stream, node, source, playing: new Set(), outputId: output?.deviceId ?? null, pending: [] };
// Two literal emits, not a computed event name — a computed
// `socket.emit(x ? 'a' : 'b')` is invisible to the static
@@ -222,16 +262,16 @@ export default function VoiceCallHost() {
if (currentMode === 'call') socket.emit('voice:call:attach');
else socket.emit('voice:capture:start');
setBlocked(null);
- }, []);
+ }, [releaseLock]);
const stop = useCallback(() => {
+ startGenRef.current += 1;
if (modeRef.current === 'call') socket.emit('voice:call:detach');
else socket.emit('voice:capture:stop');
teardown();
- lockRelease.current?.();
- lockRelease.current = null;
+ releaseLock();
setAttached(false);
- }, [teardown]);
+ }, [releaseLock, teardown]);
useEffect(() => {
const onCallState = (snapshot) => {
@@ -273,6 +313,7 @@ export default function VoiceCallHost() {
socket.on('voice:call:tts', onTts);
socket.on('voice:tts:cancel', onTtsCancel);
return () => {
+ startGenRef.current += 1;
socket.off('voice:call:state', onCallState);
socket.off('voice:capture:state', onCaptureState);
socket.off('voice:call:tts', onTts);
@@ -280,10 +321,9 @@ export default function VoiceCallHost() {
if (modeRef.current === 'call') socket.emit('voice:call:detach');
else socket.emit('voice:capture:stop');
teardown();
- lockRelease.current?.();
- lockRelease.current = null;
+ releaseLock();
};
- }, [playToCall, teardown]);
+ }, [playToCall, releaseLock, teardown]);
const playTestTone = async () => {
const context = audio.current.context || new AudioContext();
diff --git a/client/src/pages/VoiceCallHost.test.jsx b/client/src/pages/VoiceCallHost.test.jsx
index 13815af90a..52f2082620 100644
--- a/client/src/pages/VoiceCallHost.test.jsx
+++ b/client/src/pages/VoiceCallHost.test.jsx
@@ -37,12 +37,38 @@ const devices = [
{ label: 'BlackHole 2ch', kind: 'audiooutput', deviceId: 'out-1' },
];
+const exclusiveLock = () => {
+ let held = false;
+ navigator.locks.request = vi.fn((_name, _options, fn) => {
+ if (held) return Promise.resolve(fn(null));
+ held = true;
+ return Promise.resolve(fn(true)).then(() => { held = false; });
+ });
+};
+
+const audioContext = ({ addModule = () => Promise.resolve() } = {}) => {
+ const close = vi.fn(() => Promise.resolve());
+ vi.stubGlobal('AudioContext', function FakeAudioContext() {
+ this.sampleRate = 48000;
+ this.audioWorklet = { addModule };
+ this.createMediaStreamSource = () => ({ connect: vi.fn(), disconnect: vi.fn() });
+ this.close = close;
+ });
+ vi.stubGlobal('AudioWorkletNode', function FakeAudioWorkletNode() {
+ this.port = { close: vi.fn() };
+ this.disconnect = vi.fn();
+ });
+ vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:call-host-worklet');
+ vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
+ return { close };
+};
+
beforeEach(() => {
vi.clearAllMocks();
grantCapabilities();
});
-afterEach(() => { vi.unstubAllGlobals(); });
+afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); });
describe('VoiceCallHost', () => {
it('says nothing reaches PortOS until the host is attached', () => {
@@ -86,6 +112,68 @@ describe('VoiceCallHost', () => {
expect(navigator.mediaDevices.getUserMedia).not.toHaveBeenCalled();
});
+ it('releases the lock after a missing device so a retry can open it', async () => {
+ exclusiveLock();
+ navigator.mediaDevices.enumerateDevices.mockResolvedValueOnce([devices[1]]).mockResolvedValue(devices);
+ navigator.mediaDevices.getUserMedia.mockRejectedValue(new Error('permission denied'));
+ render(<VoiceCallHost />, { wrapper: MemoryRouter });
+
+ await act(async () => { fireEvent.click(screen.getByText('Attach call host')); });
+ expect((await screen.findByRole('alert')).textContent).toMatch(/BlackHole 16ch/);
+ await act(async () => { fireEvent.click(screen.getByText('Attach call host')); });
+
+ expect(navigator.mediaDevices.getUserMedia).toHaveBeenCalledTimes(1);
+ expect((await screen.findByRole('alert')).textContent).toMatch(/permission denied/);
+ });
+
+ it('releases the lock after permission denial so a retry requests permission again', async () => {
+ exclusiveLock();
+ navigator.mediaDevices.enumerateDevices.mockResolvedValue(devices);
+ navigator.mediaDevices.getUserMedia.mockRejectedValue(new Error('permission denied'));
+ render(<VoiceCallHost />, { wrapper: MemoryRouter });
+
+ await act(async () => { fireEvent.click(screen.getByText('Attach call host')); });
+ await act(async () => { fireEvent.click(screen.getByText('Attach call host')); });
+
+ expect(navigator.mediaDevices.getUserMedia).toHaveBeenCalledTimes(2);
+ expect((await screen.findByRole('alert')).textContent).toMatch(/permission denied/);
+ });
+
+ it('stops a stream resolved after unmount without attaching a host', async () => {
+ exclusiveLock();
+ navigator.mediaDevices.enumerateDevices.mockResolvedValue(devices);
+ let resolveStream;
+ navigator.mediaDevices.getUserMedia.mockReturnValue(new Promise((resolve) => { resolveStream = resolve; }));
+ const track = { stop: vi.fn() };
+ const { unmount } = render(<VoiceCallHost />, { wrapper: MemoryRouter });
+
+ await act(async () => { fireEvent.click(screen.getByText('Attach call host')); });
+ unmount();
+ await act(async () => { resolveStream({ getTracks: () => [track] }); });
+
+ expect(track.stop).toHaveBeenCalledTimes(1);
+ expect(socket.emit).not.toHaveBeenCalledWith('voice:call:attach');
+ expect(socket.emit).not.toHaveBeenCalledWith('voice:capture:start');
+ });
+
+ it('cleans up a failed worklet load and releases the lock for retry', async () => {
+ exclusiveLock();
+ navigator.mediaDevices.enumerateDevices.mockResolvedValue(devices);
+ const track = { stop: vi.fn() };
+ navigator.mediaDevices.getUserMedia.mockResolvedValue({ getTracks: () => [track] });
+ const { close } = audioContext({ addModule: () => Promise.reject(new Error('worklet unavailable')) });
+ render(<VoiceCallHost />, { wrapper: MemoryRouter });
+
+ await act(async () => { fireEvent.click(screen.getByText('Attach call host')); });
+ expect((await screen.findByRole('alert')).textContent).toMatch(/worklet unavailable/);
+ await act(async () => { fireEvent.click(screen.getByText('Attach call host')); });
+
+ expect(navigator.mediaDevices.getUserMedia).toHaveBeenCalledTimes(2);
+ expect(track.stop).toHaveBeenCalledTimes(2);
+ expect(close).toHaveBeenCalledTimes(2);
+ expect(socket.emit).not.toHaveBeenCalledWith('voice:call:attach');
+ });
+
it('opens the exact device with every processing stage off', async () => {
navigator.mediaDevices.enumerateDevices.mockResolvedValue(devices);
// getUserMedia succeeding is as far as jsdom goes; the AudioContext work