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