Your always-on AI coworkers that move between text, calls, and Slack.
TypeScript
fix(client): tolerate transient control-poll failures in useVoice (#39)
Saim Shafiqueed05fbba1fe1
diff --git a/package-lock.json b/package-lock.jsonindex 25174ed..f591795 100644--- a/package-lock.json+++ b/package-lock.json@@ -2245,6 +2245,7 @@"cpu": ["ppc64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -2261,6 +2262,7 @@"cpu": ["arm"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -2277,6 +2279,7 @@"cpu": ["arm64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -2293,6 +2296,7 @@"cpu": ["x64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -2309,6 +2313,7 @@"cpu": ["arm64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -2325,6 +2330,7 @@"cpu": ["x64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -2341,6 +2347,7 @@"cpu": ["arm64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -2357,6 +2364,7 @@"cpu": ["x64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -2373,6 +2381,7 @@"cpu": ["arm"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -2389,6 +2398,7 @@"cpu": ["arm64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -2405,6 +2415,7 @@"cpu": ["ia32"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -2421,6 +2432,7 @@"cpu": ["loong64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -2437,6 +2449,7 @@"cpu": ["mips64el"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -2453,6 +2466,7 @@"cpu": ["ppc64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -2469,6 +2483,7 @@"cpu": ["riscv64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -2485,6 +2500,7 @@"cpu": ["s390x"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -2501,6 +2517,7 @@"cpu": ["x64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -2517,6 +2534,7 @@"cpu": ["arm64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -2533,6 +2551,7 @@"cpu": ["x64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -2549,6 +2568,7 @@"cpu": ["arm64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -2565,6 +2585,7 @@"cpu": ["x64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -2581,6 +2602,7 @@"cpu": ["arm64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -2597,6 +2619,7 @@"cpu": ["x64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -2613,6 +2636,7 @@"cpu": ["arm64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -2629,6 +2653,7 @@"cpu": ["ia32"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -2645,6 +2670,7 @@"cpu": ["x64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -4094,6 +4120,7 @@"cpu": ["arm"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -4110,6 +4137,7 @@"cpu": ["arm64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -4126,6 +4154,7 @@"cpu": ["arm64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -4142,6 +4171,7 @@"cpu": ["x64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -4158,6 +4188,7 @@"cpu": ["x64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -4174,6 +4205,7 @@"cpu": ["arm"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -4190,9 +4222,7 @@"cpu": ["arm64"],- "libc": [- "glibc"- ],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -4209,9 +4239,7 @@"cpu": ["arm64"],- "libc": [- "musl"- ],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -4228,9 +4256,7 @@"cpu": ["ppc64"],- "libc": [- "glibc"- ],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -4247,9 +4273,7 @@"cpu": ["s390x"],- "libc": [- "glibc"- ],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -4266,9 +4290,7 @@"cpu": ["x64"],- "libc": [- "glibc"- ],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -4285,9 +4307,7 @@"cpu": ["x64"],- "libc": [- "musl"- ],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -4304,6 +4324,7 @@"cpu": ["arm64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -4320,6 +4341,7 @@"cpu": ["arm64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -4336,6 +4358,7 @@"cpu": ["x64"],+ "dev": true,"license": "MIT","optional": true,"os": [@@ -8127,7 +8150,7 @@"version": "0.28.2","resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz","integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==",- "devOptional": true,+ "dev": true,"hasInstallScript": true,"license": "MIT","bin": {@@ -8801,6 +8824,7 @@"version": "2.3.3","resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz","integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",+ "dev": true,"hasInstallScript": true,"license": "MIT","optional": true,@@ -10068,6 +10092,7 @@"cpu": ["arm64"],+ "dev": true,"license": "MPL-2.0","optional": true,"os": [@@ -10088,6 +10113,7 @@"cpu": ["arm64"],+ "dev": true,"license": "MPL-2.0","optional": true,"os": [@@ -10108,6 +10134,7 @@"cpu": ["x64"],+ "dev": true,"license": "MPL-2.0","optional": true,"os": [@@ -10128,6 +10155,7 @@"cpu": ["x64"],+ "dev": true,"license": "MPL-2.0","optional": true,"os": [@@ -10148,6 +10176,7 @@"cpu": ["arm"],+ "dev": true,"license": "MPL-2.0","optional": true,"os": [@@ -10168,9 +10197,7 @@"cpu": ["arm64"],- "libc": [- "glibc"- ],+ "dev": true,"license": "MPL-2.0","optional": true,"os": [@@ -10191,9 +10218,7 @@"cpu": ["arm64"],- "libc": [- "musl"- ],+ "dev": true,"license": "MPL-2.0","optional": true,"os": [@@ -10214,9 +10239,7 @@"cpu": ["x64"],- "libc": [- "glibc"- ],+ "dev": true,"license": "MPL-2.0","optional": true,"os": [@@ -10237,9 +10260,7 @@"cpu": ["x64"],- "libc": [- "musl"- ],+ "dev": true,"license": "MPL-2.0","optional": true,"os": [@@ -10260,6 +10281,7 @@"cpu": ["arm64"],+ "dev": true,"license": "MPL-2.0","optional": true,"os": [@@ -10280,6 +10302,7 @@"cpu": ["x64"],+ "dev": true,"license": "MPL-2.0","optional": true,"os": [@@ -13785,7 +13808,7 @@"version": "4.23.15","resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.15.tgz","integrity": "sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==",- "devOptional": true,+ "dev": true,"license": "MIT","dependencies": {"esbuild": "~0.28.0"diff --git a/src/client/useVoice.ts b/src/client/useVoice.tsindex cdbc405..875a100 100644--- a/src/client/useVoice.ts+++ b/src/client/useVoice.ts@@ -1,5 +1,9 @@import { useCallback, useEffect, useRef, useState } from 'react';import { api, authHeaders } from './api';+// A single failed control poll is usually a network flap, not a dead call.+// Only treat the control connection as lost after this many consecutive+// poll failures, mirroring the grace period #26 gives the peer connection.+const CONTROL_POLL_FAILURE_LIMIT = 3;export function useVoice(threadId: string,onSaved: () => void,@@ -29,6 +33,7 @@ export function useVoice(channel: RTCDataChannel;transcript: string[];timer?: ReturnType<typeof setTimeout>;+ controlPollFailures: number;disconnectTimer?: ReturnType<typeof setTimeout>;cancelled: boolean;}@@ -114,10 +119,18 @@ export function useVoice(if (id)void api<{ endedAt: number | null }>(`/voice/calls/${id}`).then((call) => {- if (session.current === current && call.endedAt) void end();+ if (session.current !== current) return;+ if (call.endedAt) {+ void end();+ return;+ }+ current.controlPollFailures = 0;}).catch(() => {if (session.current !== current) return;+ current.controlPollFailures += 1;+ if (current.controlPollFailures < CONTROL_POLL_FAILURE_LIMIT)+ return;setError('Call control connection was lost.');void end();});@@ -156,6 +169,7 @@ export function useVoice(cancelled: false,id: undefined as string | undefined,timer: undefined as ReturnType<typeof setTimeout> | undefined,+ controlPollFailures: 0,disconnectTimer: undefined as ReturnType<typeof setTimeout> | undefined,};session.current = current;diff --git a/tests/use-voice-control-poll.test.ts b/tests/use-voice-control-poll.test.tsnew file mode 100644index 0000000..2a3f540--- /dev/null+++ b/tests/use-voice-control-poll.test.ts@@ -0,0 +1,125 @@+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 | undefined;+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;+}+function failPolls(times: number) {+ let seen = 0;+ api.mockImplementation(async (path: string) => {+ if (path === '/voice/calls') return { id: 'call', sdp: 'answer' };+ if (path === '/voice/calls/call' && seen < times) {+ seen += 1;+ throw new Error('network flap');+ }+ return { endedAt: 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');+ });+ expect(voice.status).toBe('active');+});+afterEach(async () => {+ await act(async () => root.unmount());+ vi.useRealTimers();+ vi.unstubAllGlobals();+});+const ends = () => api.mock.calls.filter(([path]) => path.endsWith('/end'));+it('keeps the call alive after a single failed control poll', async () => {+ failPolls(1);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2000);+ });+ expect(ends()).toHaveLength(0);+ expect(voice.status).toBe('active');+ expect(voice.error).toBe('');+});+it('keeps the call alive when a later poll succeeds before the failure limit', async () => {+ failPolls(2);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(6000);+ });+ expect(ends()).toHaveLength(0);+ failPolls(2);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(6000);+ });+ expect(ends()).toHaveLength(0);+ expect(voice.status).toBe('active');+});+it('ends the call after three consecutive failed control polls', async () => {+ failPolls(3);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(6000);+ });+ expect(ends()).toHaveLength(1);+ expect(voice.status).toBe('idle');+ expect(voice.error).toBe('Call control connection was lost.');+});+it('ends a persistently failing control poll exactly once', async () => {+ failPolls(10);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(20000);+ });+ expect(ends()).toHaveLength(1);+});