Open History to see the last commit
1import { BearerConnectionTarget } from "@t3tools/client-runtime/connection";
2import { VoiceInputController } from "@t3tools/client-runtime/voice-input";
3import {
4 DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS,
5 EnvironmentId,
6 type EnvironmentSpeechStatus,
7} from "@t3tools/contracts";
8import { decodeSpeechPcmRequest } from "@t3tools/shared/speech";
9import { expect, it, vi } from "vite-plus/test";
10
11import { stubGlobal } from "../../test/render";
12import { createBrowserVoiceInputPlatform } from "./browserVoiceInput";
13
14vi.mock("../connection/runtime", async () => {
15 const [{ Atom }, { layerRemoteHttpClient }] = await Promise.all([
16 import("effect/reactivity"),
17 import("@t3tools/client-runtime/rpc"),
18 ]);
19 return {
20 connectionAtomRuntime: Atom.runtime(
21 layerRemoteHttpClient((input, init) => globalThis.fetch(input, init)),
22 ),
23 };
24});
25
26function capture() {
27 let receive: ((event: { data: Float32Array | "stopped" }) => void) | undefined;
28 const stopTrack = vi.fn();
29 const resources = new DisposableStack();
30 resources.use(
31 stubGlobal(
32 "AudioContext",
33 class {
34 audioWorklet = { addModule: async () => {} };
35 createMediaStreamSource() {
36 return { connect() {} };
37 }
38 resume = async () => {};
39 close = async () => {};
40 },
41 ),
42 );
43 resources.use(
44 stubGlobal(
45 "AudioWorkletNode",
46 class {
47 port = {
48 set onmessage(handler: typeof receive) {
49 receive = handler;
50 },
51 postMessage(message: string) {
52 if (message === "stop") receive?.({ data: "stopped" });
53 },
54 close() {},
55 };
56 connect() {}
57 disconnect() {}
58 },
59 ),
60 );
61 resources.use(
62 vi.spyOn(navigator.mediaDevices, "getUserMedia").mockResolvedValue({
63 getTracks: () => [{ stop: stopTrack, addEventListener() {} }],
64 } as unknown as MediaStream),
65 );
66 return {
67 feed: (data: Float32Array) => receive?.({ data }),
68 stopTrack,
69 [Symbol.dispose]: () => resources.dispose(),
70 };
71}
72
73const target = new BearerConnectionTarget({
74 environmentId: EnvironmentId.make("remote-transcription"),
75 label: "Remote transcription",
76 connectionId: "remote",
77});
78const prepared = {
79 environmentId: target.environmentId,
80 label: target.label,
81 target,
82 httpBaseUrl: "https://transcription.example.test",
83 socketUrl: "wss://transcription.example.test/ws",
84 httpAuthorization: { _tag: "Bearer" as const, token: "audio-grant" },
85};
86const status = {
87 supported: true,
88 state: "ready",
89 modelId: "native-streaming",
90 model: "Native streaming",
91 size: 1,
92 supportsStreaming: true,
93 supportsBufferedStreaming: true,
94 supportsTranslation: true,
95 languages: ["en", "fr"],
96 supportsLanguageDetection: false,
97 acceleration: "cpu",
98 modelUnloadTimeout: "never",
99 gpuDevices: [],
100 benchmarkTier: "cpu",
101} satisfies EnvironmentSpeechStatus;
102
103it("retains all PCM until stop, retries batch audio, and captures preferences before status resolves", async () => {
104 using microphone = capture();
105 let streaming = false;
106 let options = { ...DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS, speechLanguage: "fr" };
107 const requests: Array<{ pcm: Uint8Array; options: typeof options }> = [];
108 let resolveStatus!: (response: Response) => void;
109 const pendingStatus = new Promise<Response>((resolve) => {
110 resolveStatus = resolve;
111 });
112 const fetch = globalThis.fetch;
113 using _network = vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {
114 const request = new Request(input, init);
115 if (request.url === `${prepared.httpBaseUrl}/api/voice/status`)
116 return (await pendingStatus).clone();
117 if (request.url === `${prepared.httpBaseUrl}/api/voice/transcribe`) {
118 expect(request.headers.get("authorization")).toBe("Bearer audio-grant");
119 requests.push(decodeSpeechPcmRequest(new Uint8Array(await request.arrayBuffer())));
120 return requests.length === 1
121 ? new Response(null, { status: 503 })
122 : Response.json({ text: "bonjour" });
123 }
124 return fetch(input, init);
125 });
126 const onError = vi.fn();
127 const platform = createBrowserVoiceInputPlatform({
128 prepared,
129 hasAudioConsent: () => true,
130 getStreamingEnabled: () => streaming,
131 getTranscriptionOptions: () => options,
132 getMicrophoneId: () => "",
133 onLevel() {},
134 onDurationLimit() {},
135 onText() {},
136 onError,
137 });
138 const commitDraft = vi.fn();
139 const controller = new VoiceInputController({
140 recorder: platform.recorder,
141 retryFailedRecording: true,
142 getTranscriber: () => platform.transcriber,
143 requestPermission: async () => ({ granted: true, canAskAgain: true }),
144 configureRecording: async () => {},
145 releaseRecording: async () => platform.cancelRecording(),
146 deleteRecording: platform.deleteRecording,
147 readDraft: () => ({
148 ownerKey: "draft",
149 text: "",
150 selection: { start: 0, end: 0 },
151 revision: 0,
152 }),
153 commitDraft,
154 onStateChange() {},
155 });
156 using _controller = { [Symbol.dispose]: () => controller.dispose() };
157 const start = controller.start();
158 await vi.waitFor(() => expect(_network).toHaveBeenCalled());
159 streaming = true;
160 options = { ...options, speechLanguage: "en" };
161 resolveStatus(Response.json(status));
162 await start;
163 expect(controller.currentState.phase).toBe("recording");
164 microphone.feed(new Float32Array([0.1, 0.2]));
165 microphone.feed(new Float32Array([0.3]));
166 expect(requests).toHaveLength(0);
167 await controller.stop();
168 expect(controller.currentState.phase).toBe("error");
169 expect(platform.recorder.uri).not.toBeNull();
170 await controller.start();
171 expect(controller.currentState.phase).toBe("idle");
172 expect(commitDraft).toHaveBeenCalledWith("bonjour", { start: 7, end: 7 });
173 expect(requests).toHaveLength(2);
174 for (const request of requests) {
175 expect([...new Float32Array(request.pcm.slice().buffer)]).toEqual([
176 Math.fround(0.1),
177 Math.fround(0.2),
178 Math.fround(0.3),
179 ]);
180 expect(request.options.speechLanguage).toBe("fr");
181 }
182 expect(platform.recorder.uri).toBeNull();
183 expect(microphone.stopTrack).toHaveBeenCalledOnce();
184 expect(onError).not.toHaveBeenCalled();
185 streaming = false;
186 await controller.start();
187 microphone.feed(new Float32Array([0.4]));
188 controller.cancel();
189 await vi.waitFor(() => expect(microphone.stopTrack).toHaveBeenCalledTimes(2));
190 expect(requests).toHaveLength(2);
191 expect(platform.recorder.uri).toBeNull();
192});
193
194it.each([
195 { native: true, enabled: true, buffered: true, live: true },
196 { native: true, enabled: false, buffered: true, live: false },
197 { native: false, enabled: false, buffered: true, live: true },
198 { native: false, enabled: true, buffered: true, live: true },
199 { native: false, enabled: false, buffered: false, live: false },
200])(
201 "selects the destination model's processing path: %j",
202 async ({ native, enabled, buffered, live }) => {
203 const sockets: string[] = [];
204 using _socket = stubGlobal(
205 "WebSocket",
206 class extends EventTarget {
207 constructor(url: string) {
208 super();
209 sockets.push(url);
210 }
211 close() {}
212 },
213 );
214 using _network = vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {
215 const request = new Request(input, init);
216 if (request.url.endsWith("/api/voice/status"))
217 return Response.json({
218 ...status,
219 supportsStreaming: native,
220 supportsBufferedStreaming: buffered,
221 });
222 if (request.url.includes("/api/auth/websocket-ticket/"))
223 return Response.json({ ticket: "stream-ticket", expiresAt: "2030-01-01T00:00:00.000Z" });
224 throw new Error(`Unexpected request: ${request.url}`);
225 });
226 const abort = new AbortController();
227 using _abort = { [Symbol.dispose]: () => abort.abort() };
228 const platform = createBrowserVoiceInputPlatform({
229 prepared,
230 hasAudioConsent: () => true,
231 getStreamingEnabled: () => enabled,
232 getTranscriptionOptions: () => ({
233 ...DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS,
234 speechTranslateToEnglish: true,
235 speechLanguage: "fr",
236 }),
237 getMicrophoneId: () => "",
238 onLevel() {},
239 onDurationLimit() {},
240 onText() {},
241 onError() {},
242 });
243 const transcription = await platform.transcriber.prepare({ signal: abort.signal });
244 expect(Boolean(transcription.streaming)).toBe(live);
245 expect(transcription.locale).toBe(native && enabled ? "fr" : "en");
246 expect(sockets).toEqual(
247 live ? ["wss://transcription.example.test/ws/voice?wsTicket=stream-ticket"] : [],
248 );
249 },
250);