Skip to content

Your always-on AI coworkers that move between text, calls, and Slack.

TypeScript

fix: allow voice connections five seconds to recover (#26)

Charan Rathore82488bd0dfce
diff --git a/package-lock.json b/package-lock.json
index eb88e96..25174ed 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -44,12 +44,14 @@
"@types/node": "^26.6.3",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
+ "@types/react-test-renderer": "^19.3.0",
"@vitejs/plugin-react": "^6.1.1",
"concurrently": "^10.0.5",
"cross-env": "^10.1.0",
"eslint": "^10.11.0",
"eslint-plugin-react-hooks": "^7.1.1",
"prettier": "^3.9.9",
+ "react-test-renderer": "^19.3.0",
"tsx": "^4.23.15",
"typescript": "^6.0.3",
"typescript-eslint": "^8.71.0",
@@ -5851,6 +5853,16 @@
"@types/react": "^19.3.0"
}
},
+ "node_modules/@types/react-test-renderer": {
+ "version": "19.3.0",
+ "resolved": "https://registry.npmjs.org/@types/react-test-renderer/-/react-test-renderer-19.3.0.tgz",
+ "integrity": "sha512-TX4p2D4Z2oigM3SXU7+QyLSUnSR0vR1S1Pfxm/qFL9nHQ3jclgi6ioGoWQmlIr1DeKRVmPJrmNlhgM0JlWlLUg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/react": "*"
+ }
+ },
"node_modules/@types/retry": {
"version": "0.12.0",
"resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz",
@@ -12763,6 +12775,27 @@
}
}
},
+ "node_modules/react-test-renderer": {
+ "version": "19.3.0",
+ "resolved": "https://registry.npmjs.org/react-test-renderer/-/react-test-renderer-19.3.0.tgz",
+ "integrity": "sha512-AUxgv+hRbqjRgx4xVwiWL6cvDDKPAva1VWLXQIMoevqQn9us//C5TX9LEnBGH47D0zvJpjwjxb1umzgOMvE8Wg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "react-is": "^19.3.0",
+ "scheduler": "^0.28.0"
+ },
+ "peerDependencies": {
+ "react": "^19.3.0"
+ }
+ },
+ "node_modules/react-test-renderer/node_modules/react-is": {
+ "version": "19.3.0",
+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.3.0.tgz",
+ "integrity": "sha512-UpMYezM4v5/18F28aC66AEsjXIgE02kyEMH6yLdgLXu/UTfa1Ntwck/nNLrbqJsEXW7gPb0coNO9FQse9WTovA==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/readable-stream": {
"version": "4.7.0",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.7.0.tgz",
diff --git a/package.json b/package.json
index 671e631..0d3e3b7 100644
--- a/package.json
+++ b/package.json
@@ -59,12 +59,14 @@
"@types/node": "^26.6.3",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
+ "@types/react-test-renderer": "^19.3.0",
"@vitejs/plugin-react": "^6.1.1",
"concurrently": "^10.0.5",
"cross-env": "^10.1.0",
"eslint": "^10.11.0",
"eslint-plugin-react-hooks": "^7.1.1",
"prettier": "^3.9.9",
+ "react-test-renderer": "^19.3.0",
"tsx": "^4.23.15",
"typescript": "^6.0.3",
"typescript-eslint": "^8.71.0",
diff --git a/src/client/useVoice.ts b/src/client/useVoice.ts
index 3909137..cdbc405 100644
--- a/src/client/useVoice.ts
+++ b/src/client/useVoice.ts
@@ -29,6 +29,7 @@ export function useVoice(
channel: RTCDataChannel;
transcript: string[];
timer?: ReturnType<typeof setTimeout>;
+ disconnectTimer?: ReturnType<typeof setTimeout>;
cancelled: boolean;
}
| undefined
@@ -45,6 +46,7 @@ export function useVoice(
current.audio.pause();
current.audio.srcObject = null;
clearTimeout(current.timer);
+ clearTimeout(current.disconnectTimer);
}, []);
const end = useCallback(async () => {
if (ending.current) return;
@@ -63,6 +65,7 @@ export function useVoice(
});
current.audio.pause();
clearTimeout(current.timer);
+ clearTimeout(current.disconnectTimer);
ending.current = true;
setStatus('ending');
try {
@@ -153,6 +156,7 @@ export function useVoice(
cancelled: false,
id: undefined as string | undefined,
timer: undefined as ReturnType<typeof setTimeout> | undefined,
+ disconnectTimer: undefined as ReturnType<typeof setTimeout> | undefined,
};
session.current = current;
stream.getTracks().forEach((track) => pc.addTrack(track, stream!));
@@ -169,6 +173,8 @@ export function useVoice(
pc.onconnectionstatechange = () => {
if (current.cancelled) return;
if (pc.connectionState === 'connected') {
+ clearTimeout(current.disconnectTimer);
+ current.disconnectTimer = undefined;
setStatus('active');
setStartedAt((value) => value ?? Date.now());
if (current.id)
@@ -178,7 +184,16 @@ export function useVoice(
},
);
}
- if (['failed', 'disconnected'].includes(pc.connectionState)) {
+ if (pc.connectionState === 'disconnected' && !current.disconnectTimer) {
+ current.disconnectTimer = setTimeout(() => {
+ current.disconnectTimer = undefined;
+ if (current.cancelled || pc.connectionState !== 'disconnected')
+ return;
+ setError('The voice connection dropped.');
+ void end();
+ }, 5000);
+ }
+ if (pc.connectionState === 'failed') {
setError('The voice connection dropped.');
void end();
}
diff --git a/tests/use-voice.test.ts b/tests/use-voice.test.ts
new file mode 100644
index 0000000..0705dac
--- /dev/null
+++ b/tests/use-voice.test.ts
@@ -0,0 +1,138 @@
+import { createElement } from 'react';
+import { act, create, type ReactTestRenderer } from 'react-test-renderer';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { useVoice } from '../src/client/useVoice';
+const api = vi.hoisted(() => vi.fn());
+vi.mock('../src/client/api', () => ({ api, authHeaders: () => ({}) }));
+let voice: ReturnType<typeof useVoice>;
+let root: ReactTestRenderer;
+let pc: FakePeer;
+const track = { stop: vi.fn(), enabled: true };
+class FakePeer {
+ connectionState = 'new';
+ onconnectionstatechange?: () => void;
+ channel = { close: vi.fn(), readyState: 'open' };
+ constructor() {
+ // The test needs the peer created by the hook, like a browser constructor.
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
+ pc = this;
+ }
+ createDataChannel() {
+ return this.channel;
+ }
+ addTrack() {}
+ async createOffer() {
+ return { sdp: 'offer' };
+ }
+ async setLocalDescription() {}
+ async setRemoteDescription() {}
+ close() {}
+ state(value: string) {
+ this.connectionState = value;
+ this.onconnectionstatechange?.();
+ }
+}
+function Hook() {
+ voice = useVoice('thread', () => {});
+ return null;
+}
+beforeEach(async () => {
+ vi.useFakeTimers();
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
+ vi.stubGlobal('RTCPeerConnection', FakePeer);
+ vi.stubGlobal('navigator', {
+ mediaDevices: { getUserMedia: async () => ({ getTracks: () => [track] }) },
+ });
+ vi.stubGlobal(
+ 'Audio',
+ class {
+ autoplay = false;
+ srcObject = null;
+ pause() {}
+ },
+ );
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({}));
+ api
+ .mockReset()
+ .mockImplementation(async (path: string) =>
+ path === '/voice/calls'
+ ? { id: 'call', sdp: 'answer' }
+ : { endedAt: null },
+ );
+ await act(async () => {
+ root = create(createElement(Hook));
+ });
+ await act(async () => {
+ await voice.start();
+ pc.state('connected');
+ });
+});
+afterEach(async () => {
+ await act(async () => root.unmount());
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+const ends = () => api.mock.calls.filter(([path]) => path.endsWith('/end'));
+it('allows a transient disconnect to recover within five seconds', async () => {
+ await act(async () => {
+ pc.state('disconnected');
+ await vi.advanceTimersByTimeAsync(4000);
+ });
+ expect(ends()).toHaveLength(0);
+ await act(async () => {
+ pc.state('connected');
+ await vi.advanceTimersByTimeAsync(6000);
+ });
+ expect(ends()).toHaveLength(0);
+ expect(voice.status).toBe('active');
+});
+it('ends a persistent disconnect after five seconds, not before', async () => {
+ await act(async () => {
+ pc.state('disconnected');
+ await vi.advanceTimersByTimeAsync(4999);
+ });
+ expect(ends()).toHaveLength(0);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
+ });
+ expect(ends()).toHaveLength(1);
+ expect(voice.status).toBe('idle');
+});
+it('does not extend the grace window on repeated disconnected events', async () => {
+ await act(async () => {
+ pc.state('disconnected');
+ await vi.advanceTimersByTimeAsync(3000);
+ pc.state('disconnected');
+ await vi.advanceTimersByTimeAsync(2000);
+ });
+ expect(ends()).toHaveLength(1);
+});
+it('ends failed connections immediately and cancels a pending grace timer', async () => {
+ await act(async () => {
+ pc.state('disconnected');
+ pc.state('failed');
+ });
+ expect(ends()).toHaveLength(1);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(6000);
+ });
+ expect(ends()).toHaveLength(1);
+});
+it('clears disconnect timers on manual end', async () => {
+ await act(async () => {
+ pc.state('disconnected');
+ await voice.end();
+ await vi.advanceTimersByTimeAsync(6000);
+ });
+ expect(ends()).toHaveLength(1);
+});
+it('clears disconnect timers on unmount', async () => {
+ await act(async () => {
+ pc.state('disconnected');
+ root.unmount();
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(6000);
+ });
+ expect(ends()).toHaveLength(0);
+});