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

CloudVoiceConfiguration.browser.test.tsx

261 lines10.9 KB

1import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection";
2import { EnvironmentId } from "@t3tools/contracts";
3import * as Option from "effect/Option";
4import { expect, it, vi } from "vite-plus/test";
5import { page, userEvent } from "vite-plus/test/browser";
6import { render } from "../../../test/render";
7import "~/index.css";
8import { chooseAudioDestination } from "../../speech/voiceConsent";
9import { useEnvironmentScope, usePreparedConnection } from "../../state/session";
10import { VoiceSettingsPanel } from "./VoiceSettingsPanel";
11import { SettingsScopeProvider } from "./SettingsScopeContext";
12​
13vi.mock(import("../../state/session"), { spy: true });
14vi.mock("../../state/environments", async (importOriginal) => ({
15 ...(await importOriginal<typeof import("../../state/environments")>()),
16 useEnvironments: () => ({
17 environments: [
18 {
19 environmentId: "voice-host",
20 label: "Laptop",
21 connection: { phase: "available" },
22 serverConfig: {
23 featureFlags: { secretProviders: true },
24 secretReferences: true,
25 settings: {
26 secretProviders: {
27 work: { kind: "one_password", label: "Work vault", config: { account: "work" } },
28 },
29 },
30 environment: {
31 platform: { os: "linux", arch: "x64" },
32 capabilities: { voiceTranscription: true, cloudVoiceTranscription: true },
33 },
34 },
35 },
36 ],
37 }),
38}));
39​
40const id = EnvironmentId.make("voice-host");
41const grantKey = "t3code:voice-audio-grant:v1";
42​
43async function withVoicePanel(
44 route: (url: URL, request: RequestInfo | URL, init?: RequestInit) => Promise<Response> | null,
45 body: (screen: Awaited<ReturnType<typeof render>>) => Promise<void>,
46) {
47 const target = new PrimaryConnectionTarget({
48 environmentId: id,
49 label: "Laptop",
50 httpBaseUrl: window.location.origin,
51 wsBaseUrl: "ws://localhost",
52 });
53 const prepared = Option.some({
54 ...target,
55 target,
56 socketUrl: target.wsBaseUrl,
57 httpAuthorization: null,
58 });
59 using cleanup = new DisposableStack();
60 cleanup.defer(() => chooseAudioDestination(null));
61 const fetch = globalThis.fetch;
62 using _network = vi.spyOn(globalThis, "fetch").mockImplementation((request, init) => {
63 const url = new URL(request instanceof Request ? request.url : request, window.location.href);
64 return route(url, request, init) ?? fetch(request, init);
65 });
66 await vi.mocked(useEnvironmentScope).withImplementation(
67 () => true,
68 async () => {
69 await vi.mocked(usePreparedConnection).withImplementation(
70 () => prepared,
71 async () => {
72 await using screen = await render(
73 <SettingsScopeProvider search={{}} onChange={() => {}}>
74 <VoiceSettingsPanel />
75 </SettingsScopeProvider>,
76 );
77 await body(screen);
78 },
79 );
80 },
81 );
83​
84it("cancelling a provider's setup keeps the current destination and writes nothing", async () => {
85 chooseAudioDestination({ kind: "environment", environmentId: id });
86 const writes: unknown[] = [];
87 await withVoicePanel(
88 (url, request, init) => {
89 if (url.pathname === "/api/voice/cloud/keys")
90 return Promise.resolve(Response.json({ openai: false, xai: true }));
91 if (url.pathname !== "/api/voice/cloud/openai/key") return null;
92 return new Request(request, init).json().then((body) => {
93 writes.push(body);
94 return new Response(null, { status: 204 });
95 });
96 },
97 async (screen) => {
98 const destination = screen.getByRole("combobox", { name: "Transcribe with" });
99 await expect.element(destination).toHaveTextContent("Laptop");
100 await destination.click();
101 await page.getByRole("option", { name: "OpenAI via Laptop" }).click();
102 const dialog = page.getByRole("dialog");
103 await dialog.getByRole("button", { name: "Cancel" }).click();
104 await expect.element(dialog).not.toBeInTheDocument();
105 await expect.element(destination).toHaveTextContent("Laptop");
106 expect(writes).toEqual([]);
107 },
108 );
109});
110​
111it("enables the chosen provider only after a successful setup", async () => {
112 chooseAudioDestination({ kind: "environment", environmentId: id });
113 const writes: unknown[] = [];
114 let rejectNextWrite = true;
115 await withVoicePanel(
116 (url, request, init) => {
117 if (url.pathname === "/api/voice/cloud/keys")
118 return Promise.resolve(Response.json({ openai: writes.length > 0, xai: true }));
119 if (url.pathname !== "/api/voice/cloud/openai/key") return null;
120 if (rejectNextWrite) {
121 rejectNextWrite = false;
122 return Promise.resolve(new Response(null, { status: 403 }));
123 }
124 return new Request(request, init).json().then((body) => {
125 writes.push(body);
126 return new Response(null, { status: 204 });
127 });
128 },
129 async (screen) => {
130 const destination = screen.getByRole("combobox", { name: "Transcribe with" });
131 await destination.click();
132 await page.getByRole("option", { name: "OpenAI via Laptop" }).click();
133 const dialog = page.getByRole("dialog");
134 await dialog.getByRole("combobox", { name: "OpenAI API key source" }).click();
135 await page.getByRole("option", { name: "Work vault" }).click();
136 await dialog.getByLabelText("OpenAI API key reference").fill("op://Work/Voice/key");
137 await userEvent.keyboard("{Enter}");
138 await expect.element(dialog.getByRole("alert")).toBeVisible();
139 expect(writes).toEqual([]);
140 await expect.element(dialog.getByRole("button", { name: "Save and enable" })).toBeEnabled();
141 await dialog.getByLabelText("OpenAI API key reference").click();
142 await userEvent.keyboard("{Enter}");
143 await expect.element(dialog).not.toBeInTheDocument();
144 await expect.element(destination).toHaveTextContent("OpenAI via Laptop");
145 expect(writes).toEqual([{ key: { provider: "work", reference: "op://Work/Voice/key" } }]);
146 },
147 );
148});
149​
150it("keeps the active provider's grant when editing its key", async () => {
151 chooseAudioDestination({ kind: "cloud", provider: "openai", environmentId: id });
152 const grant = window.localStorage.getItem(grantKey);
153 const writes: unknown[] = [];
154 await withVoicePanel(
155 (url, request, init) => {
156 if (url.pathname === "/api/voice/cloud/keys")
157 return Promise.resolve(Response.json({ openai: true, xai: true }));
158 if (url.pathname !== "/api/voice/cloud/openai/key") return null;
159 return new Request(request, init).json().then((body) => {
160 writes.push(body);
161 return new Response(null, { status: 204 });
162 });
163 },
164 async (screen) => {
165 await screen.getByRole("button", { name: "Manage key" }).click();
166 const dialog = page.getByRole("dialog");
167 await dialog.getByLabelText("OpenAI API key", { exact: true }).fill("replacement");
168 await userEvent.keyboard("{Enter}");
169 await expect.element(dialog).not.toBeInTheDocument();
170 expect(writes).toEqual([{ key: "replacement" }]);
171 expect(window.localStorage.getItem(grantKey)).toBe(grant);
172 },
173 );
174});
175​
176it("uses a provider's saved key without writing it, and turns dictation off", async () => {
177 chooseAudioDestination({ kind: "environment", environmentId: id });
178 await withVoicePanel(
179 (url) =>
180 url.pathname === "/api/voice/cloud/keys"
181 ? Promise.resolve(Response.json({ openai: false, xai: true }))
182 : null,
183 async (screen) => {
184 const destination = screen.getByRole("combobox", { name: "Transcribe with" });
185 await destination.click();
186 await page.getByRole("option", { name: "Grok Voice Transcribe via Laptop" }).click();
187 await page
188 .getByRole("dialog")
189 .getByRole("button", { name: "Use Grok Voice Transcribe" })
190 .click();
191 await expect.element(destination).toHaveTextContent("Grok Voice Transcribe via Laptop");
192 await destination.click();
193 await page.getByRole("option", { name: "Off", exact: true }).click();
194 await expect.element(destination).toHaveTextContent("Off");
195 },
196 );
197});
198​
199it("OpenRouter needs an exact model, and changing it writes no credential", async () => {
200 chooseAudioDestination(null);
201 const writes: unknown[] = [];
202 const grantModel = () => {
203 const raw = window.localStorage.getItem(grantKey);
204 const parsed = raw ? (JSON.parse(raw) as { destination?: { model?: string } }) : null;
205 return parsed?.destination?.model ?? null;
206 };
207 await withVoicePanel(
208 (url, request, init) => {
209 if (url.pathname === "/api/voice/cloud/keys")
210 return Promise.resolve(Response.json({ openai: false, xai: false, openrouter: true }));
211 if (url.pathname === "/api/voice/cloud/openrouter/models")
212 return Promise.resolve(
213 Response.json({
214 models: [
215 { id: "acme/transcribe-1", name: "Acme: Transcribe 1" },
216 { id: "other/listen-2", name: "Other: Listen 2" },
217 ],
218 }),
219 );
220 if (url.pathname === "/api/voice/cloud/openrouter/key")
221 return new Request(request, init).json().then((body) => {
222 writes.push(body);
223 return new Response(null, { status: 204 });
224 });
225 return null;
226 },
227 async (screen) => {
228 const destination = screen.getByRole("combobox", { name: "Transcribe with" });
229 await destination.click();
230 await page.getByRole("option", { name: "OpenRouter via Laptop" }).click();
231 const dialog = page.getByRole("dialog");
232 const save = dialog.getByRole("button", { name: "Save and enable" });
233 await expect.element(save).toBeDisabled();
234 const picker = dialog.getByRole("combobox", { name: "OpenRouter model" });
235 await expect.element(picker).toBeVisible();
236 await picker.fill("listen");
237 await expect.element(page.getByRole("option", { name: /Other: Listen 2/ })).toBeVisible();
238 await page.getByRole("option", { name: /Other: Listen 2/ }).click();
239 await expect.element(save).toBeEnabled();
240 const key = dialog.getByLabelText("OpenRouter API key", { exact: true });
241 await key.fill("op://not-a-literal-key");
242 await expect.element(save).toBeDisabled();
243 await key.fill("");
244 await save.click();
245 await expect.element(dialog).not.toBeInTheDocument();
246 await expect.element(destination).toHaveTextContent("OpenRouter via Laptop");
247 expect(grantModel()).toBe("other/listen-2");
248 expect(writes).toEqual([]);
249 await screen.getByRole("button", { name: "Manage OpenRouter" }).click();
250 const current = dialog.getByRole("combobox", { name: "OpenRouter model" });
251 await expect.element(current).toHaveValue("Other: Listen 2");
252 await current.fill("acme");
253 await page.getByRole("option", { name: /Acme: Transcribe 1/ }).click();
254 await dialog.getByRole("button", { name: "Save" }).click();
255 await expect.element(dialog).not.toBeInTheDocument();
256 await expect.element(destination).toHaveTextContent("OpenRouter via Laptop");
257 expect(grantModel()).toBe("acme/transcribe-1");
258 expect(writes).toEqual([]);
259 },
260 );
261});