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