Open History to see the last commit
1import { useLayoutEffect } from "react";
2import { expect, it, vi } from "vite-plus/test";
3import * as Effect from "effect/Effect";
4import * as Option from "effect/Option";
5import type { PreparedConnection } from "@t3tools/client-runtime/connection";
6import {
7 DEFAULT_CLIENT_SETTINGS,
8 DEFAULT_SERVER_SETTINGS,
9 type EnvironmentId,
10 type ProjectId,
11 type SpeechCustomWords,
12 type SpeechPostProcessingOptions,
13 type SpeechTranscriptionOptions,
14} from "@t3tools/contracts";
15
16import { act, render } from "../../test/render";
17import { useEnvironmentSpeechInput } from "./useEnvironmentSpeechInput";
18import { chooseAudioDestination, chooseTranscriptCleanup, bindAudioGrant } from "./voiceConsent";
19import { writeBrowserClientSettings } from "../clientPersistenceStorage";
20
21const mocks = vi.hoisted(() => ({
22 voice: undefined as unknown as ReturnType<typeof useEnvironmentSpeechInput>,
23 settings: {} as Record<string, unknown>,
24 connected: new Set<string>(),
25 voiceCapable: new Set<string>(),
26 canDictate: new Set<string>(),
27 prepared: new Map<string, unknown>(),
28 primaryEnvironmentId: "primary-env",
29 statusRequests: [] as string[],
30 statusUnavailable: false,
31 modelState: "ready" as "ready" | "missing-model",
32 download: vi.fn<() => Promise<void>>(),
33 platforms: [] as string[],
34 microphoneRequests: [] as string[],
35 transcribeCalls: [] as string[],
36 cleanupCalls: [] as string[],
37 cleanupDraft: vi.fn(),
38 cleanupOptions: [] as SpeechPostProcessingOptions[],
39 recordingOptions: [] as SpeechTranscriptionOptions[],
40 projectWords: {} as Record<string, SpeechCustomWords>,
41 transcripts: [] as Array<string | Error>,
42 committed: vi.fn(),
43 draft: "",
44}));
45
46vi.mock("../state/session", () => ({
47 useEnvironmentScope: (id: string) => mocks.canDictate.has(id),
48 usePreparedConnection: (environmentId: string | null) => {
49 if (!environmentId || !mocks.connected.has(environmentId)) return Option.none();
50 let prepared = mocks.prepared.get(environmentId);
51 if (!prepared) {
52 prepared = { environmentId, label: environmentId };
53 mocks.prepared.set(environmentId, prepared);
54 }
55 return Option.some(prepared);
56 },
57}));
58vi.mock("../state/environments", () => ({
59 usePrimaryEnvironmentId: () => mocks.primaryEnvironmentId,
60 useEnvironment: (environmentId: string | null) =>
61 environmentId && mocks.connected.has(environmentId)
62 ? {
63 environmentId,
64 serverConfig: {
65 environment: {
66 capabilities: { voiceTranscription: mocks.voiceCapable.has(environmentId) },
67 },
68 },
69 }
70 : null,
71}));
72vi.mock("../hooks/useSettings", () => ({
73 useClientSettingsHydrated: () => true,
74 useClientSettings: (selector?: (settings: Record<string, unknown>) => unknown) => {
75 const settings = { ...DEFAULT_CLIENT_SETTINGS, ...mocks.settings };
76 return selector ? selector(settings) : settings;
77 },
78 useEnvironmentSettings: (
79 environmentId: string,
80 selector: (settings: Record<string, unknown>) => unknown,
81 ) =>
82 selector({
83 ...DEFAULT_SERVER_SETTINGS,
84 projectSettingsOverrides: Object.fromEntries(
85 Object.entries(environmentId === THREAD_ENV ? mocks.projectWords : {}).map(
86 ([projectId, words]) => [projectId, { speechProjectCustomWords: words }],
87 ),
88 ),
89 }),
90}));
91vi.mock("../lib/runtime", () => ({ runtime: { runPromise: Effect.runPromise } }));
92vi.mock("../components/ui/toast", () => ({ toastManager: { add: vi.fn() } }));
93vi.mock("@t3tools/client-runtime/voice-input", async (importOriginal) => ({
94 ...(await importOriginal<typeof import("@t3tools/client-runtime/voice-input")>()),
95 getEnvironmentSpeechStatus: (prepared: PreparedConnection) =>
96 Effect.sync(() => {
97 mocks.statusRequests.push(prepared.environmentId);
98 if (mocks.statusUnavailable) throw new Error("Temporarily offline");
99 return {
100 supported: true,
101 state: mocks.modelState,
102 modelId: "test-model",
103 model: "Test",
104 size: 1,
105 supportsStreaming: false,
106 supportsTranslation: false,
107 acceleration: "auto",
108 modelUnloadTimeout: "min_15",
109 gpuDevices: [],
110 };
111 }),
112 downloadEnvironmentSpeechModel: () => Effect.promise(mocks.download),
113 getEnvironmentSpeechModels: () => Effect.succeed({ models: [] }),
114 postProcessEnvironmentTranscript: (
115 prepared: PreparedConnection,
116 transcript: string,
117 draft: unknown,
118 options: SpeechPostProcessingOptions,
119 ) =>
120 Effect.sync(() => {
121 mocks.cleanupCalls.push(prepared.environmentId);
122 mocks.cleanupDraft(draft);
123 mocks.cleanupOptions.push(options);
124 return { text: `Cleaned ${transcript}` };
125 }),
126}));
127// Capture and the wire live behind the platform; its `prepared` is where audio would go.
128vi.mock("./browserVoiceInput", () => ({
129 createBrowserVoiceInputPlatform: (input: {
130 prepared: PreparedConnection;
131 getTranscriptionOptions?: () => SpeechTranscriptionOptions;
132 }) => {
133 const environmentId = input.prepared.environmentId;
134 mocks.platforms.push(environmentId);
135 return {
136 recorder: {
137 uri: `blob:${environmentId}`,
138 prepareToRecordAsync: async () => {
139 mocks.microphoneRequests.push(environmentId);
140 },
141 record() {},
142 stop: async () => {},
143 },
144 transcriber: {
145 prepare: async () => {
146 const options = input.getTranscriptionOptions?.();
147 if (options) mocks.recordingOptions.push(options);
148 return {
149 locale: "en",
150 transcribe: async () => {
151 mocks.transcribeCalls.push(environmentId);
152 const next = mocks.transcripts.shift() ?? "dictated";
153 if (next instanceof Error) throw next;
154 return next;
155 },
156 };
157 },
158 },
159 cancelRecording() {},
160 deleteRecording() {},
161 };
162 },
163}));
164
165const THREAD_ENV = "thread-env";
166
167function setup(options: { readonly destination?: string | null } = {}) {
168 mocks.settings = {};
169 setDestination(options.destination ?? null);
170 chooseTranscriptCleanup(false);
171 mocks.primaryEnvironmentId = "primary-env";
172 mocks.connected = new Set(["primary-env", THREAD_ENV, "env-a", "env-b"]);
173 mocks.voiceCapable = new Set(["primary-env", THREAD_ENV, "env-a", "env-b"]);
174 mocks.canDictate = new Set(mocks.voiceCapable);
175 mocks.prepared.clear();
176 mocks.statusRequests = [];
177 mocks.statusUnavailable = false;
178 mocks.modelState = "ready";
179 mocks.download.mockReset();
180 mocks.platforms = [];
181 mocks.microphoneRequests = [];
182 mocks.transcribeCalls = [];
183 mocks.cleanupCalls = [];
184 mocks.cleanupDraft.mockClear();
185 mocks.cleanupOptions = [];
186 mocks.recordingOptions = [];
187 mocks.projectWords = {};
188 mocks.transcripts = [];
189 mocks.committed.mockClear();
190 mocks.draft = "";
191}
192
193function setDestination(environmentId: string | null) {
194 chooseAudioDestination(
195 environmentId ? { kind: "environment", environmentId: environmentId as EnvironmentId } : null,
196 );
197}
198
199function Probe(props: {
200 readonly projectId?: string;
201 readonly projectName?: string;
202 readonly cleanup?: boolean;
203}) {
204 const value = useEnvironmentSpeechInput({
205 environmentId: THREAD_ENV as EnvironmentId,
206 projectId: props.projectId as ProjectId | undefined,
207 projectName: props.projectName,
208 cleanup: props.cleanup,
209 ownerKey: "draft",
210 draftText: mocks.draft,
211 readDraft: () => ({
212 text: mocks.draft,
213 selection: { start: mocks.draft.length, end: mocks.draft.length },
214 }),
215 commitDraft: mocks.committed,
216 });
217 useLayoutEffect(() => {
218 mocks.voice = value;
219 });
220 return null;
221}
222
223function expectNoAudioSent() {
224 expect(mocks.platforms).toEqual([]);
225 expect(mocks.microphoneRequests).toEqual([]);
226 expect(mocks.transcribeCalls).toEqual([]);
227 expect(mocks.statusRequests).toEqual([]);
228}
229
230it.each([
231 ["nothing is configured", {}],
232 // A transcription host picked by an earlier PoC build is not consent.
233 ["a legacy transcription host is configured", { voiceTranscriptionEnvironmentId: "env-a" }],
234])("stays local-only when %s, even with voice-capable environments", async (_, legacy) => {
235 setup();
236 mocks.settings = { ...legacy, speechSilenceFiltering: true };
237 await using _screen = await render(<Probe />);
238 await act(() => mocks.voice.start());
239 expectNoAudioSent();
240 expect(mocks.committed).not.toHaveBeenCalled();
241 expect(mocks.voice.available).toBe(false);
242 expect(mocks.voice.transcriptionEnvironmentId).toBeNull();
243});
244
245it.each([true, false])(
246 "sends audio with silence filtering %s only to the chosen environment",
247 async (speechSilenceFiltering) => {
248 setup({ destination: "env-a" });
249 mocks.settings = { speechSilenceFiltering };
250 await using _screen = await render(<Probe />);
251 expect(mocks.voice.transcriptionEnvironmentId).toBe("env-a");
252 await act(() => mocks.voice.start());
253 expect(mocks.voice.state.phase).toBe("recording");
254 await act(() => mocks.voice.stop());
255 expect(
256 new Set([...mocks.platforms, ...mocks.microphoneRequests, ...mocks.transcribeCalls]),
257 ).toEqual(new Set(["env-a"]));
258 expect(mocks.statusRequests.every((id) => id === "env-a")).toBe(true);
259 expect(mocks.recordingOptions[0]?.speechSilenceFiltering).toBe(speechSilenceFiltering);
260 // Cleanup is a separate opt-in and stays off by default.
261 expect(mocks.cleanupCalls).toEqual([]);
262 expect(mocks.committed).toHaveBeenCalledExactlyOnceWith("dictated", expect.anything());
263 },
264);
265
266it.each([
267 ["is disconnected", () => mocks.connected.delete("env-a")],
268 ["cannot operate", () => mocks.canDictate.delete("env-a")],
269 ["does not support transcription", () => mocks.voiceCapable.delete("env-a")],
270])(
271 "does not fall back to another environment when the chosen one %s",
272 async (_, breakDestination) => {
273 setup({ destination: "env-a" });
274 breakDestination();
275 await using _screen = await render(<Probe />);
276 await act(() => mocks.voice.start());
277 expectNoAudioSent();
278 expect(mocks.voice.available).toBe(false);
279 },
280);
281
282it.each([
283 ["revoked", null],
284 ["moved to another environment", "env-b"],
285 ["renewed for the same environment", "env-a"],
286])("abandons an in-progress recording when consent is %s", async (_, next) => {
287 setup({ destination: "env-a" });
288 await using screen = await render(<Probe />);
289 await act(() => mocks.voice.start());
290 expect(mocks.voice.state.phase).toBe("recording");
291 setDestination(next);
292 await screen.rerender(<Probe />);
293 expect(mocks.voice.state.phase).toBe("idle");
294 await act(() => mocks.voice.stop());
295 expect(mocks.transcribeCalls).toEqual([]);
296 expect(mocks.committed).not.toHaveBeenCalled();
297});
298
299it("retries a failed transcription on the same chosen environment", async () => {
300 setup({ destination: "env-a" });
301 mocks.transcripts = [new Error("inference failed"), "second try"];
302 await using _screen = await render(<Probe />);
303 await act(() => mocks.voice.start());
304 await act(() => mocks.voice.stop());
305 expect(mocks.voice.state).toMatchObject({ phase: "error", errorAction: "retry" });
306 await act(() => mocks.voice.start());
307 if (mocks.voice.state.phase === "recording") await act(() => mocks.voice.stop());
308 expect(mocks.transcribeCalls).toEqual(["env-a", "env-a"]);
309 expect(mocks.committed).toHaveBeenCalledExactlyOnceWith("second try", expect.anything());
310});
311
312it("reopens setup after reconnecting during a download and ignores its stale completion", async () => {
313 setup({ destination: "env-a" });
314 mocks.modelState = "missing-model";
315 let finishDownload!: () => void;
316 mocks.download.mockReturnValue(
317 new Promise<void>((resolve) => {
318 finishDownload = resolve;
319 }),
320 );
321 await using screen = await render(<Probe />);
322 await act(() => mocks.voice.start());
323 let done: Promise<void> | undefined;
324 await act(() => {
325 done = mocks.voice.setup.download();
326 });
327 expect(mocks.voice.setup.downloading).toBe(true);
328 mocks.connected.delete("env-a");
329 await screen.rerender(<Probe />);
330 expect(mocks.voice.setup.open).toBe(false);
331 mocks.connected.add("env-a");
332 await screen.rerender(<Probe />);
333 await act(() => mocks.voice.start());
334 expect(mocks.voice.setup).toMatchObject({ open: true, downloading: false, step: 0 });
335 finishDownload();
336 await act(async () => {
337 await done;
338 });
339 expect(mocks.voice.setup.error).toBeNull();
340});
341
342it("does not resend a failed recording after consent is revoked", async () => {
343 setup({ destination: "env-a" });
344 mocks.transcripts = [new Error("inference failed")];
345 await using screen = await render(<Probe />);
346 await act(() => mocks.voice.start());
347 await act(() => mocks.voice.stop());
348 expect(mocks.voice.state.phase).toBe("error");
349 setDestination(null);
350 await screen.rerender(<Probe />);
351 await act(() => mocks.voice.start());
352 expect(mocks.transcribeCalls).toEqual(["env-a"]);
353 expect(mocks.microphoneRequests).toEqual(["env-a"]);
354 expect(mocks.committed).not.toHaveBeenCalled();
355});
356
357it("revokes across windows even before the storage event and survives stale preference writes", async () => {
358 setup({ destination: "env-a" });
359 await using _screen = await render(<Probe />);
360 await act(() => mocks.voice.start());
361 expect(mocks.voice.state.phase).toBe("recording");
362 const other = document.createElement("iframe");
363 document.body.append(other);
364 try {
365 const storage = other.contentWindow!.localStorage;
366 const key = "t3code:voice-audio-grant:v1";
367 const grant = JSON.parse(storage.getItem(key)!) as { id: string };
368 const canSend = bindAudioGrant(grant.id);
369 expect(canSend()).toBe(true);
370 storage.removeItem(key);
371 expect(canSend()).toBe(false);
372 writeBrowserClientSettings({ ...DEFAULT_CLIENT_SETTINGS, wordWrap: false });
373 await vi.waitFor(() => expect(mocks.voice.available).toBe(false));
374 expect(mocks.voice.state.phase).toBe("idle");
375 await act(() => mocks.voice.stop());
376 expect(mocks.transcribeCalls).toEqual([]);
377 setDestination("env-a");
378 expect(canSend()).toBe(false);
379 } finally {
380 other.remove();
381 }
382});
383
384it("cleans the transcript only after cleanup is separately enabled", async () => {
385 setup({ destination: "env-a" });
386 chooseTranscriptCleanup(true);
387 const nearby = "x".repeat(1_024);
388 mocks.draft = "unrelated private paragraph " + nearby;
389 await using screen = await render(<Probe />);
390 await act(() => mocks.voice.start());
391 await act(() => mocks.voice.stop());
392 expect(mocks.cleanupCalls).toHaveLength(1);
393 expect(mocks.cleanupDraft).toHaveBeenCalledExactlyOnceWith({
394 text: nearby,
395 selection: { start: nearby.length, end: nearby.length },
396 });
397 expect(mocks.committed).toHaveBeenCalledExactlyOnceWith(
398 mocks.draft + " Cleaned dictated",
399 expect.anything(),
400 );
401
402 await act(() => mocks.voice.start());
403 chooseTranscriptCleanup(false);
404 await screen.rerender(<Probe />);
405 await act(() => mocks.voice.stop());
406 expect(mocks.cleanupCalls).toHaveLength(1);
407});
408
409// The settings model test must show what the model heard, not what a provider rewrote.
410it.each([
411 { cleanup: false, authorized: true },
412 { cleanup: undefined, authorized: false },
413])(
414 "keeps a recording without authorized cleanup off the provider: $cleanup / $authorized",
415 async ({ cleanup, authorized }) => {
416 setup({ destination: "env-a" });
417 chooseTranscriptCleanup(true);
418 mocks.settings.speechCorrectionWord = "sorry";
419 if (!authorized) mocks.canDictate.delete(THREAD_ENV);
420 mocks.projectWords = { "proj-1": [{ term: "Acme", aliases: ["ack me"] }] };
421 await using _screen = await render(
422 <Probe {...(cleanup === undefined ? {} : { cleanup })} projectId="proj-1" />,
423 );
424 await act(() => mocks.voice.start());
425 await act(() => mocks.voice.stop());
426 expect(mocks.cleanupCalls).toEqual([]);
427 expect(mocks.recordingOptions.at(-1)?.speechCustomWords).toEqual(mocks.projectWords["proj-1"]);
428 expect(mocks.recordingOptions.at(-1)?.speechCorrectionWord).toBeUndefined();
429 expect(mocks.transcribeCalls).toEqual(["env-a"]);
430 expect(mocks.committed).toHaveBeenCalledExactlyOnceWith("dictated", expect.anything());
431 },
432);
433
434it("sends the project's vocabulary and name as hints, and the cue only with cleanup on", async () => {
435 setup({ destination: "env-a" });
436 mocks.settings.speechCustomWords = [{ term: "Effect", aliases: ["a fact"] }];
437 mocks.settings.speechCorrectionWord = "scratch that";
438 // Stored on the draft's environment under its project, never read from the audio destination.
439 mocks.projectWords = { "proj-1": [{ term: "effect", aliases: ["affect"] }] };
440 await using screen = await render(<Probe projectId="proj-1" projectName="Acme App" />);
441 await act(() => mocks.voice.start());
442 await act(() => mocks.voice.stop());
443 expect(mocks.recordingOptions.at(-1)?.speechCustomWords).toEqual([
444 { term: "Acme App", aliases: [] },
445 { term: "effect", aliases: ["affect"] },
446 ]);
447 expect(mocks.cleanupCalls).toEqual([]);
448
449 chooseTranscriptCleanup(true);
450 await screen.rerender(<Probe projectId="proj-1" projectName="Acme App" />);
451 await act(() => mocks.voice.start());
452 await act(() => mocks.voice.stop());
453 expect(mocks.recordingOptions.at(-1)?.speechCustomWords.map(({ term }) => term)).toEqual([
454 "scratch that",
455 "Acme App",
456 "effect",
457 ]);
458 expect(mocks.cleanupOptions.at(-1)).toMatchObject({ speechCorrectionWord: "scratch that" });
459 expect(mocks.recordingOptions.at(-1)?.speechCorrectionWord).toBe("scratch that");
460 chooseTranscriptCleanup(false);
461 await act(() => mocks.voice.start());
462 await act(() => mocks.voice.stop());
463 expect(mocks.recordingOptions.at(-1)?.speechCorrectionWord).toBeUndefined();
464 expect(mocks.recordingOptions.at(-1)?.speechCustomWords.map(({ term }) => term)).not.toContain(
465 "scratch that",
466 );
467});
468
469it("shares one status probe per destination across every mounted editor", async () => {
470 setup({ destination: "env-a" });
471 await using _screen = await render(
472 <>
473 <Probe />
474 <Probe />
475 <Probe />
476 </>,
477 );
478 expect(mocks.voice.available).toBe(true);
479 expect(mocks.statusRequests).toEqual(["env-a"]);
480});
481
482it("lets the user retry after a status failure without reselecting the destination", async () => {
483 setup({ destination: "env-a" });
484 mocks.statusUnavailable = true;
485 await using _screen = await render(<Probe />);
486 expect(mocks.statusRequests).toEqual(["env-a"]);
487 expect(mocks.voice.available).toBe(true);
488 expect(mocks.microphoneRequests).toEqual([]);
489 mocks.statusUnavailable = false;
490 await act(() => mocks.voice.start());
491 await act(() => mocks.voice.stop());
492 expect(mocks.transcribeCalls).toEqual(["env-a"]);
493});