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 { render } from "../../../test/render";
16import { __setClientSettingsForTests, getClientSettings } from "../../hooks/useSettings";
17import {
18 useEnvironmentSpeechInput,
19 useVoiceTranscriptionDestination,
20} from "../../speech/useEnvironmentSpeechInput";
21import { chooseAudioDestination, chooseTranscriptCleanup } from "../../speech/voiceConsent";
22import { useEnvironmentScope } from "../../state/session";
23import { toastManager } from "../ui/toast";
24import { SettingsScopeProvider } from "./SettingsScopeContext";
25import { SpeechLanguageSelect } from "./SpeechLanguageSelect";
26import { VoiceSettingsPanel } from "./VoiceSettingsPanel";
27
28vi.mock(import("../../speech/useEnvironmentSpeechInput"), { spy: true });
29vi.mock(import("../../state/session"), { spy: true });
30
31// The real connection runtime authorizes relay requests with a signed-in cloud session.
32vi.mock("../../connection/runtime", async () => {
33 const [{ ManagedRelay }, rpc, { Atom }, Context, Effect, Layer] = await Promise.all([
34 import("@t3tools/client-runtime/relay"),
35 import("@t3tools/client-runtime/rpc"),
36 import("effect/reactivity"),
37 import("effect/Context"),
38 import("effect/Effect"),
39 import("effect/Layer"),
40 ]);
41 type AuthorizedHttp =
42 import("@t3tools/client-runtime/authorization").AuthorizedRemoteHttpEnvironment;
43 // Services resolve by key, and client-runtime does not export this one.
44 class RemoteEnvironmentAuthorization extends Context.Service<
45 RemoteEnvironmentAuthorization,
46 {
47 readonly authorizeDpopHttp: (input: {
48 readonly expectedEnvironmentId: AuthorizedHttp["environmentId"];
49 }) => Effect.Effect<AuthorizedHttp>;
50 }
51 // @effect-diagnostics-next-line deterministicKeys:off
52 >()("@t3tools/client-runtime/authorization/service/RemoteEnvironmentAuthorization") {}
53 return {
54 connectionAtomRuntime: Atom.runtime(
55 Layer.mergeAll(
56 rpc.layerRemoteHttpClient((input, init) => globalThis.fetch(input, init)),
57 Layer.succeed(ManagedRelay.ManagedRelayDpopSigner, {
58 thumbprint: Effect.succeed("thumbprint"),
59 createProof: () => Effect.succeed("proof"),
60 }),
61 Layer.succeed(RemoteEnvironmentAuthorization, {
62 authorizeDpopHttp: ({ expectedEnvironmentId }) =>
63 Effect.succeed({
64 environmentId: expectedEnvironmentId,
65 label: "MacBook Pro",
66 httpBaseUrl: window.location.origin,
67 httpAuthorization: {
68 _tag: "Dpop",
69 accessToken: "relay-access-token",
70 expiresAtEpochMs: 4_102_444_800_000,
71 },
72 }),
73 }),
74 ),
75 ),
76 };
77});
78
79function deferred<T>() {
80 let resolve!: (value: T) => void;
81 const promise = new Promise<T>((done) => {
82 resolve = done;
83 });
84 return { promise, resolve };
85}
86
87it.each([{ cpu: null, accelerated: 2.1 }, { cpu: 5, accelerated: null }, { accelerated: 2.1 }])(
88 "uses the destination environment's benchmark tier across switches with measurements %j",
89 async (secondsPer30s) => {
90 const target = new PrimaryConnectionTarget({
91 environmentId: EnvironmentId.make("voice-local"),
92 label: "Local CPU",
93 httpBaseUrl: window.location.origin,
94 wsBaseUrl: "ws://localhost",
95 });
96 const local: PreparedConnection = {
97 ...target,
98 target,
99 socketUrl: target.wsBaseUrl,
100 httpAuthorization: null,
101 };
102 const remote: PreparedConnection = {
103 environmentId: EnvironmentId.make("voice-remote"),
104 label: "Remote GPU",
105 httpBaseUrl: "https://voice.example.test",
106 socketUrl: "wss://voice.example.test/ws",
107 httpAuthorization: { _tag: "Bearer", token: "test-token" },
108 target: new BearerConnectionTarget({
109 environmentId: EnvironmentId.make("voice-remote"),
110 label: "Remote GPU",
111 connectionId: "remote",
112 }),
113 };
114 let prepared = local;
115 const remoteStatus = deferred<Response>();
116 const remoteRequested = deferred<void>();
117 const status = {
118 supported: true,
119 state: "ready",
120 modelId: "both",
121 model: "Bilingual",
122 size: 100,
123 supportsStreaming: false,
124 supportsTranslation: false,
125 acceleration: "auto",
126 modelUnloadTimeout: "never",
127 gpuDevices: [],
128 benchmarkTier: "cpu",
129 } satisfies EnvironmentSpeechStatus;
130 const model: EnvironmentSpeechModel = {
131 id: "both",
132 name: "Bilingual",
133 description: "",
134 size: 100,
135 languages: ["en"],
136 accuracy: 1,
137 speed: 1,
138 recommended: true,
139 supportsStreaming: false,
140 supportsTranslation: false,
141 supportsLanguageDetection: false,
142 active: false,
143 state: "downloadable",
144 benchmark: {
145 accuracy: { en: { grade: "A-", errorPercent: 4 } },
146 secondsPer30s,
147 },
148 };
149 const cpuBenchmark = `Speed: ${secondsPer30s.cpu === undefined ? "update server" : secondsPer30s.cpu === null ? "not benchmarked" : `${secondsPer30s.cpu} s / 30 s`}`;
150 const gpuBenchmark = `Speed: ${secondsPer30s.accelerated === null ? "not benchmarked" : `${secondsPer30s.accelerated} s / 30 s`}`;
151 const fetch = globalThis.fetch;
152 using _network = vi.spyOn(globalThis, "fetch").mockImplementation((input, init) => {
153 const url = new URL(input instanceof Request ? input.url : input, window.location.href);
154 if (url.pathname === "/api/voice/status") {
155 if (url.origin === remote.httpBaseUrl) {
156 remoteRequested.resolve();
157 return remoteStatus.promise;
158 }
159 return Promise.resolve(Response.json(status));
160 }
161 if (url.pathname === "/api/voice/models")
162 return Promise.resolve(Response.json({ models: [model] }));
163 return fetch(input, init);
164 });
165 await vi.mocked(useVoiceTranscriptionDestination).withImplementation(
166 () => ({
167 environmentId: prepared.environmentId,
168 label: prepared.label,
169 grantId: "test",
170 prepared,
171 }),
172 async () => {
173 const panel = () => (
174 <SettingsScopeProvider search={{}} onChange={() => {}}>
175 <VoiceSettingsPanel />
176 </SettingsScopeProvider>
177 );
178 await using screen = await render(panel());
179 await expect.element(screen.getByText(cpuBenchmark)).toBeVisible();
180 prepared = remote;
181 await screen.rerender(panel());
182 await remoteRequested.promise;
183 await expect.element(screen.getByText(cpuBenchmark)).not.toBeInTheDocument();
184 remoteStatus.resolve(
185 Response.json({
186 ...status,
187 benchmarkTier: "accelerated",
188 gpuDevices: [{ id: "gpu", name: "Remote GPU" }],
189 }),
190 );
191 await expect.element(screen.getByText(gpuBenchmark)).toBeVisible();
192 prepared = local;
193 await screen.rerender(panel());
194 await expect.element(screen.getByText(cpuBenchmark)).toBeVisible();
195 await expect.element(screen.getByText(gpuBenchmark)).not.toBeInTheDocument();
196 },
197 );
198 },
199);
200
201it("tests the selected model after download and preserves its transcript across filters", async () => {
202 const target = new PrimaryConnectionTarget({
203 environmentId: EnvironmentId.make("voice-filter"),
204 label: "Test environment",
205 httpBaseUrl: window.location.origin,
206 wsBaseUrl: "ws://localhost",
207 });
208 const prepared = { ...target, target, socketUrl: target.wsBaseUrl, httpAuthorization: null };
209 const model: EnvironmentSpeechModel = {
210 id: "tiny",
211 name: "Tiny",
212 description: "",
213 size: 100,
214 languages: ["en"],
215 accuracy: 1,
216 speed: 1,
217 recommended: false,
218 supportsStreaming: false,
219 supportsTranslation: false,
220 supportsLanguageDetection: false,
221 active: true,
222 state: "installed",
223 };
224 const status = {
225 supported: true,
226 state: "ready",
227 modelId: model.id,
228 model: model.name,
229 size: model.size,
230 supportsStreaming: false,
231 supportsTranslation: false,
232 acceleration: "cpu",
233 modelUnloadTimeout: "never",
234 gpuDevices: [],
235 benchmarkTier: "cpu",
236 } satisfies EnvironmentSpeechStatus;
237 let installed = false;
238 const fetch = globalThis.fetch;
239 using _network = vi.spyOn(globalThis, "fetch").mockImplementation((input, init) => {
240 const url = new URL(input instanceof Request ? input.url : input, window.location.href);
241 if (url.pathname === "/api/voice/status")
242 return Promise.resolve(
243 Response.json(installed ? status : { ...status, state: "missing-model" }),
244 );
245 if (url.pathname === "/api/voice/models/download") {
246 installed = true;
247 return Promise.resolve(Response.json({ models: [model] }));
248 }
249 if (url.pathname === "/api/voice/models")
250 return Promise.resolve(
251 Response.json({
252 models: [
253 installed ? model : { ...model, state: "downloadable", active: false },
254 {
255 ...model,
256 id: "both",
257 name: "Bilingual",
258 active: false,
259 languages: ["en", "fr"],
260 ...(url.searchParams.has("benchmarks")
261 ? {
262 benchmark: {
263 accuracy: {
264 en: { grade: "A-", errorPercent: 4 },
265 fr: { grade: "B+", errorPercent: 5.5 },
266 },
267 secondsPer30s: { cpu: 5, accelerated: 2.1 },
268 },
269 }
270 : {}),
271 },
272 ],
273 }),
274 );
275 return fetch(input, init);
276 });
277 const transcript = "Keep this transcript.";
278 using _scope = vi.mocked(useEnvironmentScope).mockReturnValue(true);
279 await vi.mocked(useVoiceTranscriptionDestination).withImplementation(
280 () => ({ environmentId: target.environmentId, label: target.label, grantId: "test", prepared }),
281 async () => {
282 await vi.mocked(useEnvironmentSpeechInput).withImplementation(
283 (input) => ({
284 available: true,
285 status,
286 transcriptionEnvironmentId: target.environmentId,
287 transcriptionEnvironmentLabel: target.label,
288 setup: {
289 open: false,
290 step: 0,
291 model: null,
292 language: null,
293 downloading: false,
294 catalogFailed: false,
295 retryCatalog: null,
296 error: null,
297 setOpen: () => {},
298 download: async () => {},
299 cancelDownload: async () => {},
300 startRecording: async () => {},
301 },
302 state: { phase: "idle", error: null, errorAction: null },
303 preview: null,
304 level: 0,
305 preparing: false,
306 blocksSubmission: false,
307 freezesEditor: false,
308 start: async () => {
309 input.commitDraft(transcript, { start: transcript.length, end: transcript.length });
310 },
311 submitAfterDictation: () => {},
312 stop: async () => {},
313 cancel: () => {},
314 skipPostProcessing: () => {},
315 }),
316 async () => {
317 await using screen = await render(
318 <SettingsScopeProvider search={{}} onChange={() => {}}>
319 <VoiceSettingsPanel />
320 </SettingsScopeProvider>,
321 );
322 const testModel = screen.getByRole("button", { name: "Test model", exact: true });
323 const download = screen.getByRole("button", { name: "Download", exact: true });
324 await expect.element(download).toBeVisible();
325 expect(testModel.query()).toBeNull();
326 expect(screen.getByRole("button", { name: "Set up voice input" }).query()).toBeNull();
327 await userEvent.click(download);
328 await expect.element(testModel).toBeVisible();
329 expect(screen.getByRole("button", { name: "Set up voice input" }).query()).toBeNull();
330 await userEvent.click(testModel);
331 const result = screen.getByRole("status", { name: "Test transcript" });
332 await expect.element(result).toHaveTextContent(transcript);
333
334 const search = screen.getByRole("textbox", { name: "Search transcription models" });
335 await userEvent.fill(search, "no matching model");
336 await expect.element(screen.getByText("No models match.")).toBeVisible();
337 await userEvent.clear(search);
338 await userEvent.fill(screen.getByRole("textbox", { name: "Search languages" }), "fr");
339 const french = screen.getByRole("button", { name: "French", exact: true });
340 await userEvent.click(french);
341 await expect.element(screen.getByText("Bilingual", { exact: true })).toBeVisible();
342 await expect.element(screen.getByText("B+", { exact: true })).toBeVisible();
343 expect(screen.container.querySelector("#transcription-test")).toHaveAttribute("hidden");
344 await userEvent.click(french);
345 await expect.element(result).toBeVisible();
346 await vi.waitFor(() =>
347 expect(
348 screen.container.querySelector('[aria-label="Test transcript"]')?.textContent,
349 ).toBe(transcript),
350 );
351 },
352 );
353 },
354 );
355});
356
357it("loads the models of a relay-connected destination", async () => {
358 const target = new RelayConnectionTarget({
359 environmentId: EnvironmentId.make("voice-relay"),
360 label: "MacBook Pro",
361 });
362 const prepared = {
363 environmentId: target.environmentId,
364 label: target.label,
365 httpBaseUrl: window.location.origin,
366 socketUrl: "ws://localhost",
367 httpAuthorization: {
368 _tag: "Dpop" as const,
369 accessToken: "stale-access-token",
370 expiresAtEpochMs: 4_102_444_800_000,
371 },
372 target,
373 };
374 const model: EnvironmentSpeechModel = {
375 id: "tiny",
376 name: "Tiny",
377 description: "",
378 size: 100,
379 languages: ["en"],
380 accuracy: 1,
381 speed: 1,
382 recommended: false,
383 supportsStreaming: false,
384 supportsTranslation: false,
385 supportsLanguageDetection: false,
386 active: false,
387 state: "downloadable",
388 };
389 const status = {
390 supported: true,
391 state: "missing-model",
392 modelId: model.id,
393 model: model.name,
394 size: model.size,
395 supportsStreaming: false,
396 supportsTranslation: false,
397 acceleration: "cpu",
398 modelUnloadTimeout: "never",
399 gpuDevices: [],
400 benchmarkTier: "cpu",
401 } satisfies EnvironmentSpeechStatus;
402 const authorizations: Array<string | null> = [];
403 const fetch = globalThis.fetch;
404 using _network = vi.spyOn(globalThis, "fetch").mockImplementation((input, init) => {
405 const url = new URL(input instanceof Request ? input.url : input, window.location.href);
406 if (url.pathname === "/api/voice/status") {
407 authorizations.push(new Headers(init?.headers).get("authorization"));
408 return Promise.resolve(Response.json(status));
409 }
410 if (url.pathname === "/api/voice/models")
411 return Promise.resolve(Response.json({ models: [model] }));
412 return fetch(input, init);
413 });
414 using notify = vi.spyOn(toastManager, "add").mockReturnValue("test");
415 // Restored even when an assertion fails, unlike `withImplementation`.
416 using _destination = vi.mocked(useVoiceTranscriptionDestination).mockImplementation(() => ({
417 environmentId: target.environmentId,
418 label: target.label,
419 grantId: "test",
420 prepared,
421 }));
422 await using screen = await render(
423 <SettingsScopeProvider search={{}} onChange={() => {}}>
424 <VoiceSettingsPanel />
425 </SettingsScopeProvider>,
426 );
427 await vi.waitFor(() => expect(authorizations.length + notify.mock.calls.length).not.toBe(0));
428 expect(notify).not.toHaveBeenCalled();
429 expect(authorizations).toEqual(["DPoP relay-access-token"]);
430 await expect.element(screen.getByText("Tiny", { exact: true })).toBeVisible();
431});
432
433it("recovers from a failed download progress poll without notifying, but reports a failed initial load", async () => {
434 const target = new PrimaryConnectionTarget({
435 environmentId: EnvironmentId.make("voice-progress"),
436 label: "Test environment",
437 httpBaseUrl: window.location.origin,
438 wsBaseUrl: "ws://localhost",
439 });
440 const prepared = { ...target, target, socketUrl: target.wsBaseUrl, httpAuthorization: null };
441 const model: EnvironmentSpeechModel = {
442 id: "tiny",
443 name: "Tiny",
444 description: "",
445 size: 100,
446 languages: ["en"],
447 accuracy: 1,
448 speed: 1,
449 recommended: false,
450 supportsStreaming: false,
451 supportsTranslation: false,
452 supportsLanguageDetection: false,
453 active: false,
454 state: "downloading",
455 };
456 const status = {
457 supported: true,
458 state: "missing-model",
459 modelId: model.id,
460 model: model.name,
461 size: model.size,
462 supportsStreaming: false,
463 supportsTranslation: false,
464 acceleration: "cpu",
465 modelUnloadTimeout: "never",
466 gpuDevices: [],
467 benchmarkTier: "cpu",
468 };
469 const unavailable = () => new Response(null, { status: 503 });
470 const readModels = vi
471 .fn((_withBenchmarks: boolean) => unavailable())
472 .mockImplementationOnce(() => Response.json({ models: [model] }))
473 .mockImplementationOnce(unavailable)
474 .mockImplementationOnce(() => Response.json({ models: [{ ...model, state: "installed" }] }));
475 const fetch = globalThis.fetch;
476 using _network = vi.spyOn(globalThis, "fetch").mockImplementation((input, init) => {
477 const url = new URL(input instanceof Request ? input.url : input, window.location.href);
478 if (url.pathname === "/api/voice/status") return Promise.resolve(Response.json(status));
479 if (url.pathname === "/api/voice/models")
480 return Promise.resolve(readModels(url.searchParams.has("benchmarks")));
481 return fetch(input, init);
482 });
483 using notify = vi.spyOn(toastManager, "add").mockReturnValue("test");
484 await vi.mocked(useVoiceTranscriptionDestination).withImplementation(
485 () => ({ environmentId: target.environmentId, label: target.label, grantId: "test", prepared }),
486 async () => {
487 const panel = (key: string) => (
488 <SettingsScopeProvider search={{}} onChange={() => {}}>
489 <VoiceSettingsPanel key={key} />
490 </SettingsScopeProvider>
491 );
492 await using screen = await render(panel("first"));
493 await expect.element(screen.getByRole("button", { name: "Use model" })).toBeVisible();
494 expect(readModels.mock.calls.map(([withBenchmarks]) => withBenchmarks)).toEqual([
495 true,
496 false,
497 false,
498 ]);
499 expect(notify).not.toHaveBeenCalled();
500 await screen.rerender(panel("reopened"));
501 await vi.waitFor(() =>
502 expect(notify).toHaveBeenCalledWith(
503 expect.objectContaining({ title: "Could not load transcription models" }),
504 ),
505 );
506 },
507 );
508});
509
510it.each([
511 ["speech-models", "voice-transcription-destination"],
512 ["speech-hardware", "voice-transcription-destination"],
513 ["transcription-test", "voice-transcription-destination"],
514 ["speech-correction-word", "speech-post-processing"],
515 ["speech-post-processing-model", "speech-post-processing"],
516])(
517 "searching for disabled %s focuses its opt-in without enabling it",
518 async (target, prerequisite) => {
519 chooseAudioDestination(null);
520 chooseTranscriptCleanup(false);
521 await using screen = await render(
522 <SettingsScopeProvider search={{}} onChange={() => {}}>
523 <VoiceSettingsPanel />
524 </SettingsScopeProvider>,
525 { router: `/#${target}` },
526 );
527 await vi.waitFor(() => expect(document.activeElement?.id).toBe(prerequisite));
528 await expect
529 .element(screen.getByRole("combobox", { name: "Transcribe with" }))
530 .toHaveTextContent("Off");
531 await expect
532 .element(screen.getByRole("switch", { name: "Clean up transcripts" }))
533 .not.toBeChecked();
534 },
535);
536
537it("keeps a missing destination selected without claiming it cannot transcribe", async () => {
538 __setClientSettingsForTests(getClientSettings());
539 using cleanup = new DisposableStack();
540 cleanup.defer(() => chooseAudioDestination(null));
541 chooseAudioDestination({ kind: "environment", environmentId: EnvironmentId.make("missing") });
542 await using screen = await render(
543 <SettingsScopeProvider search={{}} onChange={() => {}}>
544 <VoiceSettingsPanel />
545 </SettingsScopeProvider>,
546 );
547 await expect
548 .element(screen.getByRole("combobox", { name: "Transcribe with" }))
549 .toHaveTextContent("Chosen environment (unavailable)");
550 await expect.element(screen.getByText(/can’t transcribe audio/)).not.toBeInTheDocument();
551});
552
553it("shows the model's effective language and restores the saved preference when supported again", async () => {
554 const previous = getClientSettings();
555 using cleanup = new DisposableStack();
556 cleanup.defer(() => __setClientSettingsForTests(previous));
557 __setClientSettingsForTests({ ...previous, speechLanguage: "fr" });
558 await using screen = await render(<SpeechLanguageSelect model={{ languages: ["en"] }} />);
559 const picker = screen.getByRole("combobox", { name: "Transcription language" });
560 await expect.element(picker).toHaveTextContent("English (French unavailable)");
561 await screen.rerender(
562 <SpeechLanguageSelect model={{ languages: ["en", "de"], supportsLanguageDetection: true }} />,
563 );
564 await expect.element(picker).toHaveTextContent("Auto-detect (French unavailable)");
565 await screen.rerender(<SpeechLanguageSelect model={{ languages: ["en", "fr"] }} />);
566 await expect.element(picker).toHaveTextContent("French");
567 expect(getClientSettings().speechLanguage).toBe("fr");
568});
569
570it("keeps punctuation in a saved dictionary term and its alias", async () => {
571 const previous = getClientSettings();
572 using cleanup = new DisposableStack();
573 cleanup.defer(() => __setClientSettingsForTests(previous));
574 __setClientSettingsForTests({ ...previous, speechCustomWords: [] });
575 await using screen = await render(
576 <SettingsScopeProvider search={{}} onChange={() => {}}>
577 <VoiceSettingsPanel />
578 </SettingsScopeProvider>,
579 );
580 await userEvent.type(
581 screen.getByRole("textbox", { name: "Add a word or phrase to the dictionary" }),
582 "O'Reilly{Enter}",
583 );
584 expect(getClientSettings().speechCustomWords[0]?.term).toBe("O'Reilly");
585 await userEvent.click(screen.getByRole("button", { name: "Add an alias for O'Reilly" }));
586 await userEvent.type(
587 screen.getByRole("textbox", { name: "Alias for O'Reilly" }),
588 '"Oh Really"{Enter}',
589 );
590 expect(getClientSettings().speechCustomWords).toEqual([
591 { term: "O'Reilly", aliases: ['"Oh Really"'] },
592 ]);
593});