Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useEnvironmentSpeechInput.browser.test.tsx

921 lines34.3 KB

1import { useLayoutEffect } from "react";
2import { expect, it, vi } from "vite-plus/test";
3import { page, userEvent } from "vite-plus/test/browser";
4import * as Deferred from "effect/Deferred";
5import * as Effect from "effect/Effect";
6import * as Option from "effect/Option";
7import type { PreparedConnection } from "@t3tools/client-runtime/connection";
8import { getEnvironmentSpeechModels } from "@t3tools/client-runtime/voice-input";
9import {
10 DEFAULT_CLIENT_SETTINGS,
11 DEFAULT_SERVER_SETTINGS,
12 EnvironmentId,
13 type EnvironmentSpeechModel,
14 type ProjectId,
15 type SpeechCustomWords,
16 type SpeechPostProcessingOptions,
17 type SpeechTranscriptionOptions,
18} from "@t3tools/contracts";
19​
20import { act, render, stubGlobal } from "../../test/render";
21import { AppRouteModal } from "../components/AppRouteModal";
22import { GlobalVoiceInputIndicator } from "../components/chat/GlobalVoiceInputIndicator";
23import { VoiceInputSetup } from "../components/chat/VoiceInputSetup";
24import type { createBrowserVoiceInputPlatform } from "./browserVoiceInput";
25import { useEnvironmentSpeechInput } from "./useEnvironmentSpeechInput";
26import {
27 chooseAudioDestination,
28 chooseTranscriptCleanup,
29 bindAudioGrant,
30 pendingCloudAudioChoice,
31} from "./voiceConsent";
32import { writeBrowserClientSettings } from "../clientPersistenceStorage";
33​
34const mocks = vi.hoisted(() => ({
35 voice: undefined as unknown as ReturnType<typeof useEnvironmentSpeechInput>,
36 settings: {} as Record<string, unknown>,
37 connected: new Set<string>(),
38 voiceCapable: new Set<string>(),
39 cloudVoiceCapable: new Set<string>(),
40 canDictate: new Set<string>(),
41 prepared: new Map<string, unknown>(),
42 primaryEnvironmentId: "primary-env",
43 statusRequests: [] as string[],
44 statusUnavailable: false,
45 statusTier: "accelerated" as "cpu" | "accelerated",
46 modelState: "ready" as "ready" | "missing-model",
47 statusModelId: "test-model",
48 models: [] as EnvironmentSpeechModel[],
49 catalogOffline: false,
50 download: vi.fn<(modelId: string) => Promise<void>>(),
51 selected: [] as string[],
52 selectionFails: false,
53 platforms: [] as string[],
54 microphoneRequests: [] as string[],
55 transcribeCalls: [] as string[],
56 cleanupCalls: [] as string[],
57 cleanupDraft: vi.fn(),
58 cleanupOptions: [] as SpeechPostProcessingOptions[],
59 recordingOptions: [] as SpeechTranscriptionOptions[],
60 projectWords: {} as Record<string, SpeechCustomWords>,
61 transcripts: [] as Array<string | Error>,
62 committed: vi.fn(),
63 draft: "",
64 storedDraft: "",
65}));
66​
67vi.mock("../components/sidebar/mainAppLocation", () => ({
68 useCloseAppModal: () => () => Promise.resolve(),
69}));
70vi.mock("../state/session", () => ({
71 useEnvironmentScope: (id: string) => mocks.canDictate.has(id),
72 usePreparedConnection: (environmentId: string | null) => {
73 if (!environmentId || !mocks.connected.has(environmentId)) return Option.none();
74 let prepared = mocks.prepared.get(environmentId);
75 if (!prepared) {
76 prepared = { environmentId, label: environmentId };
77 mocks.prepared.set(environmentId, prepared);
78 }
79 return Option.some(prepared);
80 },
81}));
82vi.mock("../state/environments", () => ({
83 usePrimaryEnvironmentId: () => mocks.primaryEnvironmentId,
84 useEnvironment: (environmentId: string | null) =>
85 environmentId && mocks.connected.has(environmentId)
86 ? {
87 environmentId,
88 serverConfig: {
89 environment: {
90 capabilities: {
91 voiceTranscription: mocks.voiceCapable.has(environmentId),
92 cloudVoiceTranscription: mocks.cloudVoiceCapable.has(environmentId),
93 },
94 },
95 },
96 }
97 : null,
98}));
99vi.mock("../hooks/useSettings", () => ({
100 updateClientSettings: vi.fn(),
101 getClientSettings: () => ({ ...DEFAULT_CLIENT_SETTINGS, ...mocks.settings }),
102 isClientSettingsHydrated: () => true,
103 useClientSettingsHydrated: () => true,
104 useClientSettings: (selector?: (settings: Record<string, unknown>) => unknown) => {
105 const settings = { ...DEFAULT_CLIENT_SETTINGS, ...mocks.settings };
106 return selector ? selector(settings) : settings;
107 },
108 useEnvironmentSettings: (
109 environmentId: string,
110 selector: (settings: Record<string, unknown>) => unknown,
111 ) =>
112 selector({
113 ...DEFAULT_SERVER_SETTINGS,
114 projectSettingsOverrides: Object.fromEntries(
115 Object.entries(environmentId === THREAD_ENV ? mocks.projectWords : {}).map(
116 ([projectId, words]) => [projectId, { speechProjectCustomWords: words }],
117 ),
118 ),
119 }),
120}));
121vi.mock("./runEnvironmentSpeech", () => ({ runEnvironmentSpeech: Effect.runPromise }));
122vi.mock("../components/ui/toast", () => ({ toastManager: { add: vi.fn() } }));
123vi.mock("@t3tools/client-runtime/voice-input", async (importOriginal) => ({
124 ...(await importOriginal<typeof import("@t3tools/client-runtime/voice-input")>()),
125 getEnvironmentSpeechStatus: (prepared: PreparedConnection) =>
126 Effect.sync(() => {
127 mocks.statusRequests.push(prepared.environmentId);
128 if (mocks.statusUnavailable) throw new Error("Temporarily offline");
129 return {
130 supported: true,
131 state: mocks.modelState,
132 modelId: mocks.statusModelId,
133 model: "Test",
134 size: 1,
135 supportsStreaming: false,
136 supportsTranslation: false,
137 acceleration: "auto",
138 benchmarkTier: mocks.statusTier,
139 modelUnloadTimeout: "min_15",
140 gpuDevices: [],
141 };
142 }),
143 downloadEnvironmentSpeechModel: (_prepared: PreparedConnection, modelId: string) =>
144 Effect.promise(async () => {
145 await mocks.download(modelId);
146 return { models: mocks.models };
147 }),
148 selectEnvironmentSpeechModel: (_prepared: PreparedConnection, modelId: string) =>
149 Effect.sync(() => {
150 mocks.selected.push(modelId);
151 if (mocks.selectionFails) throw new Error("selection failed");
152 mocks.statusModelId = modelId;
153 return { models: mocks.models };
154 }),
155 getEnvironmentSpeechModels: vi.fn((_prepared: PreparedConnection, includeBenchmarks = false) =>
156 Effect.sync(() => {
157 if (mocks.catalogOffline) throw new Error("Catalog offline");
158 return {
159 models: mocks.models.map(({ benchmark, ...model }) =>
160 includeBenchmarks ? { ...model, ...(benchmark ? { benchmark } : {}) } : model,
161 ),
162 };
163 }),
164 ),
165 postProcessEnvironmentTranscript: (
166 prepared: PreparedConnection,
167 transcript: string,
168 draft: unknown,
169 options: SpeechPostProcessingOptions,
170 ) =>
171 Effect.sync(() => {
172 mocks.cleanupCalls.push(prepared.environmentId);
173 mocks.cleanupDraft(draft);
174 mocks.cleanupOptions.push(options);
175 return { text: `Cleaned ${transcript}` };
176 }),
177}));
178vi.mock("./browserVoiceInput", () => ({
179 createBrowserVoiceInputPlatform: (
180 input: Parameters<typeof createBrowserVoiceInputPlatform>[0],
181 ) => {
182 const environmentId = input.prepared.environmentId;
183 mocks.platforms.push(environmentId);
184 return {
185 recorder: {
186 uri: `blob:${environmentId}`,
187 prepareToRecordAsync: async () => {
188 mocks.microphoneRequests.push(environmentId);
189 },
190 record() {},
191 stop: async () => {},
192 },
193 transcriber: {
194 prepare: async () => {
195 mocks.recordingOptions.push(input.getTranscriptionOptions());
196 return {
197 locale: "en",
198 transcribe: async () => {
199 mocks.transcribeCalls.push(
200 input.cloudProvider
201 ? `${[input.cloudProvider, (input as { cloudModel?: string }).cloudModel].filter(Boolean).join(":")} via ${environmentId}`
202 : environmentId,
203 );
204 const next = mocks.transcripts.shift() ?? "dictated";
205 if (next instanceof Error) throw next;
206 return next;
207 },
208 };
209 },
210 },
211 cancelRecording() {},
212 deleteRecording() {},
213 };
214 },
215}));
216​
217const THREAD_ENV = "thread-env";
218​
219function setup(options: { readonly destination?: string | null } = {}) {
220 mocks.settings = {};
221 setDestination(options.destination ?? null);
222 if (!options.destination) localStorage.removeItem("t3code:voice-audio-grant:v1");
223 chooseTranscriptCleanup(false);
224 mocks.primaryEnvironmentId = "primary-env";
225 mocks.connected = new Set(["primary-env", THREAD_ENV, "env-a", "env-b"]);
226 mocks.voiceCapable = new Set(["primary-env", THREAD_ENV, "env-a", "env-b"]);
227 mocks.cloudVoiceCapable.clear();
228 mocks.canDictate = new Set(mocks.voiceCapable);
229 mocks.prepared.clear();
230 mocks.statusRequests = [];
231 mocks.statusUnavailable = false;
232 mocks.modelState = "ready";
233 mocks.statusTier = "accelerated";
234 mocks.statusModelId = "test-model";
235 mocks.models = [];
236 mocks.catalogOffline = false;
237 mocks.download.mockReset();
238 mocks.selected = [];
239 mocks.selectionFails = false;
240 mocks.platforms = [];
241 mocks.microphoneRequests = [];
242 mocks.transcribeCalls = [];
243 mocks.cleanupCalls = [];
244 mocks.cleanupDraft.mockClear();
245 mocks.cleanupOptions = [];
246 mocks.recordingOptions = [];
247 mocks.projectWords = {};
248 mocks.transcripts = [];
249 mocks.committed.mockClear();
250 mocks.draft = "";
251 mocks.storedDraft = "";
253​
254function setDestination(environmentId: string | null) {
255 chooseAudioDestination(
256 environmentId ? { kind: "environment", environmentId: environmentId as EnvironmentId } : null,
257 );
259​
260function Probe(props: {
261 readonly projectId?: string;
262 readonly projectName?: string;
263 readonly cleanup?: boolean;
264 readonly showWizard?: boolean;
265 readonly ownerKey?: string;
266 readonly persistent?: boolean;
267}) {
268 const value = useEnvironmentSpeechInput({
269 environmentId: THREAD_ENV as EnvironmentId,
270 projectId: props.projectId as ProjectId | undefined,
271 projectName: props.projectName,
272 cleanup: props.cleanup,
273 ownerKey: props.ownerKey ?? "draft",
274 persistentDraft: props.persistent
275 ? {
276 readStoredText: () => mocks.storedDraft,
277 commitStoredText: (text) => {
278 mocks.storedDraft = text;
279 },
280 open: () => {},
281 }
282 : undefined,
283 readDraft: () => ({
284 text: mocks.draft,
285 selection: { start: mocks.draft.length, end: mocks.draft.length },
286 }),
287 commitDraft: mocks.committed,
288 });
289 useLayoutEffect(() => {
290 mocks.voice = value;
291 });
292 return props.showWizard ? (
293 <VoiceInputSetup
294 {...value.setup}
295 environmentId={value.transcriptionEnvironmentId}
296 status={value.status}
297 onOpenChange={value.setup.setOpen}
298 onRetryCatalog={value.setup.retryCatalog}
299 onDownload={value.setup.download}
300 onCancelDownload={value.setup.cancelDownload}
301 onStartRecording={value.setup.startRecording}
302 />
303 ) : null;
305​
306function expectNoAudioSent() {
307 expect(mocks.platforms).toEqual([]);
308 expect(mocks.microphoneRequests).toEqual([]);
309 expect(mocks.transcribeCalls).toEqual([]);
310 expect(mocks.statusRequests).toEqual([]);
312​
313it.each([
314 ["nothing is configured", {}],
315 // A transcription host picked by an earlier PoC build is not consent.
316 ["a legacy transcription host is configured", { voiceTranscriptionEnvironmentId: "env-a" }],
317])("opens destination setup without sending audio when %s", async (_, legacy) => {
318 setup();
319 mocks.settings = { ...legacy, speechSilenceFiltering: true };
320 await using screen = await render(<Probe />);
321 // The composer mic and the dictation shortcut both gate on this.
322 expect(mocks.voice.available).toBe(true);
323 await act(() => mocks.voice.start());
324 expect(screen.router?.state.location).toMatchObject({
325 pathname: "/settings/voice",
326 hash: "voice-transcription-destination",
327 });
328 expectNoAudioSent();
329 expect(mocks.committed).not.toHaveBeenCalled();
330 expect(mocks.voice.state.phase).toBe("idle");
331 expect(mocks.voice.transcriptionEnvironmentId).toBeNull();
332 expect(localStorage.getItem("t3code:voice-audio-grant:v1")).toBeNull();
333});
334​
335it.each([true, false])(
336 "sends audio with silence filtering %s only to the chosen environment",
337 async (speechSilenceFiltering) => {
338 setup({ destination: "env-a" });
339 mocks.settings = { speechSilenceFiltering };
340 await using _screen = await render(<Probe />);
341 expect(mocks.voice.transcriptionEnvironmentId).toBe("env-a");
342 await act(() => mocks.voice.start());
343 expect(mocks.voice.state.phase).toBe("recording");
344 await act(() => mocks.voice.stop());
345 expect(
346 new Set([...mocks.platforms, ...mocks.microphoneRequests, ...mocks.transcribeCalls]),
347 ).toEqual(new Set(["env-a"]));
348 expect(mocks.statusRequests.every((id) => id === "env-a")).toBe(true);
349 expect(mocks.recordingOptions[0]?.speechSilenceFiltering).toBe(speechSilenceFiltering);
350 // Cleanup is a separate opt-in and stays off by default.
351 expect(mocks.cleanupCalls).toEqual([]);
352 expect(mocks.committed).toHaveBeenCalledExactlyOnceWith("dictated", expect.anything());
353 },
354);
355​
356it.each([
357 ["is disconnected", () => mocks.connected.delete("env-a")],
358 ["cannot operate", () => mocks.canDictate.delete("env-a")],
359 ["does not support transcription", () => mocks.voiceCapable.delete("env-a")],
360])(
361 "does not fall back to another environment when the chosen one %s",
362 async (_, breakDestination) => {
363 setup({ destination: "env-a" });
364 breakDestination();
365 await using _screen = await render(<Probe />);
366 await act(() => mocks.voice.start());
367 expectNoAudioSent();
368 expect(mocks.voice.available).toBe(false);
369 },
370);
371​
372it.each([
373 ["revoked", null],
374 ["moved to another environment", "env-b"],
375 ["renewed for the same environment", "env-a"],
376])("abandons an in-progress recording when consent is %s", async (_, next) => {
377 setup({ destination: "env-a" });
378 await using screen = await render(<Probe />);
379 await act(() => mocks.voice.start());
380 expect(mocks.voice.state.phase).toBe("recording");
381 setDestination(next);
382 await screen.rerender(<Probe />);
383 if (next === null) expect(mocks.voice.available).toBe(false);
384 expect(mocks.voice.state.phase).toBe("idle");
385 await act(() => mocks.voice.stop());
386 expect(mocks.transcribeCalls).toEqual([]);
387 expect(mocks.committed).not.toHaveBeenCalled();
388});
389​
390it("retries a failed transcription on the same chosen environment", async () => {
391 setup({ destination: "env-a" });
392 mocks.transcripts = [new Error("inference failed"), "second try"];
393 await using _screen = await render(<Probe />);
394 await act(() => mocks.voice.start());
395 await act(() => mocks.voice.stop());
396 expect(mocks.voice.state).toMatchObject({ phase: "error", errorAction: "retry" });
397 await act(() => mocks.voice.start());
398 if (mocks.voice.state.phase === "recording") await act(() => mocks.voice.stop());
399 expect(mocks.transcribeCalls).toEqual(["env-a", "env-a"]);
400 expect(mocks.committed).toHaveBeenCalledExactlyOnceWith("second try", expect.anything());
401});
402​
403it.each([
404 ["a stored thread draft keeps recording into it", true],
405 ["an editor-only draft is abandoned", false],
406])("when the editor switches owner mid-recording, %s", async (_name, persistent) => {
407 setup({ destination: "env-a" });
408 mocks.storedDraft = "Earlier text";
409 const view = (ownerKey: string) => (
410 <>
411 <Probe ownerKey={ownerKey} persistent={persistent} />
412 <GlobalVoiceInputIndicator />
413 </>
414 );
415 await using screen = await render(view("thread-a"));
416 await act(() => mocks.voice.start());
417 expect(mocks.voice.state.phase).toBe("recording");
418 // The indicator stays away while the recording's own editor is on screen.
419 expect(page.getByRole("button", { name: "Finish voice input" }).query()).toBeNull();
420​
421 await screen.rerender(view("thread-b"));
422 // One microphone: thread-b cannot start its own recording while thread-a's runs.
423 expect(mocks.voice.available).toBe(!persistent);
424 if (!persistent) {
425 await expect
426 .element(page.getByRole("button", { name: "Finish voice input" }))
427 .not.toBeInTheDocument();
428 expect(mocks.transcribeCalls).toEqual([]);
429 expect(mocks.storedDraft).toBe("Earlier text");
430 return;
431 }
432 await page.getByRole("button", { name: "Finish voice input" }).click();
433​
434 await vi.waitFor(() => expect(mocks.storedDraft).toBe("Earlier text dictated"));
435 expect(mocks.transcribeCalls).toEqual(["env-a"]);
436 expect(mocks.committed).not.toHaveBeenCalled();
437});
438​
439it("finishes an off-screen recording with the keyboard while Settings is open", async () => {
440 setup({ destination: "env-a" });
441 mocks.storedDraft = "Earlier text";
442 await using screen = await render(
443 <>
444 <Probe ownerKey="thread-a" persistent />
445 <GlobalVoiceInputIndicator />
446 </>,
447 );
448 await act(() => mocks.voice.start());
449 await screen.rerender(
450 <>
451 <AppRouteModal label="Settings">
452 <button type="button">Settings control</button>
453 </AppRouteModal>
454 <GlobalVoiceInputIndicator hidden />
455 </>,
456 );
457 await expect.element(page.getByRole("dialog", { name: "Settings" })).toHaveFocus();
458 await userEvent.keyboard("{Shift>}{Tab}{/Shift}");
459 await expect.element(page.getByRole("button", { name: "Finish voice input" })).toHaveFocus();
460 await userEvent.keyboard("{Enter}");
461 await vi.waitFor(() => expect(mocks.storedDraft).toBe("Earlier text dictated"));
462});
463​
464it("reopens setup after reconnecting during a download and ignores its stale completion", async () => {
465 setup({ destination: "env-a" });
466 mocks.modelState = "missing-model";
467 mocks.settings = { speechLanguage: "en" };
468 mocks.models = [catalogModel(mocks.statusModelId, ["en"], true)];
469 let finishDownload!: () => void;
470 mocks.download.mockReturnValue(
471 new Promise<void>((resolve) => {
472 finishDownload = resolve;
473 }),
474 );
475 await using screen = await render(<Probe />);
476 await act(() => mocks.voice.start());
477 let done: Promise<void> | undefined;
478 await act(() => {
479 done = mocks.voice.setup.download();
480 });
481 expect(mocks.voice.setup.downloading).toBe(true);
482 mocks.connected.delete("env-a");
483 await screen.rerender(<Probe />);
484 expect(mocks.voice.setup.open).toBe(false);
485 mocks.connected.add("env-a");
486 await screen.rerender(<Probe />);
487 await act(() => mocks.voice.start());
488 expect(mocks.voice.setup).toMatchObject({ open: true, downloading: false, step: 0 });
489 finishDownload();
490 await act(async () => {
491 await done;
492 });
493 expect(mocks.voice.setup.error).toBeNull();
494});
495​
496function catalogModel(
497 id: string,
498 languages: readonly string[],
499 recommended: boolean,
500 errorPercent = 4,
501): EnvironmentSpeechModel {
502 return {
503 id,
504 name: id,
505 description: "",
506 size: 1,
507 languages,
508 accuracy: 0,
509 speed: 0,
510 recommended,
511 benchmark: {
512 accuracy: Object.fromEntries(
513 languages.map((language) => [language, { grade: "A", errorPercent }]),
514 ),
515 secondsPer30s: { accelerated: 2, cpu: 3 },
516 },
517 supportsStreaming: false,
518 supportsLanguageDetection: languages.length > 1,
519 supportsTranslation: false,
520 active: false,
521 state: "downloadable",
522 };
524​
525it.each([
526 ["the browser prefers German", ["de-DE"], undefined, "auto", "accelerated"],
527 ["the remote environment uses CPU", ["de-DE"], undefined, "auto", "cpu"],
528 ["the desktop exposes no locale methods", ["de-DE"], {}, "auto", "accelerated"],
529 [
530 "an older preload exposes only the OS locale",
531 ["en-US"],
532 { getSystemLocale: () => "de-DE" },
533 "auto",
534 "accelerated",
535 ],
536 [
537 "the desktop OS prefers German",
538 ["en-US"],
539 { getPreferredSystemLanguages: () => ["de-DE"] },
540 "auto",
541 "accelerated",
542 ],
543 ["German is the chosen Voice language", ["en-US"], undefined, "de", "accelerated"],
544])(
545 "offers and downloads a German-capable model when %s",
546 async (_, languages, bridge, speechLanguage, tier) => {
547 setup({ destination: "env-a" });
548 mocks.settings = { speechLanguage };
549 mocks.statusTier = tier as "cpu" | "accelerated";
550 using _languages = vi.spyOn(navigator, "languages", "get").mockReturnValue(languages);
551 using _bridge = stubGlobal("desktopBridge", bridge);
552 const englishDefault = "handy-computer/parakeet-unified-en-0.6b-gguf";
553 const german = "handy-computer/nemotron-3.5-asr-streaming-0.6b-gguf";
554 mocks.modelState = "missing-model";
555 mocks.statusModelId = englishDefault;
556 mocks.models = [
557 { ...catalogModel(englishDefault, ["en"], true), active: true },
558 catalogModel("handy-computer/canary-180m-flash-gguf", ["en", "de", "es", "fr"], true),
559 {
560 ...catalogModel(german, ["en", "de", "fr"], false, 2),
561 benchmark: {
562 accuracy: { de: { grade: "A", errorPercent: 2 } },
563 secondsPer30s: { cpu: 20, accelerated: 2 },
564 },
565 },
566 ];
567 mocks.download.mockResolvedValue(undefined);
568 await using _screen = await render(<Probe />);
569 await act(() => mocks.voice.start());
570 expect(mocks.voice.setup.open).toBe(true);
571 await act(() => mocks.voice.setup.download());
572 const expected = tier === "cpu" ? "handy-computer/canary-180m-flash-gguf" : german;
573 expect(mocks.download).toHaveBeenCalledExactlyOnceWith(expected);
574 expect(mocks.voice.setup.model?.id).toBe(expected);
575 expect(mocks.voice.setup.model?.recommended).toBe(true);
576 },
577);
578​
579it.each(["cancel", "failed restart"] as const)(
580 "closes pending catalog setup on %s",
581 async (action) => {
582 setup({ destination: "env-a" });
583 mocks.modelState = "missing-model";
584 mocks.settings = { speechLanguage: "en" };
585 mocks.models = [catalogModel("current", ["en"], true)];
586 const response = Deferred.makeUnsafe<{ models: EnvironmentSpeechModel[] }>();
587 vi.mocked(getEnvironmentSpeechModels).mockReturnValueOnce(Deferred.await(response));
588 await using _screen = await render(<Probe showWizard />);
589 let firstStart!: Promise<void>;
590 await act(() => {
591 firstStart = mocks.voice.start();
592 });
593 await expect.element(page.getByText("Loading transcription models…")).toBeVisible();
594 if (action === "cancel") {
595 await act(() => mocks.voice.cancel());
596 } else {
597 mocks.statusUnavailable = true;
598 await act(() => mocks.voice.start());
599 mocks.statusUnavailable = false;
600 }
601 expect(mocks.voice.setup.open).toBe(false);
602​
603 await act(() => mocks.voice.start());
604 Deferred.doneUnsafe(
605 response,
606 Effect.succeed({ models: [catalogModel("stale", ["en"], true)] }),
607 );
608 await act(() => firstStart);
609 await expect.element(page.getByRole("heading", { name: "current" })).toBeVisible();
610 expect(mocks.microphoneRequests).toEqual([]);
611 },
612);
613​
614it.each([true, false])(
615 "never downloads the English default when no German recommendation is available (catalog offline: %s)",
616 async (offline) => {
617 setup({ destination: "env-a" });
618 mocks.settings = { speechLanguage: "de" };
619 mocks.modelState = "missing-model";
620 mocks.statusModelId = "english";
621 mocks.models = [catalogModel("english", ["en"], true)];
622 mocks.catalogOffline = offline;
623 await using _screen = await render(<Probe showWizard />);
624 await act(() => mocks.voice.start());
625 const wizard = page.getByRole("dialog", { name: "Set up voice input" });
626 const retry = wizard.getByRole("button", { name: "Retry loading models" });
627 const download = wizard.getByRole("button", { name: "Download model" });
628 await expect.element(wizard.getByRole("alert")).toBeVisible();
629 await expect.element(download).not.toBeInTheDocument();
630 if (offline) {
631 mocks.catalogOffline = false;
632 mocks.models.push(catalogModel("german", ["de"], true));
633 // Another client can finish setup while the catalog is offline.
634 mocks.modelState = "ready";
635 mocks.statusTier = "accelerated";
636 await userEvent.click(retry);
637 await expect.element(wizard.getByRole("heading", { name: "german" })).toBeVisible();
638 await expect.element(download).toBeEnabled();
639 }
640 await expect.element(retry).not.toBeInTheDocument();
641 expect(mocks.download).not.toHaveBeenCalled();
642 expect(mocks.microphoneRequests).toEqual([]);
643 },
644);
645​
646it.each([
647 ["selects the offered model once its download installed it", "installed", ["german"], null],
648 [
649 "does not advance a cancelled download when another model is ready",
650 "downloadable",
651 [],
652 "The model is not ready. Try downloading it again.",
653 ],
654 [
655 "reports a failed selection apart from the download",
656 "installed",
657 ["german"],
658 "The model downloaded, but this environment could not select it. Try again.",
659 ],
660] as const)("%s", async (_, landedState, selected, error) => {
661 setup({ destination: "env-a" });
662 using _languages = vi.spyOn(navigator, "languages", "get").mockReturnValue(["de-DE"]);
663 mocks.selectionFails = error !== null && landedState === "installed";
664 mocks.modelState = "missing-model";
665 mocks.statusModelId = "english";
666 mocks.models = [catalogModel("english", ["en"], true), catalogModel("german", ["de"], true)];
667 mocks.download.mockImplementation(async () => {
668 mocks.models = [mocks.models[0]!, { ...mocks.models[1]!, state: landedState }];
669 mocks.modelState = "ready";
670 mocks.statusTier = "accelerated";
671 });
672 await using _screen = await render(<Probe />);
673 await act(() => mocks.voice.start());
674 expect(mocks.voice.setup.language).toBe("de");
675 await act(() => mocks.voice.setup.download());
676 expect(mocks.selected).toEqual(selected);
677 expect(mocks.voice.setup.error).toBe(error);
678 expect(mocks.voice.setup.downloading).toBe(false);
679 expect(mocks.voice.setup.step).toBe(landedState === "installed" && !error ? 1 : 0);
680});
681​
682it("does not resend a failed recording after consent is revoked", async () => {
683 setup({ destination: "env-a" });
684 mocks.transcripts = [new Error("inference failed")];
685 await using screen = await render(<Probe />);
686 await act(() => mocks.voice.start());
687 await act(() => mocks.voice.stop());
688 expect(mocks.voice.state.phase).toBe("error");
689 setDestination(null);
690 await screen.rerender(<Probe />);
691 await act(() => mocks.voice.start());
692 expect(mocks.transcribeCalls).toEqual(["env-a"]);
693 expect(mocks.microphoneRequests).toEqual(["env-a"]);
694 expect(mocks.committed).not.toHaveBeenCalled();
695});
696​
697it("revokes across windows even before the storage event and survives stale preference writes", async () => {
698 setup({ destination: "env-a" });
699 await using _screen = await render(<Probe />);
700 await act(() => mocks.voice.start());
701 expect(mocks.voice.state.phase).toBe("recording");
702 const other = document.createElement("iframe");
703 document.body.append(other);
704 try {
705 const storage = other.contentWindow!.localStorage;
706 const key = "t3code:voice-audio-grant:v1";
707 const grant = JSON.parse(storage.getItem(key)!) as { id: string };
708 const canSend = bindAudioGrant(grant.id);
709 expect(canSend()).toBe(true);
710 const saved = pendingCloudAudioChoice({
711 kind: "cloud",
712 provider: "openai",
713 environmentId: EnvironmentId.make("env-a"),
714 });
715 expect(canSend()).toBe(true);
716 storage.removeItem(key);
717 saved();
718 expect(storage.getItem(key)).toBeNull();
719 expect(canSend()).toBe(false);
720 writeBrowserClientSettings({ ...DEFAULT_CLIENT_SETTINGS, wordWrap: false });
721 await vi.waitFor(() => expect(mocks.voice.transcriptionEnvironmentId).toBeNull());
722 expect(mocks.voice.state.phase).toBe("idle");
723 await act(() => mocks.voice.stop());
724 expect(mocks.transcribeCalls).toEqual([]);
725 setDestination("env-a");
726 expect(canSend()).toBe(false);
727 } finally {
728 other.remove();
729 }
730});
731​
732it.each(["not-json", JSON.stringify("off")])(
733 "does not enable a pending provider over %s before the save completes",
734 async (previous) => {
735 setup();
736 mocks.cloudVoiceCapable.add("env-b");
737 mocks.modelState = "missing-model";
738 window.localStorage.setItem("t3code:voice-audio-grant:v1", previous);
739 const save = pendingCloudAudioChoice({
740 kind: "cloud",
741 environmentId: EnvironmentId.make("env-b"),
742 provider: "xai",
743 });
744 await using _screen = await render(<Probe />);
745 expect(mocks.voice.transcriptionEnvironmentId).toBeNull();
746 if (previous === JSON.stringify("off")) expect(mocks.voice.available).toBe(false);
747 await act(() => mocks.voice.start());
748 expectNoAudioSent();
749 await act(save);
750 await act(() => mocks.voice.start());
751 await act(() => mocks.voice.stop());
752 expect(mocks.transcribeCalls).toEqual(["xai via env-b"]);
753 expect(mocks.statusRequests).toEqual([]);
754 },
755);
756​
757it("sends audio to OpenRouter only under a device grant naming the exact model", async () => {
758 setup();
759 mocks.cloudVoiceCapable.add("env-b");
760 const key = "t3code:voice-audio-grant:v1";
761 const destination = { kind: "cloud", environmentId: "env-b", provider: "openrouter" };
762 window.localStorage.setItem(key, JSON.stringify({ id: "no-model", destination }));
763 {
764 await using _screen = await render(<Probe />);
765 await act(() => mocks.voice.start());
766 expectNoAudioSent();
767 }
768 const model = "acme/transcribe-1";
769 window.localStorage.setItem(
770 key,
771 JSON.stringify({ id: "model", destination: { ...destination, model } }),
772 );
773 await using _screen = await render(<Probe />);
774 await act(() => mocks.voice.start());
775 await act(() => mocks.voice.stop());
776 expect(mocks.transcribeCalls).toEqual([`openrouter:${model} via env-b`]);
777 expect(mocks.statusRequests).toEqual([]);
778});
779​
780it("uses neither destination when the cloud save marker cannot be read", async () => {
781 setup({ destination: "env-a" });
782 const key = "t3code:voice-audio-grant:v1";
783 const previous = JSON.parse(window.localStorage.getItem(key)!) as { id: string };
784 const canSendToPrevious = bindAudioGrant(previous.id);
785 const save = pendingCloudAudioChoice({
786 kind: "cloud",
787 environmentId: EnvironmentId.make("env-b"),
788 provider: "openai",
789 });
790 save();
791 const getItem = Storage.prototype.getItem;
792 using _blocked = vi.spyOn(Storage.prototype, "getItem").mockImplementation(function (
793 this: Storage,
794 k,
795 ) {
796 if (k.startsWith(`${key}:saved:`))
797 throw new DOMException("Storage is blocked", "SecurityError");
798 return getItem.call(this, k);
799 });
800 await using _screen = await render(<Probe />);
801 expect(mocks.voice.transcriptionEnvironmentId).toBeNull();
802 expect(canSendToPrevious()).toBe(false);
803 expect(mocks.voice.available).toBe(false);
804 await act(() => mocks.voice.start());
805 expectNoAudioSent();
806});
807​
808it("cleans text on a cloud-only draft environment only while cleanup is separately enabled", async () => {
809 setup({ destination: "env-a" });
810 mocks.voiceCapable.delete(THREAD_ENV);
811 mocks.cloudVoiceCapable.add(THREAD_ENV);
812 chooseTranscriptCleanup(true);
813 const nearby = "x".repeat(1_024);
814 mocks.draft = "unrelated private paragraph " + nearby;
815 await using screen = await render(<Probe />);
816 await act(() => mocks.voice.start());
817 await act(() => mocks.voice.stop());
818 expect(mocks.transcribeCalls).toEqual(["env-a"]);
819 expect(mocks.cleanupCalls).toEqual([THREAD_ENV]);
820 expect(mocks.cleanupDraft).toHaveBeenCalledExactlyOnceWith({
821 text: nearby,
822 selection: { start: nearby.length, end: nearby.length },
823 });
824 expect(mocks.committed).toHaveBeenCalledExactlyOnceWith(
825 mocks.draft + " Cleaned dictated",
826 expect.anything(),
827 );
828​
829 await act(() => mocks.voice.start());
830 chooseTranscriptCleanup(false);
831 await screen.rerender(<Probe />);
832 await act(() => mocks.voice.stop());
833 expect(mocks.cleanupCalls).toHaveLength(1);
834});
835​
836// The settings model test must show what the model heard, not what a provider rewrote.
837it.each([
838 { cleanup: false, authorized: true },
839 { cleanup: undefined, authorized: false },
840])(
841 "keeps a recording without authorized cleanup off the provider: $cleanup / $authorized",
842 async ({ cleanup, authorized }) => {
843 setup({ destination: "env-a" });
844 mocks.cloudVoiceCapable.add(THREAD_ENV);
845 chooseTranscriptCleanup(true);
846 mocks.settings.speechCorrectionWord = "sorry";
847 if (!authorized) mocks.canDictate.delete(THREAD_ENV);
848 mocks.projectWords = { "proj-1": [{ term: "Acme", aliases: ["ack me"] }] };
849 await using _screen = await render(
850 <Probe {...(cleanup === undefined ? {} : { cleanup })} projectId="proj-1" />,
851 );
852 await act(() => mocks.voice.start());
853 await act(() => mocks.voice.stop());
854 expect(mocks.cleanupCalls).toEqual([]);
855 expect(mocks.recordingOptions.at(-1)?.speechCustomWords).toEqual(mocks.projectWords["proj-1"]);
856 expect(mocks.recordingOptions.at(-1)?.speechCorrectionWord).toBeUndefined();
857 expect(mocks.transcribeCalls).toEqual(["env-a"]);
858 expect(mocks.committed).toHaveBeenCalledExactlyOnceWith("dictated", expect.anything());
859 },
860);
861​
862it("sends the project's vocabulary and name as hints, and the cue only with cleanup on", async () => {
863 setup({ destination: "env-a" });
864 mocks.settings.speechCustomWords = [{ term: "Effect", aliases: ["a fact"] }];
865 mocks.settings.speechCorrectionWord = "scratch that";
866 // Stored on the draft's environment under its project, never read from the audio destination.
867 mocks.projectWords = { "proj-1": [{ term: "effect", aliases: ["affect"] }] };
868 await using screen = await render(<Probe projectId="proj-1" projectName="Acme App" />);
869 await act(() => mocks.voice.start());
870 await act(() => mocks.voice.stop());
871 expect(mocks.recordingOptions.at(-1)?.speechCustomWords).toEqual([
872 { term: "Acme App", aliases: [] },
873 { term: "effect", aliases: ["affect"] },
874 ]);
875 expect(mocks.cleanupCalls).toEqual([]);
876​
877 chooseTranscriptCleanup(true);
878 await screen.rerender(<Probe projectId="proj-1" projectName="Acme App" />);
879 await act(() => mocks.voice.start());
880 await act(() => mocks.voice.stop());
881 expect(mocks.recordingOptions.at(-1)?.speechCustomWords.map(({ term }) => term)).toEqual([
882 "scratch that",
883 "Acme App",
884 "effect",
885 ]);
886 expect(mocks.cleanupOptions.at(-1)).toMatchObject({ speechCorrectionWord: "scratch that" });
887 expect(mocks.recordingOptions.at(-1)?.speechCorrectionWord).toBe("scratch that");
888 chooseTranscriptCleanup(false);
889 await act(() => mocks.voice.start());
890 await act(() => mocks.voice.stop());
891 expect(mocks.recordingOptions.at(-1)?.speechCorrectionWord).toBeUndefined();
892 expect(mocks.recordingOptions.at(-1)?.speechCustomWords.map(({ term }) => term)).not.toContain(
893 "scratch that",
894 );
895});
896​
897it("shares one status probe per destination across every mounted editor", async () => {
898 setup({ destination: "env-a" });
899 await using _screen = await render(
900 <>
901 <Probe />
902 <Probe />
903 <Probe />
904 </>,
905 );
906 expect(mocks.voice.available).toBe(true);
907 expect(mocks.statusRequests).toEqual(["env-a"]);
908});
909​
910it("lets the user retry after a status failure without reselecting the destination", async () => {
911 setup({ destination: "env-a" });
912 mocks.statusUnavailable = true;
913 await using _screen = await render(<Probe />);
914 expect(mocks.statusRequests).toEqual(["env-a"]);
915 expect(mocks.voice.available).toBe(true);
916 expect(mocks.microphoneRequests).toEqual([]);
917 mocks.statusUnavailable = false;
918 await act(() => mocks.voice.start());
919 await act(() => mocks.voice.stop());
920 expect(mocks.transcribeCalls).toEqual(["env-a"]);
921});