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