Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

VoiceSettingsPanel.browser.test.tsx

319 lines12.5 KB

1import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection";
2import {
3 EnvironmentId,
4 type EnvironmentSpeechModel,
5 type EnvironmentSpeechStatus,
6} from "@t3tools/contracts";
7import { expect, it, vi } from "vite-plus/test";
8import { userEvent } from "vite-plus/test/browser";
9import { render } from "../../../test/render";
10import { __setClientSettingsForTests, getClientSettings } from "../../hooks/useSettings";
11import {
12 useEnvironmentSpeechInput,
13 useVoiceTranscriptionDestination,
14} from "../../speech/useEnvironmentSpeechInput";
15import { chooseAudioDestination, chooseTranscriptCleanup } from "../../speech/voiceConsent";
16import { toastManager } from "../ui/toast";
17import { SettingsScopeProvider } from "./SettingsScopeContext";
18import { SpeechLanguageSelect } from "./SpeechLanguageSelect";
19import { VoiceSettingsPanel } from "./VoiceSettingsPanel";
20​
21vi.mock(import("../../speech/useEnvironmentSpeechInput"), { spy: true });
22​
23it("preserves the model test transcript when its model is filtered out", async () => {
24 const target = new PrimaryConnectionTarget({
25 environmentId: EnvironmentId.make("voice-filter"),
26 label: "Test environment",
27 httpBaseUrl: window.location.origin,
28 wsBaseUrl: "ws://localhost",
29 });
30 const prepared = { ...target, target, socketUrl: target.wsBaseUrl, httpAuthorization: null };
31 const model: EnvironmentSpeechModel = {
32 id: "tiny",
33 name: "Tiny",
34 description: "",
35 size: 100,
36 languages: ["en"],
37 accuracy: 1,
38 speed: 1,
39 recommended: false,
40 supportsStreaming: false,
41 supportsTranslation: false,
42 supportsLanguageDetection: false,
43 active: true,
44 state: "installed",
45 };
46 const status = {
47 supported: true,
48 state: "ready",
49 modelId: model.id,
50 model: model.name,
51 size: model.size,
52 supportsStreaming: false,
53 supportsTranslation: false,
54 acceleration: "cpu",
55 modelUnloadTimeout: "never",
56 gpuDevices: [],
57 } satisfies EnvironmentSpeechStatus;
58 const fetch = globalThis.fetch;
59 using _network = vi.spyOn(globalThis, "fetch").mockImplementation((input, init) => {
60 const url = new URL(input instanceof Request ? input.url : input, window.location.href);
61 if (url.pathname === "/api/voice/status") return Promise.resolve(Response.json(status));
62 if (url.pathname === "/api/voice/models")
63 return Promise.resolve(
64 Response.json({
65 models: [
66 model,
67 {
68 ...model,
69 id: "both",
70 name: "Bilingual",
71 active: false,
72 languages: ["en", "fr"],
73 ...(url.searchParams.has("benchmarks")
74 ? {
75 benchmark: {
76 accuracy: {
77 en: { grade: "A-", errorPercent: 4 },
78 fr: { grade: "B+", errorPercent: 5.5 },
79 },
80 secondsPer30s: 2.1,
81 },
82 }
83 : {}),
84 },
85 ],
86 }),
87 );
88 return fetch(input, init);
89 });
90 const transcript = "Keep this transcript.";
91 await vi.mocked(useVoiceTranscriptionDestination).withImplementation(
92 () => ({ environmentId: target.environmentId, label: target.label, grantId: "test", prepared }),
93 async () => {
94 await vi.mocked(useEnvironmentSpeechInput).withImplementation(
95 (input) => ({
96 available: true,
97 status,
98 transcriptionEnvironmentId: target.environmentId,
99 transcriptionEnvironmentLabel: target.label,
100 setup: {
101 open: false,
102 step: 0,
103 model: null,
104 downloading: false,
105 error: null,
106 setOpen: () => {},
107 download: async () => {},
108 cancelDownload: async () => {},
109 startRecording: async () => {},
110 },
111 state: { phase: "idle", error: null, errorAction: null },
112 preview: null,
113 level: 0,
114 preparing: false,
115 blocksSubmission: false,
116 freezesEditor: false,
117 start: async () => {
118 input.commitDraft(transcript, { start: transcript.length, end: transcript.length });
119 },
120 submitAfterDictation: () => {},
121 stop: async () => {},
122 cancel: () => {},
123 skipPostProcessing: () => {},
124 }),
125 async () => {
126 await using screen = await render(
127 <SettingsScopeProvider search={{}} onChange={() => {}}>
128 <VoiceSettingsPanel />
129 </SettingsScopeProvider>,
130 );
131 const testModel = screen.getByRole("button", { name: "Test model", exact: true });
132 await expect.element(testModel).toBeVisible();
133 await userEvent.click(testModel);
134 const result = screen.getByRole("status", { name: "Test transcript" });
135 await expect.element(result).toHaveTextContent(transcript);
136​
137 const search = screen.getByRole("textbox", { name: "Search transcription models" });
138 await userEvent.fill(search, "no matching model");
139 await expect.element(screen.getByText("No models match.")).toBeVisible();
140 await userEvent.clear(search);
141 await userEvent.fill(screen.getByRole("textbox", { name: "Search languages" }), "fr");
142 const french = screen.getByRole("button", { name: "French", exact: true });
143 await userEvent.click(french);
144 await expect.element(screen.getByText("Bilingual", { exact: true })).toBeVisible();
145 await expect.element(screen.getByText("B+", { exact: true })).toBeVisible();
146 expect(screen.container.querySelector("#transcription-test")).toHaveAttribute("hidden");
147 await userEvent.click(french);
148 await expect.element(result).toBeVisible();
149 await vi.waitFor(() =>
150 expect(
151 screen.container.querySelector('[aria-label="Test transcript"]')?.textContent,
152 ).toBe(transcript),
153 );
154 },
155 );
156 },
157 );
158});
159​
160it("recovers from a failed download progress poll without notifying, but reports a failed initial load", async () => {
161 const target = new PrimaryConnectionTarget({
162 environmentId: EnvironmentId.make("voice-progress"),
163 label: "Test environment",
164 httpBaseUrl: window.location.origin,
165 wsBaseUrl: "ws://localhost",
166 });
167 const prepared = { ...target, target, socketUrl: target.wsBaseUrl, httpAuthorization: null };
168 const model: EnvironmentSpeechModel = {
169 id: "tiny",
170 name: "Tiny",
171 description: "",
172 size: 100,
173 languages: ["en"],
174 accuracy: 1,
175 speed: 1,
176 recommended: false,
177 supportsStreaming: false,
178 supportsTranslation: false,
179 supportsLanguageDetection: false,
180 active: false,
181 state: "downloading",
182 };
183 const status = {
184 supported: true,
185 state: "missing-model",
186 modelId: model.id,
187 model: model.name,
188 size: model.size,
189 supportsStreaming: false,
190 supportsTranslation: false,
191 acceleration: "cpu",
192 modelUnloadTimeout: "never",
193 gpuDevices: [],
194 };
195 const unavailable = () => new Response(null, { status: 503 });
196 const readModels = vi
197 .fn((_withBenchmarks: boolean) => unavailable())
198 .mockImplementationOnce(() => Response.json({ models: [model] }))
199 .mockImplementationOnce(unavailable)
200 .mockImplementationOnce(() => Response.json({ models: [{ ...model, state: "installed" }] }));
201 const fetch = globalThis.fetch;
202 using _network = vi.spyOn(globalThis, "fetch").mockImplementation((input, init) => {
203 const url = new URL(input instanceof Request ? input.url : input, window.location.href);
204 if (url.pathname === "/api/voice/status") return Promise.resolve(Response.json(status));
205 if (url.pathname === "/api/voice/models")
206 return Promise.resolve(readModels(url.searchParams.has("benchmarks")));
207 return fetch(input, init);
208 });
209 using notify = vi.spyOn(toastManager, "add").mockReturnValue("test");
210 await vi.mocked(useVoiceTranscriptionDestination).withImplementation(
211 () => ({ environmentId: target.environmentId, label: target.label, grantId: "test", prepared }),
212 async () => {
213 const panel = (key: string) => (
214 <SettingsScopeProvider search={{}} onChange={() => {}}>
215 <VoiceSettingsPanel key={key} />
216 </SettingsScopeProvider>
217 );
218 await using screen = await render(panel("first"));
219 await expect.element(screen.getByRole("button", { name: "Use model" })).toBeVisible();
220 expect(readModels.mock.calls.map(([withBenchmarks]) => withBenchmarks)).toEqual([
221 true,
222 false,
223 false,
224 ]);
225 expect(notify).not.toHaveBeenCalled();
226 await screen.rerender(panel("reopened"));
227 await vi.waitFor(() =>
228 expect(notify).toHaveBeenCalledWith(
229 expect.objectContaining({ title: "Could not load transcription models" }),
230 ),
231 );
232 },
233 );
234});
235​
236it.each([
237 ["speech-models", "voice-transcription-destination"],
238 ["speech-hardware", "voice-transcription-destination"],
239 ["transcription-test", "voice-transcription-destination"],
240 ["speech-correction-word", "speech-post-processing"],
241 ["speech-post-processing-model", "speech-post-processing"],
242])(
243 "searching for disabled %s focuses its opt-in without enabling it",
244 async (target, prerequisite) => {
245 chooseAudioDestination(null);
246 chooseTranscriptCleanup(false);
247 await using screen = await render(
248 <SettingsScopeProvider search={{}} onChange={() => {}}>
249 <VoiceSettingsPanel />
250 </SettingsScopeProvider>,
251 { router: `/#${target}` },
252 );
253 await vi.waitFor(() => expect(document.activeElement?.id).toBe(prerequisite));
254 await expect
255 .element(screen.getByRole("combobox", { name: "Send microphone audio to" }))
256 .toHaveTextContent("Off");
257 await expect
258 .element(screen.getByRole("switch", { name: "Clean up transcripts with a provider" }))
259 .not.toBeChecked();
260 },
261);
262​
263it("keeps a missing destination selected without claiming it cannot transcribe", async () => {
264 __setClientSettingsForTests(getClientSettings());
265 using cleanup = new DisposableStack();
266 cleanup.defer(() => chooseAudioDestination(null));
267 chooseAudioDestination({ kind: "environment", environmentId: EnvironmentId.make("missing") });
268 await using screen = await render(
269 <SettingsScopeProvider search={{}} onChange={() => {}}>
270 <VoiceSettingsPanel />
271 </SettingsScopeProvider>,
272 );
273 await expect
274 .element(screen.getByRole("combobox", { name: "Send microphone audio to" }))
275 .toHaveTextContent("Chosen environment (unavailable)");
276 await expect.element(screen.getByText(/can’t transcribe audio/)).not.toBeInTheDocument();
277});
278​
279it("shows the model's effective language and restores the saved preference when supported again", async () => {
280 const previous = getClientSettings();
281 using cleanup = new DisposableStack();
282 cleanup.defer(() => __setClientSettingsForTests(previous));
283 __setClientSettingsForTests({ ...previous, speechLanguage: "fr" });
284 await using screen = await render(<SpeechLanguageSelect model={{ languages: ["en"] }} />);
285 const picker = screen.getByRole("combobox", { name: "Transcription language" });
286 await expect.element(picker).toHaveTextContent("English (French unavailable)");
287 await screen.rerender(
288 <SpeechLanguageSelect model={{ languages: ["en", "de"], supportsLanguageDetection: true }} />,
289 );
290 await expect.element(picker).toHaveTextContent("Auto-detect (French unavailable)");
291 await screen.rerender(<SpeechLanguageSelect model={{ languages: ["en", "fr"] }} />);
292 await expect.element(picker).toHaveTextContent("French");
293 expect(getClientSettings().speechLanguage).toBe("fr");
294});
295​
296it("keeps punctuation in a saved dictionary term and its alias", async () => {
297 const previous = getClientSettings();
298 using cleanup = new DisposableStack();
299 cleanup.defer(() => __setClientSettingsForTests(previous));
300 __setClientSettingsForTests({ ...previous, speechCustomWords: [] });
301 await using screen = await render(
302 <SettingsScopeProvider search={{}} onChange={() => {}}>
303 <VoiceSettingsPanel />
304 </SettingsScopeProvider>,
305 );
306 await userEvent.type(
307 screen.getByRole("textbox", { name: "Add a word or phrase to the dictionary" }),
308 "O'Reilly{Enter}",
309 );
310 expect(getClientSettings().speechCustomWords[0]?.term).toBe("O'Reilly");
311 await userEvent.click(screen.getByRole("button", { name: "Add an alias for O'Reilly" }));
312 await userEvent.type(
313 screen.getByRole("textbox", { name: "Alias for O'Reilly" }),
314 '"Oh Really"{Enter}',
315 );
316 expect(getClientSettings().speechCustomWords).toEqual([
317 { term: "O'Reilly", aliases: ['"Oh Really"'] },
318 ]);
319});