Open History to see the last commit
1import {
2 BearerConnectionTarget,
3 PrimaryConnectionTarget,
4 RelayConnectionTarget,
5 type PreparedConnection,
6} from "@t3tools/client-runtime/connection";
7import type * as Effect from "effect/Effect";
8import {
9 EnvironmentId,
10 type EnvironmentSpeechModel,
11 type EnvironmentSpeechStatus,
12} from "@t3tools/contracts";
13import { expect, it, vi } from "vite-plus/test";
14import { userEvent } from "vite-plus/test/browser";
15import { act, render } from "../../../test/render";
16import { __setClientSettingsForTests, getClientSettings } from "../../hooks/useSettings";
17import { readBrowserClientSettings } from "../../clientPersistenceStorage";
18import { chooseRecordingMicrophone } from "../../speech/browserMicrophones";
19import {
20 useEnvironmentSpeechInput,
21 useVoiceTranscriptionDestination,
22} from "../../speech/useEnvironmentSpeechInput";
23import { chooseAudioDestination, chooseTranscriptCleanup } from "../../speech/voiceConsent";
24import { useEnvironmentScope } from "../../state/session";
25import { AppRouteModal } from "../AppRouteModal";
26import { toastManager } from "../ui/toast";
27import { SettingsScopeProvider } from "./SettingsScopeContext";
28import { SpeechLanguageSelect } from "./SpeechLanguageSelect";
29import { VoiceSettingsPanel } from "./VoiceSettingsPanel";
30
31vi.mock(import("../../speech/useEnvironmentSpeechInput"), { spy: true });
32vi.mock(import("../../state/session"), { spy: true });
33
34// The real connection runtime authorizes relay requests with a signed-in cloud session.
35vi.mock("../../connection/runtime", async () => {
36 const [{ ManagedRelay }, rpc, { Atom }, Context, Effect, Layer] = await Promise.all([
37 import("@t3tools/client-runtime/relay"),
38 import("@t3tools/client-runtime/rpc"),
39 import("effect/reactivity"),
40 import("effect/Context"),
41 import("effect/Effect"),
42 import("effect/Layer"),
43 ]);
44 type AuthorizedHttp =
45 import("@t3tools/client-runtime/authorization").AuthorizedRemoteHttpEnvironment;
46 // Services resolve by key, and client-runtime does not export this one.
47 class RemoteEnvironmentAuthorization extends Context.Service<
48 RemoteEnvironmentAuthorization,
49 {
50 readonly authorizeDpopHttp: (input: {
51 readonly expectedEnvironmentId: AuthorizedHttp["environmentId"];
52 }) => Effect.Effect<AuthorizedHttp>;
53 }
54 // @effect-diagnostics-next-line deterministicKeys:off
55 >()("@t3tools/client-runtime/authorization/service/RemoteEnvironmentAuthorization") {}
56 return {
57 connectionAtomRuntime: Atom.runtime(
58 Layer.mergeAll(
59 rpc.layerRemoteHttpClient((input, init) => globalThis.fetch(input, init)),
60 Layer.succeed(ManagedRelay.ManagedRelayDpopSigner, {
61 thumbprint: Effect.succeed("thumbprint"),
62 createProof: () => Effect.succeed("proof"),
63 }),
64 Layer.succeed(RemoteEnvironmentAuthorization, {
65 authorizeDpopHttp: ({ expectedEnvironmentId }) =>
66 Effect.succeed({
67 environmentId: expectedEnvironmentId,
68 label: "MacBook Pro",
69 httpBaseUrl: window.location.origin,
70 httpAuthorization: {
71 _tag: "Dpop",
72 accessToken: "relay-access-token",
73 expiresAtEpochMs: 4_102_444_800_000,
74 },
75 }),
76 }),
77 ),
78 ),
79 };
80});
81
82function deferred<T>() {
83 let resolve!: (value: T) => void;
84 const promise = new Promise<T>((done) => {
85 resolve = done;
86 });
87 return { promise, resolve };
88}
89
90it.each([{ cpu: null, accelerated: 2.1 }, { cpu: 5, accelerated: null }, { accelerated: 2.1 }])(
91 "uses the destination environment's benchmark tier across switches with measurements %j",
92 async (secondsPer30s) => {
93 const target = new PrimaryConnectionTarget({
94 environmentId: EnvironmentId.make("voice-local"),
95 label: "Local CPU",
96 httpBaseUrl: window.location.origin,
97 wsBaseUrl: "ws://localhost",
98 });
99 const local: PreparedConnection = {
100 ...target,
101 target,
102 socketUrl: target.wsBaseUrl,
103 httpAuthorization: null,
104 };
105 const remote: PreparedConnection = {
106 environmentId: EnvironmentId.make("voice-remote"),
107 label: "Remote GPU",
108 httpBaseUrl: "https://voice.example.test",
109 socketUrl: "wss://voice.example.test/ws",
110 httpAuthorization: { _tag: "Bearer", token: "test-token" },
111 target: new BearerConnectionTarget({
112 environmentId: EnvironmentId.make("voice-remote"),
113 label: "Remote GPU",
114 connectionId: "remote",
115 }),
116 };
117 let prepared = local;
118 const remoteStatus = deferred<Response>();
119 const remoteRequested = deferred<void>();
120 const status = {
121 supported: true,
122 state: "ready",
123 modelId: "both",
124 model: "Bilingual",
125 size: 100,
126 supportsStreaming: true,
127 supportsTranslation: false,
128 acceleration: "auto",
129 modelUnloadTimeout: "never",
130 gpuDevices: [],
131 benchmarkTier: "cpu",
132 } satisfies EnvironmentSpeechStatus;
133 const model: EnvironmentSpeechModel = {
134 id: "both",
135 name: "Bilingual",
136 description: "",
137 size: 100,
138 languages: ["en"],
139 accuracy: 1,
140 speed: 1,
141 recommended: true,
142 supportsStreaming: false,
143 supportsTranslation: false,
144 supportsLanguageDetection: false,
145 active: false,
146 state: "downloadable",
147 benchmark: {
148 accuracy: { en: { grade: "A-", errorPercent: 4 } },
149 secondsPer30s,
150 },
151 };
152 const cpuBenchmark = `Speed: ${secondsPer30s.cpu === undefined ? "update server for this benchmark" : secondsPer30s.cpu === null ? "not benchmarked" : `${secondsPer30s.cpu} s / 30 s`}`;
153 const gpuBenchmark = `Speed: ${secondsPer30s.accelerated === null ? "not benchmarked" : `${secondsPer30s.accelerated} s / 30 s`}`;
154 const fetch = globalThis.fetch;
155 using _network = vi.spyOn(globalThis, "fetch").mockImplementation((input, init) => {
156 const url = new URL(input instanceof Request ? input.url : input, window.location.href);
157 if (url.pathname === "/api/voice/status") {
158 if (url.origin === remote.httpBaseUrl) {
159 remoteRequested.resolve();
160 return remoteStatus.promise;
161 }
162 return Promise.resolve(Response.json(status));
163 }
164 if (url.pathname === "/api/voice/models")
165 return Promise.resolve(Response.json({ models: [model] }));
166 return fetch(input, init);
167 });
168 await vi.mocked(useVoiceTranscriptionDestination).withImplementation(
169 () => ({
170 environmentId: prepared.environmentId,
171 label: prepared.label,
172 grantId: "test",
173 prepared,
174 }),
175 async () => {
176 const previous = getClientSettings();
177 using cleanup = new DisposableStack();
178 cleanup.defer(() => __setClientSettingsForTests(previous));
179 __setClientSettingsForTests({ ...previous, speechStreaming: true });
180 const panel = () => (
181 <SettingsScopeProvider search={{}} onChange={() => {}}>
182 <VoiceSettingsPanel />
183 </SettingsScopeProvider>
184 );
185 await using screen = await render(panel());
186 await expect.element(screen.getByText(cpuBenchmark)).toBeVisible();
187 await userEvent.click(screen.getByRole("button", { name: "Advanced", exact: true }));
188 const streaming = screen.getByRole("switch", { name: "Streaming transcription" });
189 await expect.element(streaming).toBeEnabled();
190 await expect.element(streaming).toBeChecked();
191 streaming.element().focus();
192 await userEvent.keyboard(" ");
193 await vi.waitFor(() => expect(readBrowserClientSettings()?.speechStreaming).toBe(false));
194 prepared = remote;
195 await screen.rerender(panel());
196 await remoteRequested.promise;
197 await expect.element(screen.getByText(cpuBenchmark)).not.toBeInTheDocument();
198 remoteStatus.resolve(
199 Response.json({
200 ...status,
201 supportsStreaming: false,
202 benchmarkTier: "accelerated",
203 gpuDevices: [{ id: "gpu", name: "Remote GPU" }],
204 }),
205 );
206 await expect.element(screen.getByText(gpuBenchmark)).toBeVisible();
207 await userEvent.click(screen.getByRole("button", { name: "Advanced", exact: true }));
208 await expect.element(streaming).toBeDisabled();
209 await expect.element(streaming).not.toBeChecked();
210 await expect
211 .element(screen.getByText("This model doesn’t support native streaming."))
212 .toBeVisible();
213 prepared = local;
214 await screen.rerender(panel());
215 await expect.element(screen.getByText(cpuBenchmark)).toBeVisible();
216 await userEvent.click(screen.getByRole("button", { name: "Advanced", exact: true }));
217 await expect.element(screen.getByText(gpuBenchmark)).not.toBeInTheDocument();
218 await expect.element(streaming).toBeEnabled();
219 await expect.element(streaming).not.toBeChecked();
220 streaming.element().focus();
221 await userEvent.keyboard(" ");
222 await vi.waitFor(() => expect(readBrowserClientSettings()?.speechStreaming).toBe(true));
223 },
224 );
225 },
226);
227
228it("tests the selected model after download and preserves its transcript across filters", async () => {
229 const target = new PrimaryConnectionTarget({
230 environmentId: EnvironmentId.make("voice-filter"),
231 label: "Test environment",
232 httpBaseUrl: window.location.origin,
233 wsBaseUrl: "ws://localhost",
234 });
235 const prepared = { ...target, target, socketUrl: target.wsBaseUrl, httpAuthorization: null };
236 const model: EnvironmentSpeechModel = {
237 id: "tiny",
238 name: "Tiny",
239 description: "",
240 size: 100,
241 languages: ["en"],
242 accuracy: 1,
243 speed: 1,
244 recommended: false,
245 supportsStreaming: false,
246 supportsTranslation: false,
247 supportsLanguageDetection: false,
248 active: true,
249 state: "installed",
250 };
251 const status = {
252 supported: true,
253 state: "ready",
254 modelId: model.id,
255 model: model.name,
256 size: model.size,
257 supportsStreaming: false,
258 supportsTranslation: false,
259 acceleration: "cpu",
260 benchmarkTier: "cpu",
261 modelUnloadTimeout: "never",
262 gpuDevices: [],
263 } satisfies EnvironmentSpeechStatus;
264 let installed = false;
265 const fetch = globalThis.fetch;
266 using _network = vi.spyOn(globalThis, "fetch").mockImplementation((input, init) => {
267 const url = new URL(input instanceof Request ? input.url : input, window.location.href);
268 if (url.pathname === "/api/voice/status")
269 return Promise.resolve(
270 Response.json(installed ? status : { ...status, state: "missing-model" }),
271 );
272 if (url.pathname === "/api/voice/models/download") {
273 installed = true;
274 return Promise.resolve(Response.json({ models: [model] }));
275 }
276 if (url.pathname === "/api/voice/models")
277 return Promise.resolve(
278 Response.json({
279 models: [
280 installed ? model : { ...model, state: "downloadable", active: false },
281 {
282 ...model,
283 id: "both",
284 name: "Bilingual",
285 active: false,
286 languages: ["en", "fr"],
287 ...(url.searchParams.has("benchmarks")
288 ? {
289 benchmark: {
290 accuracy: {
291 en: { grade: "A-", errorPercent: 4 },
292 fr: { grade: "B+", errorPercent: 5.5 },
293 },
294 secondsPer30s: { accelerated: 2.1, cpu: 5 },
295 },
296 }
297 : {}),
298 },
299 ],
300 }),
301 );
302 return fetch(input, init);
303 });
304 const transcript = "Keep this transcript.";
305 using _scope = vi.mocked(useEnvironmentScope).mockReturnValue(true);
306 await vi.mocked(useVoiceTranscriptionDestination).withImplementation(
307 () => ({ environmentId: target.environmentId, label: target.label, grantId: "test", prepared }),
308 async () => {
309 await vi.mocked(useEnvironmentSpeechInput).withImplementation(
310 (input) => ({
311 available: true,
312 status,
313 transcriptionEnvironmentId: target.environmentId,
314 transcriptionEnvironmentLabel: target.label,
315 setup: {
316 open: false,
317 step: 0,
318 model: null,
319 language: null,
320 downloading: false,
321 catalogFailed: false,
322 retryCatalog: null,
323 error: null,
324 setOpen: () => {},
325 download: async () => {},
326 cancelDownload: async () => {},
327 startRecording: async () => {},
328 },
329 state: { phase: "idle", error: null, errorAction: null },
330 preview: null,
331 level: 0,
332 recordingStartedAt: null,
333 preparing: false,
334 blocksSubmission: false,
335 freezesEditor: false,
336 start: async () => {
337 input.commitDraft(transcript, { start: transcript.length, end: transcript.length });
338 },
339 submitAfterDictation: () => {},
340 stop: async () => {},
341 cancel: () => {},
342 skipPostProcessing: () => {},
343 }),
344 async () => {
345 await using screen = await render(
346 <SettingsScopeProvider search={{}} onChange={() => {}}>
347 <VoiceSettingsPanel />
348 </SettingsScopeProvider>,
349 );
350 const testModel = screen.getByRole("button", { name: "Test model", exact: true });
351 const download = screen.getByRole("button", { name: "Download", exact: true });
352 await expect.element(download).toBeVisible();
353 expect(testModel.query()).toBeNull();
354 expect(screen.getByRole("button", { name: "Set up voice input" }).query()).toBeNull();
355 await userEvent.click(download);
356 await expect.element(testModel).toBeVisible();
357 expect(screen.getByRole("button", { name: "Set up voice input" }).query()).toBeNull();
358 await userEvent.click(testModel);
359 const result = screen.getByRole("status", { name: "Test transcript" });
360 await expect.element(result).toHaveTextContent(transcript);
361
362 const search = screen.getByRole("searchbox", { name: "Search transcription models" });
363 await userEvent.fill(search, "no matching model");
364 await expect.element(screen.getByText("No models match.")).toBeVisible();
365 await userEvent.clear(search);
366 const languages = screen.getByRole("button", { name: /^Filter by language/ });
367 const languageSearch = screen.getByRole("textbox", { name: "Search languages" });
368 await userEvent.click(languages);
369 await userEvent.fill(languageSearch, "fr");
370 const french = screen.getByRole("menuitemcheckbox", { name: "French", exact: true });
371 await userEvent.click(french);
372 await userEvent.keyboard("{Escape}");
373 await expect.element(screen.getByText("Bilingual", { exact: true })).toBeVisible();
374 await expect.element(screen.getByText("B+", { exact: true })).toBeVisible();
375 expect(screen.container.querySelector("#transcription-test")).toHaveAttribute("hidden");
376 await userEvent.click(languages);
377 await expect.element(languageSearch).toHaveValue("");
378 await expect
379 .element(screen.getByRole("menuitemcheckbox", { name: "All languages", exact: true }))
380 .toBeVisible();
381 await userEvent.fill(languageSearch, "fr");
382 await userEvent.click(french);
383 await userEvent.keyboard("{Escape}");
384 await expect.element(result).toBeVisible();
385 await vi.waitFor(() =>
386 expect(
387 screen.container.querySelector('[aria-label="Test transcript"]')?.textContent,
388 ).toBe(transcript),
389 );
390 },
391 );
392 },
393 );
394});
395
396it.each([
397 { tier: "cpu", legacy: false },
398 { tier: "accelerated", legacy: false },
399 { tier: "cpu", legacy: true },
400] as const)(
401 "loads relay models using the server tier $tier (legacy: $legacy)",
402 async ({ tier, legacy }) => {
403 const target = new RelayConnectionTarget({
404 environmentId: EnvironmentId.make("voice-relay"),
405 label: "MacBook Pro",
406 });
407 const prepared = {
408 environmentId: target.environmentId,
409 label: target.label,
410 httpBaseUrl: window.location.origin,
411 socketUrl: "ws://localhost",
412 httpAuthorization: {
413 _tag: "Dpop" as const,
414 accessToken: "stale-access-token",
415 expiresAtEpochMs: 4_102_444_800_000,
416 },
417 target,
418 };
419 const model = {
420 id: "gpu",
421 name: "GPU pick",
422 description: "",
423 size: 100,
424 languages: ["en"],
425 benchmark: {
426 accuracy: { en: { grade: "A", errorPercent: 4 } },
427 secondsPer30s: { cpu: 20, accelerated: 1 },
428 },
429 accuracy: 1,
430 speed: 1,
431 recommended: false,
432 supportsStreaming: false,
433 supportsTranslation: false,
434 supportsLanguageDetection: false,
435 active: false,
436 state: "downloadable",
437 } satisfies EnvironmentSpeechModel;
438 const status = {
439 supported: true,
440 state: "missing-model",
441 modelId: model.id,
442 model: model.name,
443 size: model.size,
444 supportsStreaming: false,
445 supportsTranslation: false,
446 acceleration: "auto",
447 benchmarkTier: tier,
448 modelUnloadTimeout: "never",
449 gpuDevices: [{ id: "remote-gpu", name: "Remote GPU" }],
450 } satisfies EnvironmentSpeechStatus;
451 const cpuModel = {
452 ...model,
453 id: "cpu",
454 name: "CPU pick",
455 benchmark: {
456 accuracy: { en: { grade: "B+", errorPercent: 6 } },
457 secondsPer30s: { cpu: 1, accelerated: 8 },
458 },
459 };
460 const { benchmarkTier: _tier, ...legacyStatus } = status;
461 const models = [model, cpuModel];
462 const authorizations: Array<string | null> = [];
463 const fetch = globalThis.fetch;
464 using _network = vi.spyOn(globalThis, "fetch").mockImplementation((input, init) => {
465 const url = new URL(input instanceof Request ? input.url : input, window.location.href);
466 if (url.pathname === "/api/voice/status") {
467 authorizations.push(new Headers(init?.headers).get("authorization"));
468 return Promise.resolve(
469 Response.json(legacy ? { ...legacyStatus, acceleration: "cpu", gpuDevices: [] } : status),
470 );
471 }
472 if (url.pathname === "/api/voice/models")
473 return Promise.resolve(
474 Response.json({
475 models: legacy
476 ? models.map(({ benchmark, ...entry }) => ({
477 ...entry,
478 benchmark: {
479 accuracy: benchmark.accuracy,
480 secondsPer30s: benchmark.secondsPer30s.accelerated,
481 },
482 }))
483 : models,
484 }),
485 );
486 return fetch(input, init);
487 });
488 using notify = vi.spyOn(toastManager, "add").mockReturnValue("test");
489 // Restored even when an assertion fails, unlike `withImplementation`.
490 using _destination = vi.mocked(useVoiceTranscriptionDestination).mockImplementation(() => ({
491 environmentId: target.environmentId,
492 label: target.label,
493 grantId: "test",
494 prepared,
495 }));
496 await using screen = await render(
497 <SettingsScopeProvider search={{}} onChange={() => {}}>
498 <VoiceSettingsPanel />
499 </SettingsScopeProvider>,
500 );
501 await vi.waitFor(() => expect(authorizations.length + notify.mock.calls.length).not.toBe(0));
502 expect(notify).not.toHaveBeenCalled();
503 expect(authorizations).toEqual(["DPoP relay-access-token"]);
504 const region = screen.getByRole("region", { name: "Transcription models" });
505 await vi.waitFor(() => expect(region.element().textContent).toContain("CPU pick"));
506 if (legacy) {
507 expect(region.element().textContent).toContain("update server for this benchmark");
508 expect(region.element().textContent).not.toContain("Recommended");
509 } else {
510 const winner = tier === "cpu" ? "CPU pick" : "GPU pick";
511 await vi.waitFor(() =>
512 expect(region.element().firstElementChild?.textContent).toContain(winner + "Recommended"),
513 );
514 expect(region.element().textContent).toContain("Speed: 1 s / 30 s");
515 }
516 },
517);
518
519it("recovers from a failed download progress poll without notifying, but reports a failed initial load", async () => {
520 const target = new PrimaryConnectionTarget({
521 environmentId: EnvironmentId.make("voice-progress"),
522 label: "Test environment",
523 httpBaseUrl: window.location.origin,
524 wsBaseUrl: "ws://localhost",
525 });
526 const prepared = { ...target, target, socketUrl: target.wsBaseUrl, httpAuthorization: null };
527 const model: EnvironmentSpeechModel = {
528 id: "tiny",
529 name: "Tiny",
530 description: "",
531 size: 100,
532 languages: ["en"],
533 accuracy: 1,
534 speed: 1,
535 recommended: false,
536 supportsStreaming: false,
537 supportsTranslation: false,
538 supportsLanguageDetection: false,
539 active: false,
540 state: "downloading",
541 };
542 const status = {
543 supported: true,
544 state: "missing-model",
545 modelId: model.id,
546 model: model.name,
547 size: model.size,
548 supportsStreaming: false,
549 supportsTranslation: false,
550 acceleration: "cpu",
551 benchmarkTier: "cpu",
552 modelUnloadTimeout: "never",
553 gpuDevices: [],
554 };
555 const unavailable = () => new Response(null, { status: 503 });
556 const readModels = vi
557 .fn((_withBenchmarks: boolean) => unavailable())
558 .mockImplementationOnce(() => Response.json({ models: [model] }))
559 .mockImplementationOnce(unavailable)
560 .mockImplementationOnce(() => Response.json({ models: [{ ...model, state: "installed" }] }));
561 const fetch = globalThis.fetch;
562 using _network = vi.spyOn(globalThis, "fetch").mockImplementation((input, init) => {
563 const url = new URL(input instanceof Request ? input.url : input, window.location.href);
564 if (url.pathname === "/api/voice/status") return Promise.resolve(Response.json(status));
565 if (url.pathname === "/api/voice/models")
566 return Promise.resolve(readModels(url.searchParams.has("benchmarks")));
567 return fetch(input, init);
568 });
569 using notify = vi.spyOn(toastManager, "add").mockReturnValue("test");
570 await vi.mocked(useVoiceTranscriptionDestination).withImplementation(
571 () => ({ environmentId: target.environmentId, label: target.label, grantId: "test", prepared }),
572 async () => {
573 const panel = (key: string) => (
574 <SettingsScopeProvider search={{}} onChange={() => {}}>
575 <VoiceSettingsPanel key={key} />
576 </SettingsScopeProvider>
577 );
578 await using screen = await render(panel("first"));
579 await expect.element(screen.getByRole("button", { name: "Use model" })).toBeVisible();
580 expect(readModels.mock.calls.map(([withBenchmarks]) => withBenchmarks)).toEqual([
581 true,
582 false,
583 false,
584 ]);
585 expect(notify).not.toHaveBeenCalled();
586 await screen.rerender(panel("reopened"));
587 await vi.waitFor(() =>
588 expect(notify).toHaveBeenCalledWith(
589 expect.objectContaining({ title: "Could not load transcription models" }),
590 ),
591 );
592 },
593 );
594});
595
596it.each([
597 ["speech-models", "voice-transcription-destination"],
598 ["speech-hardware", "voice-transcription-destination"],
599 ["speech-streaming", "voice-transcription-destination"],
600 ["transcription-test", "voice-transcription-destination"],
601 ["speech-correction-word", "speech-post-processing"],
602 ["speech-post-processing-model", "speech-post-processing"],
603])(
604 "searching for disabled %s focuses its opt-in without enabling it",
605 async (target, prerequisite) => {
606 chooseAudioDestination(null);
607 chooseTranscriptCleanup(false);
608 await using screen = await render(
609 <SettingsScopeProvider search={{}} onChange={() => {}}>
610 <VoiceSettingsPanel />
611 </SettingsScopeProvider>,
612 { router: `/#${target}` },
613 );
614 await vi.waitFor(() => expect(document.activeElement?.id).toBe(prerequisite));
615 await expect
616 .element(screen.getByRole("combobox", { name: "Transcribe with" }))
617 .toHaveTextContent("Off");
618 await expect
619 .element(screen.getByRole("switch", { name: "Clean up transcripts" }))
620 .not.toBeChecked();
621 },
622);
623
624it("keeps a missing destination selected without claiming it cannot transcribe", async () => {
625 __setClientSettingsForTests(getClientSettings());
626 using cleanup = new DisposableStack();
627 cleanup.defer(() => chooseAudioDestination(null));
628 chooseAudioDestination({ kind: "environment", environmentId: EnvironmentId.make("missing") });
629 await using screen = await render(
630 <SettingsScopeProvider search={{}} onChange={() => {}}>
631 <VoiceSettingsPanel />
632 </SettingsScopeProvider>,
633 );
634 await expect
635 .element(screen.getByRole("combobox", { name: "Transcribe with" }))
636 .toHaveTextContent("Chosen environment (unavailable)");
637 await expect.element(screen.getByText(/can’t transcribe audio/)).not.toBeInTheDocument();
638});
639
640it("shows the model's effective language and restores the saved preference when supported again", async () => {
641 const previous = getClientSettings();
642 using cleanup = new DisposableStack();
643 cleanup.defer(() => __setClientSettingsForTests(previous));
644 __setClientSettingsForTests({ ...previous, speechLanguage: "fr" });
645 await using screen = await render(<SpeechLanguageSelect model={{ languages: ["en"] }} />);
646 const picker = screen.getByRole("combobox", { name: "Transcription language" });
647 await expect.element(picker).toHaveTextContent("English (French unavailable)");
648 await screen.rerender(
649 <SpeechLanguageSelect model={{ languages: ["en", "de"], supportsLanguageDetection: true }} />,
650 );
651 await expect.element(picker).toHaveTextContent("Auto-detect (French unavailable)");
652 await screen.rerender(<SpeechLanguageSelect model={{ languages: ["en", "fr"] }} />);
653 await expect.element(picker).toHaveTextContent("French");
654 expect(getClientSettings().speechLanguage).toBe("fr");
655});
656
657it("keeps punctuation in a saved dictionary term and its alias", async () => {
658 const previous = getClientSettings();
659 using cleanup = new DisposableStack();
660 cleanup.defer(() => __setClientSettingsForTests(previous));
661 __setClientSettingsForTests({ ...previous, speechCustomWords: [] });
662 await using screen = await render(
663 <SettingsScopeProvider search={{}} onChange={() => {}}>
664 <VoiceSettingsPanel />
665 </SettingsScopeProvider>,
666 );
667 await userEvent.type(
668 screen.getByRole("textbox", { name: "Add a word or phrase to the dictionary" }),
669 "O'Reilly{Enter}",
670 );
671 expect(getClientSettings().speechCustomWords[0]?.term).toBe("O'Reilly");
672 await userEvent.click(screen.getByRole("button", { name: "Add an alias for O'Reilly" }));
673 await userEvent.type(
674 screen.getByRole("textbox", { name: "Alias for O'Reilly" }),
675 '"Oh Really"{Enter}',
676 );
677 expect(getClientSettings().speechCustomWords).toEqual([
678 { term: "O'Reilly", aliases: ['"Oh Really"'] },
679 ]);
680});
681
682it("keeps a dictionary term and alias draft on the Enter that confirms an IME candidate", async () => {
683 const previous = getClientSettings();
684 using cleanup = new DisposableStack();
685 cleanup.defer(() => __setClientSettingsForTests(previous));
686 __setClientSettingsForTests({
687 ...previous,
688 speechCustomWords: [{ term: "日本語", aliases: [] }],
689 });
690 await using screen = await render(
691 <SettingsScopeProvider search={{}} onChange={() => {}}>
692 <VoiceSettingsPanel />
693 </SettingsScopeProvider>,
694 );
695 const composingEnter = () =>
696 new KeyboardEvent("keydown", { key: "Enter", isComposing: true, bubbles: true });
697 const term = screen.getByRole("textbox", { name: "Add a word or phrase to the dictionary" });
698 await userEvent.fill(term, "にほん");
699 term.element().dispatchEvent(composingEnter());
700 await expect.element(term).toHaveValue("にほん");
701 await userEvent.click(screen.getByRole("button", { name: "Add an alias for 日本語" }));
702 const alias = screen.getByRole("textbox", { name: "Alias for 日本語" });
703 await userEvent.fill(alias, "にほん");
704 alias.element().dispatchEvent(composingEnter());
705 expect(getClientSettings().speechCustomWords).toEqual([{ term: "日本語", aliases: [] }]);
706 await expect.element(alias).toHaveValue("にほん");
707});
708
709it("cancels an alias draft on Esc without closing Settings", async () => {
710 const previous = getClientSettings();
711 using cleanup = new DisposableStack();
712 cleanup.defer(() => __setClientSettingsForTests(previous));
713 __setClientSettingsForTests({
714 ...previous,
715 speechCustomWords: [{ term: "Kubernetes", aliases: [] }],
716 });
717 await using screen = await render(
718 <AppRouteModal label="Settings">
719 <SettingsScopeProvider search={{}} onChange={() => {}}>
720 <VoiceSettingsPanel />
721 </SettingsScopeProvider>
722 </AppRouteModal>,
723 { router: "/settings/voice" },
724 );
725 const settings = screen.getByRole("dialog", { name: "Settings" });
726 const addAlias = screen.getByRole("button", { name: "Add an alias for Kubernetes" });
727 await expect.element(addAlias).toBeVisible();
728 (addAlias.element() as HTMLElement).focus();
729 await userEvent.keyboard("{Enter}");
730 const alias = screen.getByRole("textbox", { name: "Alias for Kubernetes" });
731 await expect.element(alias).toHaveFocus();
732 await userEvent.keyboard("cooper");
733
734 await userEvent.keyboard("{Escape}");
735
736 await expect.element(alias).not.toBeInTheDocument();
737 await expect.element(settings).toHaveAttribute("data-open");
738 await expect.element(settings).toHaveFocus();
739 expect(getClientSettings().speechCustomWords).toEqual([{ term: "Kubernetes", aliases: [] }]);
740
741 await userEvent.keyboard("{Escape}");
742
743 await expect.element(settings).not.toBeInTheDocument();
744});
745
746it("clears the transcription model search on Esc without closing Settings", async () => {
747 const target = new PrimaryConnectionTarget({
748 environmentId: EnvironmentId.make("voice-search-escape"),
749 label: "Test environment",
750 httpBaseUrl: window.location.origin,
751 wsBaseUrl: "ws://localhost",
752 });
753 const prepared = { ...target, target, socketUrl: target.wsBaseUrl, httpAuthorization: null };
754 const model: EnvironmentSpeechModel = {
755 id: "tiny",
756 name: "Tiny",
757 description: "",
758 size: 100,
759 languages: ["en"],
760 accuracy: 1,
761 speed: 1,
762 recommended: true,
763 supportsStreaming: false,
764 supportsTranslation: false,
765 supportsLanguageDetection: false,
766 active: false,
767 state: "downloadable",
768 };
769 const status = {
770 supported: true,
771 state: "missing-model",
772 modelId: model.id,
773 model: model.name,
774 size: model.size,
775 supportsStreaming: false,
776 supportsTranslation: false,
777 acceleration: "cpu",
778 benchmarkTier: "cpu",
779 modelUnloadTimeout: "never",
780 gpuDevices: [],
781 } satisfies EnvironmentSpeechStatus;
782 const fetch = globalThis.fetch;
783 using _network = vi.spyOn(globalThis, "fetch").mockImplementation((input, init) => {
784 const url = new URL(input instanceof Request ? input.url : input, window.location.href);
785 if (url.pathname === "/api/voice/status") return Promise.resolve(Response.json(status));
786 if (url.pathname === "/api/voice/models")
787 return Promise.resolve(Response.json({ models: [model] }));
788 return fetch(input, init);
789 });
790 await vi.mocked(useVoiceTranscriptionDestination).withImplementation(
791 () => ({ environmentId: target.environmentId, label: target.label, grantId: "test", prepared }),
792 async () => {
793 await using screen = await render(
794 <AppRouteModal label="Settings">
795 <SettingsScopeProvider search={{}} onChange={() => {}}>
796 <VoiceSettingsPanel />
797 </SettingsScopeProvider>
798 </AppRouteModal>,
799 { router: "/settings/voice" },
800 );
801 const settings = screen.getByRole("dialog", { name: "Settings" });
802 const search = screen.getByRole("searchbox", { name: "Search transcription models" });
803 await expect.element(search).toBeVisible();
804
805 await userEvent.fill(search, "tiny");
806 for (const composition of [
807 { key: "Escape", isComposing: true, keyCode: 27 },
808 { key: "Escape", isComposing: false, keyCode: 229 },
809 ]) {
810 // Safari ends the composition just before the Escape keydown.
811 await act(() => {
812 search.element().dispatchEvent(new CompositionEvent("compositionend", { bubbles: true }));
813 search
814 .element()
815 .dispatchEvent(
816 new KeyboardEvent("keydown", { ...composition, bubbles: true, cancelable: true }),
817 );
818 });
819 await expect.element(search).toHaveValue("tiny");
820 await expect.element(settings).toHaveAttribute("data-open");
821 }
822
823 await userEvent.keyboard("{Escape}");
824 await expect.element(search).toHaveValue("");
825 await expect.element(search).toHaveFocus();
826 // Holding Escape repeats the keydown, which must not also close Settings.
827 await act(() => {
828 search.element().dispatchEvent(
829 new KeyboardEvent("keydown", {
830 key: "Escape",
831 repeat: true,
832 bubbles: true,
833 cancelable: true,
834 }),
835 );
836 });
837 await expect.element(settings).toHaveAttribute("data-open");
838
839 await userEvent.keyboard("{Escape}");
840 await expect.element(settings).not.toBeInTheDocument();
841 },
842 );
843});
844
845it("records from the first connected microphone in the saved order", async () => {
846 const previous = getClientSettings();
847 using cleanup = new DisposableStack();
848 cleanup.defer(() => __setClientSettingsForTests(previous));
849 // A single saved microphone from before the order existed comes first.
850 __setClientSettingsForTests({ ...previous, voiceMicrophone: "yeti", voiceMicrophones: [] });
851 const input = (deviceId: string, label: string) =>
852 ({ deviceId, label, groupId: deviceId, kind: "audioinput" }) as MediaDeviceInfo;
853 const yeti = input("yeti", "Blue Yeti");
854 const airpods = input("airpods", "AirPods Pro");
855 using devices = vi
856 .spyOn(navigator.mediaDevices, "enumerateDevices")
857 .mockResolvedValue([yeti, airpods]);
858 const saved = () =>
859 getClientSettings().voiceMicrophones.map((entry) =>
860 entry.kind === "default" ? "System default" : entry.label,
861 );
862 await using screen = await render(
863 <SettingsScopeProvider search={{}} onChange={() => {}}>
864 <VoiceSettingsPanel />
865 </SettingsScopeProvider>,
866 );
867 const list = screen.getByRole("list", { name: "Microphones, preferred first" });
868 await expect.poll(saved).toEqual(["Blue Yeti", "System default", "AirPods Pro"]);
869 const row = (index: number) => list.getByRole("listitem").nth(index);
870 await expect.element(row(0)).toHaveTextContent("1Blue YetiIn use");
871 expect(await chooseRecordingMicrophone()).toBe("yeti");
872
873 devices.mockResolvedValue([airpods]);
874 await userEvent.click(screen.getByRole("button", { name: "Refresh microphones" }));
875 await expect.element(row(0)).toHaveTextContent("1Blue YetiNot connected");
876 await expect.element(row(1)).toHaveTextContent("2System defaultIn use");
877 expect(await chooseRecordingMicrophone()).toBe("");
878
879 await userEvent.click(screen.getByRole("button", { name: "Move AirPods Pro up" }));
880 await userEvent.click(screen.getByRole("button", { name: "Move AirPods Pro up" }));
881 expect(saved()).toEqual(["AirPods Pro", "Blue Yeti", "System default"]);
882 await expect.element(screen.getByRole("button", { name: "Move AirPods Pro up" })).toBeDisabled();
883 expect(await chooseRecordingMicrophone()).toBe("airpods");
884
885 await userEvent.click(screen.getByRole("button", { name: "Forget Blue Yeti" }));
886 expect(saved()).toEqual(["AirPods Pro", "System default"]);
887 await expect
888 .element(screen.getByRole("button", { name: "Forget System default" }))
889 .not.toBeInTheDocument();
890});