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.getByPlaceholder("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 languages.element().focus();
377 await userEvent.keyboard("{Enter}");
378 await expect.element(languageSearch).toHaveValue("");
379 await expect
380 .element(screen.getByRole("menuitemcheckbox", { name: "All languages", exact: true }))
381 .toBeVisible();
382 await expect.element(languageSearch).toHaveFocus();
383 await userEvent.keyboard("fr");
384 await expect.element(languageSearch).toHaveValue("fr");
385 await userEvent.click(french);
386 await userEvent.keyboard("{Escape}");
387 await expect.element(result).toBeVisible();
388 await vi.waitFor(() =>
389 expect(
390 screen.container.querySelector('[aria-label="Test transcript"]')?.textContent,
391 ).toBe(transcript),
392 );
393 },
394 );
395 },
396 );
397});
398
399it.each([
400 { tier: "cpu", legacy: false },
401 { tier: "accelerated", legacy: false },
402 { tier: "cpu", legacy: true },
403] as const)(
404 "loads relay models using the server tier $tier (legacy: $legacy)",
405 async ({ tier, legacy }) => {
406 const target = new RelayConnectionTarget({
407 environmentId: EnvironmentId.make("voice-relay"),
408 label: "MacBook Pro",
409 });
410 const prepared = {
411 environmentId: target.environmentId,
412 label: target.label,
413 httpBaseUrl: window.location.origin,
414 socketUrl: "ws://localhost",
415 httpAuthorization: {
416 _tag: "Dpop" as const,
417 accessToken: "stale-access-token",
418 expiresAtEpochMs: 4_102_444_800_000,
419 },
420 target,
421 };
422 const model = {
423 id: "gpu",
424 name: "GPU pick",
425 description: "",
426 size: 100,
427 languages: ["en"],
428 benchmark: {
429 accuracy: { en: { grade: "A", errorPercent: 4 } },
430 secondsPer30s: { cpu: 20, accelerated: 1 },
431 },
432 accuracy: 1,
433 speed: 1,
434 recommended: false,
435 supportsStreaming: false,
436 supportsTranslation: false,
437 supportsLanguageDetection: false,
438 active: false,
439 state: "downloadable",
440 } satisfies EnvironmentSpeechModel;
441 const status = {
442 supported: true,
443 state: "missing-model",
444 modelId: model.id,
445 model: model.name,
446 size: model.size,
447 supportsStreaming: false,
448 supportsTranslation: false,
449 acceleration: "auto",
450 benchmarkTier: tier,
451 modelUnloadTimeout: "never",
452 gpuDevices: [{ id: "remote-gpu", name: "Remote GPU" }],
453 } satisfies EnvironmentSpeechStatus;
454 const cpuModel = {
455 ...model,
456 id: "cpu",
457 name: "CPU pick",
458 benchmark: {
459 accuracy: { en: { grade: "B+", errorPercent: 6 } },
460 secondsPer30s: { cpu: 1, accelerated: 8 },
461 },
462 };
463 const { benchmarkTier: _tier, ...legacyStatus } = status;
464 const models = [model, cpuModel];
465 const authorizations: Array<string | null> = [];
466 const fetch = globalThis.fetch;
467 using _network = vi.spyOn(globalThis, "fetch").mockImplementation((input, init) => {
468 const url = new URL(input instanceof Request ? input.url : input, window.location.href);
469 if (url.pathname === "/api/voice/status") {
470 authorizations.push(new Headers(init?.headers).get("authorization"));
471 return Promise.resolve(
472 Response.json(legacy ? { ...legacyStatus, acceleration: "cpu", gpuDevices: [] } : status),
473 );
474 }
475 if (url.pathname === "/api/voice/models")
476 return Promise.resolve(
477 Response.json({
478 models: legacy
479 ? models.map(({ benchmark, ...entry }) => ({
480 ...entry,
481 benchmark: {
482 accuracy: benchmark.accuracy,
483 secondsPer30s: benchmark.secondsPer30s.accelerated,
484 },
485 }))
486 : models,
487 }),
488 );
489 return fetch(input, init);
490 });
491 using notify = vi.spyOn(toastManager, "add").mockReturnValue("test");
492 // Restored even when an assertion fails, unlike `withImplementation`.
493 using _destination = vi.mocked(useVoiceTranscriptionDestination).mockImplementation(() => ({
494 environmentId: target.environmentId,
495 label: target.label,
496 grantId: "test",
497 prepared,
498 }));
499 await using screen = await render(
500 <SettingsScopeProvider search={{}} onChange={() => {}}>
501 <VoiceSettingsPanel />
502 </SettingsScopeProvider>,
503 );
504 await vi.waitFor(() => expect(authorizations.length + notify.mock.calls.length).not.toBe(0));
505 expect(notify).not.toHaveBeenCalled();
506 expect(authorizations).toEqual(["DPoP relay-access-token"]);
507 const region = screen.getByRole("region", { name: "Transcription models" });
508 await vi.waitFor(() => expect(region.element().textContent).toContain("CPU pick"));
509 if (legacy) {
510 expect(region.element().textContent).toContain("update server for this benchmark");
511 expect(region.element().textContent).not.toContain("Recommended");
512 } else {
513 const winner = tier === "cpu" ? "CPU pick" : "GPU pick";
514 await vi.waitFor(() =>
515 expect(region.element().firstElementChild?.textContent).toContain(winner + "Recommended"),
516 );
517 expect(region.element().textContent).toContain("Speed: 1 s / 30 s");
518 }
519 },
520);
521
522it("caps progress while downloading, recovers from a failed poll, and reports a failed initial load", async () => {
523 const target = new PrimaryConnectionTarget({
524 environmentId: EnvironmentId.make("voice-progress"),
525 label: "Test environment",
526 httpBaseUrl: window.location.origin,
527 wsBaseUrl: "ws://localhost",
528 });
529 const prepared = { ...target, target, socketUrl: target.wsBaseUrl, httpAuthorization: null };
530 const model: EnvironmentSpeechModel = {
531 id: "tiny",
532 name: "Tiny",
533 description: "",
534 size: 100,
535 languages: ["en"],
536 accuracy: 1,
537 speed: 1,
538 recommended: false,
539 supportsStreaming: false,
540 supportsTranslation: false,
541 supportsLanguageDetection: false,
542 active: false,
543 state: "downloading",
544 downloaded: 100,
545 };
546 const status = {
547 supported: true,
548 state: "missing-model",
549 modelId: model.id,
550 model: model.name,
551 size: model.size,
552 supportsStreaming: false,
553 supportsTranslation: false,
554 acceleration: "cpu",
555 benchmarkTier: "cpu",
556 modelUnloadTimeout: "never",
557 gpuDevices: [],
558 };
559 const unavailable = () => new Response(null, { status: 503 });
560 const installed = deferred<Response>();
561 const readModels = vi
562 .fn(async (_withBenchmarks: boolean) => unavailable())
563 .mockResolvedValueOnce(Response.json({ models: [model] }))
564 .mockResolvedValueOnce(unavailable())
565 .mockImplementationOnce(() => installed.promise);
566 const fetch = globalThis.fetch;
567 using _network = vi.spyOn(globalThis, "fetch").mockImplementation((input, init) => {
568 const url = new URL(input instanceof Request ? input.url : input, window.location.href);
569 if (url.pathname === "/api/voice/status") return Promise.resolve(Response.json(status));
570 if (url.pathname === "/api/voice/models") return readModels(url.searchParams.has("benchmarks"));
571 return fetch(input, init);
572 });
573 using notify = vi.spyOn(toastManager, "add").mockReturnValue("test");
574 await vi.mocked(useVoiceTranscriptionDestination).withImplementation(
575 () => ({ environmentId: target.environmentId, label: target.label, grantId: "test", prepared }),
576 async () => {
577 const panel = (key: string) => (
578 <SettingsScopeProvider search={{}} onChange={() => {}}>
579 <VoiceSettingsPanel key={key} />
580 </SettingsScopeProvider>
581 );
582 await using screen = await render(panel("first"));
583 const progress = screen.getByRole("progressbar", { name: "Tiny download progress" });
584 await expect.element(progress).toHaveAttribute("aria-valuenow", "99");
585 expect(progress.element().querySelector("div")?.style.width).toBe("99%");
586 installed.resolve(Response.json({ models: [{ ...model, state: "installed" }] }));
587 await expect.element(screen.getByRole("button", { name: "Use model" })).toBeVisible();
588 expect(readModels.mock.calls.map(([withBenchmarks]) => withBenchmarks)).toEqual([
589 true,
590 false,
591 false,
592 ]);
593 expect(notify).not.toHaveBeenCalled();
594 await screen.rerender(panel("reopened"));
595 await vi.waitFor(() =>
596 expect(notify).toHaveBeenCalledWith(
597 expect.objectContaining({ title: "Could not load transcription models" }),
598 ),
599 );
600 },
601 );
602});
603
604it("holds the Language row while the model status loads, and drops it if loading fails", async () => {
605 const target = new PrimaryConnectionTarget({
606 environmentId: EnvironmentId.make("voice-language-loading"),
607 label: "Test environment",
608 httpBaseUrl: window.location.origin,
609 wsBaseUrl: "ws://localhost",
610 });
611 const prepared = { ...target, target, socketUrl: target.wsBaseUrl, httpAuthorization: null };
612 const status = {
613 supported: true,
614 state: "ready",
615 modelId: "tiny",
616 model: "Tiny",
617 size: 100,
618 supportsStreaming: false,
619 supportsTranslation: false,
620 supportsLanguageDetection: true,
621 acceleration: "cpu",
622 benchmarkTier: "cpu",
623 modelUnloadTimeout: "never",
624 gpuDevices: [],
625 };
626 const pending = [Promise.withResolvers<Response>(), Promise.withResolvers<Response>()];
627 let requests = 0;
628 const fetch = globalThis.fetch;
629 using _network = vi.spyOn(globalThis, "fetch").mockImplementation((input, init) => {
630 const url = new URL(input instanceof Request ? input.url : input, window.location.href);
631 if (url.pathname === "/api/voice/status") return pending[requests++]!.promise;
632 if (url.pathname === "/api/voice/models") return Promise.resolve(Response.json({ models: [] }));
633 return fetch(input, init);
634 });
635 using _notify = vi.spyOn(toastManager, "add").mockReturnValue("test");
636 await vi.mocked(useVoiceTranscriptionDestination).withImplementation(
637 () => ({ environmentId: target.environmentId, label: target.label, grantId: "test", prepared }),
638 async () => {
639 const panel = (key: string) => (
640 <SettingsScopeProvider search={{}} onChange={() => {}}>
641 <VoiceSettingsPanel key={key} />
642 </SettingsScopeProvider>
643 );
644 await using screen = await render(panel("first"));
645 const checking = screen.getByText("Checking which languages the model supports…");
646 await expect.element(checking).toBeVisible();
647 pending[0]!.resolve(Response.json(status));
648 await expect
649 .element(screen.getByRole("combobox", { name: "Transcription language" }))
650 .toBeVisible();
651 await expect.element(checking).not.toBeInTheDocument();
652
653 await screen.rerender(panel("reopened"));
654 await expect.element(checking).toBeVisible();
655 pending[1]!.resolve(new Response(null, { status: 503 }));
656 await expect.element(checking).not.toBeInTheDocument();
657 await expect
658 .element(screen.getByRole("combobox", { name: "Transcription language" }))
659 .not.toBeInTheDocument();
660 },
661 );
662});
663
664it.each([
665 ["speech-models", "voice-transcription-destination"],
666 ["speech-hardware", "voice-transcription-destination"],
667 ["speech-streaming", "voice-transcription-destination"],
668 ["transcription-test", "voice-transcription-destination"],
669 ["speech-correction-word", "speech-post-processing"],
670 ["speech-post-processing-model", "speech-post-processing"],
671])(
672 "searching for disabled %s focuses its opt-in without enabling it",
673 async (target, prerequisite) => {
674 chooseAudioDestination(null);
675 chooseTranscriptCleanup(false);
676 await using screen = await render(
677 <SettingsScopeProvider search={{}} onChange={() => {}}>
678 <VoiceSettingsPanel />
679 </SettingsScopeProvider>,
680 { router: `/#${target}` },
681 );
682 await vi.waitFor(() => expect(document.activeElement?.id).toBe(prerequisite));
683 await expect
684 .element(screen.getByRole("combobox", { name: "Transcribe with" }))
685 .toHaveTextContent("Off");
686 await expect
687 .element(screen.getByRole("switch", { name: "Clean up transcripts" }))
688 .not.toBeChecked();
689 },
690);
691
692it("keeps a missing destination selected without claiming it cannot transcribe", async () => {
693 __setClientSettingsForTests(getClientSettings());
694 using cleanup = new DisposableStack();
695 cleanup.defer(() => chooseAudioDestination(null));
696 chooseAudioDestination({ kind: "environment", environmentId: EnvironmentId.make("missing") });
697 await using screen = await render(
698 <SettingsScopeProvider search={{}} onChange={() => {}}>
699 <VoiceSettingsPanel />
700 </SettingsScopeProvider>,
701 );
702 await expect
703 .element(screen.getByRole("combobox", { name: "Transcribe with" }))
704 .toHaveTextContent("Chosen environment (unavailable)");
705 await expect.element(screen.getByText(/can’t transcribe audio/)).not.toBeInTheDocument();
706});
707
708it("shows the model's effective language and restores the saved preference when supported again", async () => {
709 const previous = getClientSettings();
710 using cleanup = new DisposableStack();
711 cleanup.defer(() => __setClientSettingsForTests(previous));
712 __setClientSettingsForTests({ ...previous, speechLanguage: "fr" });
713 await using screen = await render(<SpeechLanguageSelect model={{ languages: ["en"] }} />);
714 const picker = screen.getByRole("combobox", { name: "Transcription language" });
715 await expect.element(picker).toHaveTextContent("English (French unavailable)");
716 await screen.rerender(
717 <SpeechLanguageSelect model={{ languages: ["en", "de"], supportsLanguageDetection: true }} />,
718 );
719 await expect.element(picker).toHaveTextContent("Auto-detect (French unavailable)");
720 await screen.rerender(<SpeechLanguageSelect model={{ languages: ["en", "fr"] }} />);
721 await expect.element(picker).toHaveTextContent("French");
722 expect(getClientSettings().speechLanguage).toBe("fr");
723});
724
725it("keeps punctuation in a saved dictionary term and its alias", async () => {
726 const previous = getClientSettings();
727 using cleanup = new DisposableStack();
728 cleanup.defer(() => __setClientSettingsForTests(previous));
729 __setClientSettingsForTests({ ...previous, speechCustomWords: [] });
730 await using screen = await render(
731 <SettingsScopeProvider search={{}} onChange={() => {}}>
732 <VoiceSettingsPanel />
733 </SettingsScopeProvider>,
734 );
735 await userEvent.type(
736 screen.getByRole("textbox", { name: "Add a word or phrase to the dictionary" }),
737 "O'Reilly{Enter}",
738 );
739 expect(getClientSettings().speechCustomWords[0]?.term).toBe("O'Reilly");
740 await userEvent.click(screen.getByRole("button", { name: "Add an alias for O'Reilly" }));
741 await userEvent.type(
742 screen.getByRole("textbox", { name: "Alias for O'Reilly" }),
743 '"Oh Really"{Enter}',
744 );
745 expect(getClientSettings().speechCustomWords).toEqual([
746 { term: "O'Reilly", aliases: ['"Oh Really"'] },
747 ]);
748});
749
750it("keeps a dictionary term and alias draft on the Enter that confirms an IME candidate", async () => {
751 const previous = getClientSettings();
752 using cleanup = new DisposableStack();
753 cleanup.defer(() => __setClientSettingsForTests(previous));
754 __setClientSettingsForTests({
755 ...previous,
756 speechCustomWords: [{ term: "日本語", aliases: [] }],
757 });
758 await using screen = await render(
759 <SettingsScopeProvider search={{}} onChange={() => {}}>
760 <VoiceSettingsPanel />
761 </SettingsScopeProvider>,
762 );
763 const composingEnter = () =>
764 new KeyboardEvent("keydown", { key: "Enter", isComposing: true, bubbles: true });
765 const term = screen.getByRole("textbox", { name: "Add a word or phrase to the dictionary" });
766 await userEvent.fill(term, "にほん");
767 term.element().dispatchEvent(composingEnter());
768 await expect.element(term).toHaveValue("にほん");
769 await userEvent.click(screen.getByRole("button", { name: "Add an alias for 日本語" }));
770 const alias = screen.getByRole("textbox", { name: "Alias for 日本語" });
771 await userEvent.fill(alias, "にほん");
772 alias.element().dispatchEvent(composingEnter());
773 expect(getClientSettings().speechCustomWords).toEqual([{ term: "日本語", aliases: [] }]);
774 await expect.element(alias).toHaveValue("にほん");
775});
776
777it("cancels an alias draft on Esc without closing Settings", async () => {
778 const previous = getClientSettings();
779 using cleanup = new DisposableStack();
780 cleanup.defer(() => __setClientSettingsForTests(previous));
781 __setClientSettingsForTests({
782 ...previous,
783 speechCustomWords: [{ term: "Kubernetes", aliases: [] }],
784 });
785 await using screen = await render(
786 <AppRouteModal label="Settings">
787 <SettingsScopeProvider search={{}} onChange={() => {}}>
788 <VoiceSettingsPanel />
789 </SettingsScopeProvider>
790 </AppRouteModal>,
791 { router: "/settings/voice" },
792 );
793 const settings = screen.getByRole("dialog", { name: "Settings" });
794 const addAlias = screen.getByRole("button", { name: "Add an alias for Kubernetes" });
795 await expect.element(addAlias).toBeVisible();
796 (addAlias.element() as HTMLElement).focus();
797 await userEvent.keyboard("{Enter}");
798 const alias = screen.getByRole("textbox", { name: "Alias for Kubernetes" });
799 await expect.element(alias).toHaveFocus();
800 await userEvent.keyboard("cooper");
801
802 await userEvent.keyboard("{Escape}");
803
804 await expect.element(alias).not.toBeInTheDocument();
805 await expect.element(settings).toHaveAttribute("data-open");
806 await expect.element(settings).toHaveFocus();
807 expect(getClientSettings().speechCustomWords).toEqual([{ term: "Kubernetes", aliases: [] }]);
808
809 await userEvent.keyboard("{Escape}");
810
811 await expect.element(settings).not.toBeInTheDocument();
812});
813
814it("clears the transcription model search on Esc without closing Settings", async () => {
815 const target = new PrimaryConnectionTarget({
816 environmentId: EnvironmentId.make("voice-search-escape"),
817 label: "Test environment",
818 httpBaseUrl: window.location.origin,
819 wsBaseUrl: "ws://localhost",
820 });
821 const prepared = { ...target, target, socketUrl: target.wsBaseUrl, httpAuthorization: null };
822 const model: EnvironmentSpeechModel = {
823 id: "tiny",
824 name: "Tiny",
825 description: "",
826 size: 100,
827 languages: ["en"],
828 accuracy: 1,
829 speed: 1,
830 recommended: true,
831 supportsStreaming: false,
832 supportsTranslation: false,
833 supportsLanguageDetection: false,
834 active: false,
835 state: "downloadable",
836 };
837 const status = {
838 supported: true,
839 state: "missing-model",
840 modelId: model.id,
841 model: model.name,
842 size: model.size,
843 supportsStreaming: false,
844 supportsTranslation: false,
845 acceleration: "cpu",
846 benchmarkTier: "cpu",
847 modelUnloadTimeout: "never",
848 gpuDevices: [],
849 } satisfies EnvironmentSpeechStatus;
850 const fetch = globalThis.fetch;
851 using _network = vi.spyOn(globalThis, "fetch").mockImplementation((input, init) => {
852 const url = new URL(input instanceof Request ? input.url : input, window.location.href);
853 if (url.pathname === "/api/voice/status") return Promise.resolve(Response.json(status));
854 if (url.pathname === "/api/voice/models")
855 return Promise.resolve(Response.json({ models: [model] }));
856 return fetch(input, init);
857 });
858 await vi.mocked(useVoiceTranscriptionDestination).withImplementation(
859 () => ({ environmentId: target.environmentId, label: target.label, grantId: "test", prepared }),
860 async () => {
861 await using screen = await render(
862 <AppRouteModal label="Settings">
863 <SettingsScopeProvider search={{}} onChange={() => {}}>
864 <VoiceSettingsPanel />
865 </SettingsScopeProvider>
866 </AppRouteModal>,
867 { router: "/settings/voice" },
868 );
869 const settings = screen.getByRole("dialog", { name: "Settings" });
870 const search = screen.getByRole("searchbox", { name: "Search transcription models" });
871 await expect.element(search).toBeVisible();
872
873 await userEvent.fill(search, "tiny");
874 for (const composition of [
875 { key: "Escape", isComposing: true, keyCode: 27 },
876 { key: "Escape", isComposing: false, keyCode: 229 },
877 ]) {
878 // Safari ends the composition just before the Escape keydown.
879 await act(() => {
880 search.element().dispatchEvent(new CompositionEvent("compositionend", { bubbles: true }));
881 search
882 .element()
883 .dispatchEvent(
884 new KeyboardEvent("keydown", { ...composition, bubbles: true, cancelable: true }),
885 );
886 });
887 await expect.element(search).toHaveValue("tiny");
888 await expect.element(settings).toHaveAttribute("data-open");
889 }
890
891 await userEvent.keyboard("{Escape}");
892 await expect.element(search).toHaveValue("");
893 await expect.element(search).toHaveFocus();
894 // Holding Escape repeats the keydown, which must not also close Settings.
895 await act(() => {
896 search.element().dispatchEvent(
897 new KeyboardEvent("keydown", {
898 key: "Escape",
899 repeat: true,
900 bubbles: true,
901 cancelable: true,
902 }),
903 );
904 });
905 await expect.element(settings).toHaveAttribute("data-open");
906
907 await userEvent.keyboard("{Escape}");
908 await expect.element(settings).not.toBeInTheDocument();
909 },
910 );
911});
912
913it("records from the first connected microphone in the saved order", async () => {
914 const previous = getClientSettings();
915 using cleanup = new DisposableStack();
916 cleanup.defer(() => __setClientSettingsForTests(previous));
917 // A single saved microphone from before the order existed comes first.
918 __setClientSettingsForTests({ ...previous, voiceMicrophone: "yeti", voiceMicrophones: [] });
919 const input = (deviceId: string, label: string) =>
920 ({ deviceId, label, groupId: deviceId, kind: "audioinput" }) as MediaDeviceInfo;
921 const yeti = input("yeti", "Blue Yeti");
922 const airpods = input("airpods", "AirPods Pro");
923 using devices = vi
924 .spyOn(navigator.mediaDevices, "enumerateDevices")
925 .mockResolvedValue([yeti, airpods]);
926 const saved = () =>
927 getClientSettings().voiceMicrophones.map((entry) =>
928 entry.kind === "default" ? "System default" : entry.label,
929 );
930 await using screen = await render(
931 <SettingsScopeProvider search={{}} onChange={() => {}}>
932 <VoiceSettingsPanel />
933 </SettingsScopeProvider>,
934 );
935 const list = screen.getByRole("list", { name: "Microphones, preferred first" });
936 await expect.poll(saved).toEqual(["Blue Yeti", "System default", "AirPods Pro"]);
937 const row = (index: number) => list.getByRole("listitem").nth(index);
938 await expect.element(row(0)).toHaveTextContent("1Blue YetiIn use");
939 expect(await chooseRecordingMicrophone()).toBe("yeti");
940
941 devices.mockResolvedValue([airpods]);
942 await userEvent.click(screen.getByRole("button", { name: "Refresh microphones" }));
943 await expect.element(row(0)).toHaveTextContent("1Blue YetiNot connected");
944 await expect.element(row(1)).toHaveTextContent("2System defaultIn use");
945 expect(await chooseRecordingMicrophone()).toBe("");
946
947 await userEvent.click(screen.getByRole("button", { name: "Move AirPods Pro up" }));
948 await userEvent.click(screen.getByRole("button", { name: "Move AirPods Pro up" }));
949 expect(saved()).toEqual(["AirPods Pro", "Blue Yeti", "System default"]);
950 await expect.element(screen.getByRole("button", { name: "Move AirPods Pro up" })).toBeDisabled();
951 expect(await chooseRecordingMicrophone()).toBe("airpods");
952
953 await userEvent.click(screen.getByRole("button", { name: "Forget Blue Yeti" }));
954 expect(saved()).toEqual(["AirPods Pro", "System default"]);
955 await expect
956 .element(screen.getByRole("button", { name: "Forget System default" }))
957 .not.toBeInTheDocument();
958});
959
960it("keeps a newer microphone list when an older refresh finishes last", async () => {
961 const previous = getClientSettings();
962 using cleanup = new DisposableStack();
963 cleanup.defer(() => __setClientSettingsForTests(previous));
964 __setClientSettingsForTests({ ...previous, voiceMicrophone: "usb", voiceMicrophones: [] });
965 const input = (deviceId: string, label: string) =>
966 ({ deviceId, label, groupId: deviceId, kind: "audioinput" }) as MediaDeviceInfo;
967 const usb = input("usb", "USB microphone");
968 const internal = input("internal", "Internal microphone");
969 using devices = vi
970 .spyOn(navigator.mediaDevices, "enumerateDevices")
971 .mockResolvedValue([usb, internal]);
972 await using screen = await render(
973 <SettingsScopeProvider search={{}} onChange={() => {}}>
974 <VoiceSettingsPanel />
975 </SettingsScopeProvider>,
976 );
977 const row = screen
978 .getByRole("list", { name: "Microphones, preferred first" })
979 .getByRole("listitem")
980 .nth(0);
981 await expect.element(row).toHaveTextContent("1USB microphoneIn use");
982
983 const olderScan = Promise.withResolvers<MediaDeviceInfo[]>();
984 devices.mockReturnValueOnce(olderScan.promise);
985 await userEvent.click(screen.getByRole("button", { name: "Refresh microphones" }));
986 devices.mockResolvedValue([internal]);
987 navigator.mediaDevices.dispatchEvent(new Event("devicechange"));
988 await expect.element(row).toHaveTextContent("1USB microphoneNot connected");
989
990 await act(async () => olderScan.resolve([usb, internal]));
991 expect(row.element()).toHaveTextContent("1USB microphoneNot connected");
992});