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

useEnvironmentSpeechInput.browser.test.tsx

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