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

ProviderSettingsPanel.environment.browser.test.tsx

509 lines17.0 KB

1import { RegistryContext } from "@effect/atom-react";
2import {
3 DEFAULT_UNIFIED_SETTINGS,
4 EnvironmentId,
5 ProviderDriverKind,
6 ProviderInstanceId,
7 type ProviderAuthState,
8 type ServerProvider,
9 type UnifiedSettings,
10} from "@t3tools/contracts";
11import * as Duration from "effect/Duration";
12import { AsyncResult, type Atom } from "effect/reactivity";
13import type { ReactNode } from "react";
14import { describe, expect, it, vi } from "vite-plus/test";
15import { page, userEvent } from "vite-plus/test/browser";
16​
17import "~/index.css";
18import { act, render } from "../../../test/render";
19​
20const state = vi.hoisted(() => ({
21 providers: null as unknown as Atom.Writable<ReadonlyArray<ServerProvider>>,
22 providerAuthQuery: null as unknown,
23 providerAuth: null as ProviderAuthState | null,
24 settings: null as unknown as UnifiedSettings,
25 canManageProviders: true,
26 canWriteSettings: true,
27 searchTargetId: null as string | null,
28 readEnvironmentIds: [] as string[],
29 updateEnvironmentIds: [] as string[],
30 mutationEnvironmentIds: [] as string[],
31 refresh: vi.fn(),
32 updateProvider: vi.fn(),
33 uninstall: vi.fn(),
34 acceptUrlAuth: vi.fn(),
35 updateSettings: vi.fn(),
36 updateModelPreferences: vi.fn(),
37 toggleFavorite: vi.fn(),
38 mutateProviderInstance: vi.fn(),
39 confirm: vi.fn<() => Promise<boolean>>(),
40}));
41​
42vi.mock(import("../../state/server"), async (original) => {
43 const actual = await original();
44 const { Atom } = await import("effect/reactivity");
45 const providers = Atom.make<ReadonlyArray<ServerProvider>>([]).pipe(Atom.keepAlive);
46 state.providers = providers;
47 const config = Atom.make(null);
48 const providerAuth = Atom.make(null);
49 state.providerAuthQuery = providerAuth;
50 const commandLabels = {
51 refreshProviders: "refresh",
52 updateProvider: "update",
53 uninstallAcpRegistryManagedBinary: "uninstall",
54 acceptAcpRegistryUrlAuth: "accept-url-auth",
55 } as const;
56 const labelled = Object.fromEntries(
57 Object.entries(commandLabels).map(([key, label]) => [
58 key,
59 { ...actual.serverEnvironment[key as keyof typeof commandLabels], label },
60 ]),
61 );
62 return {
63 ...actual,
64 providersIgnoringCheckedAtAtom: (() => providers) as never,
65 serverEnvironment: {
66 ...actual.serverEnvironment,
67 ...labelled,
68 configValueAtom: (() => config) as never,
69 providerAuthState: (() => providerAuth) as never,
70 providersValueAtom: (() => providers) as never,
71 } as never,
72 };
73});
74vi.mock(import("../../state/use-atom-command"), async (original) => ({
75 ...(await original()),
76 useAtomCommand: ((command: { label?: string }) =>
77 ({
78 refresh: state.refresh,
79 update: state.updateProvider,
80 uninstall: state.uninstall,
81 "accept-url-auth": state.acceptUrlAuth,
82 })[command.label ?? ""] ?? vi.fn()) as never,
83}));
84vi.mock(import("~/localApi"), async (original) => {
85 const api = { dialogs: { confirm: state.confirm } };
86 return {
87 ...(await original()),
88 readLocalApi: (() => api) as never,
89 ensureLocalApi: (() => api) as never,
90 };
91});
92vi.mock(import("../../state/query"), async (original) => ({
93 ...(await original()),
94 useEnvironmentQuery: ((query: unknown) => ({
95 data: query === state.providerAuthQuery ? state.providerAuth : null,
96 error: null,
97 isPending: false,
98 refresh: vi.fn(),
99 })) as never,
100}));
101vi.mock(import("../../hooks/useSettings"), async (original) => ({
102 ...(await original()),
103 useEnvironmentSettings: ((environmentId: string) => {
104 state.readEnvironmentIds.push(environmentId);
105 return state.settings;
106 }) as never,
107 useUpdateEnvironmentSettings: ((environmentId: string) => {
108 state.updateEnvironmentIds.push(environmentId);
109 return state.updateSettings;
110 }) as never,
111 useUpdateEnvironmentModelPreferences: (() => state.updateModelPreferences) as never,
112 useToggleEnvironmentModelFavorite: (() => state.toggleFavorite) as never,
113 usePersistEnvironmentProviderInstanceMutation: ((environmentId: string) => {
114 state.mutationEnvironmentIds.push(environmentId);
115 return state.mutateProviderInstance;
116 }) as never,
117}));
118vi.mock(import("../../state/session"), async (original) => {
119 const scope = (environmentId: string, requested: string) =>
120 environmentId === "remote-device" &&
121 (requested === "providers:manage"
122 ? state.canManageProviders
123 : requested === "settings:write"
124 ? state.canWriteSettings
125 : requested === "orchestration:read");
126 return {
127 ...(await original()),
128 useEnvironmentScope: scope as never,
129 readEnvironmentScope: scope as never,
130 };
131});
132vi.mock(import("../../state/entities"), async (original) => ({
133 ...(await original()),
134 useProjects: (() => []) as never,
135}));
136vi.mock(import("./settingsLayout"), async (original) => ({
137 ...(await original()),
138 useSettingsSearchTargetId: () => state.searchTargetId,
139 SettingsRow: (({
140 id,
141 title,
142 description,
143 status,
144 control,
145 children,
146 }: {
147 id?: string;
148 title: ReactNode;
149 description?: ReactNode;
150 status?: ReactNode;
151 control?: ReactNode;
152 children?: ReactNode;
153 }) => (
154 <div id={id}>
155 <h4>{title}</h4>
156 {description}
157 {status}
158 {control}
159 {children}
160 </div>
161 )) as never,
162}));
163vi.mock(import("./UsageProviderSettings"), async (original) => ({
164 ...(await original()),
165 UsageProviderSettings: (() => null) as never,
166}));
167vi.mock(import("../ProviderUpdatesAction"), async (original) => ({
168 ...(await original()),
169 ProviderUpdatesAction: (() => null) as never,
170}));
171​
172import { appAtomRegistry } from "~/rpc/atomRegistry";
173import { EnvironmentProviderSettings } from "./ProviderSettingsPanel";
174​
175const environmentId = EnvironmentId.make("remote-device");
176const codexId = ProviderInstanceId.make("codex");
177const customId = ProviderInstanceId.make("codex_work");
178​
179function provider(): ServerProvider {
180 return {
181 instanceId: codexId,
182 driver: ProviderDriverKind.make("codex"),
183 enabled: true,
184 installed: true,
185 version: "1.0.0",
186 status: "ready",
187 auth: { status: "authenticated" },
188 checkedAt: "2026-07-24T12:00:00.000Z",
189 models: [{ slug: "chosen", name: "Chosen", isCustom: false, capabilities: null }],
190 slashCommands: [],
191 skills: [],
192 versionAdvisory: {
193 status: "behind_latest",
194 currentVersion: "1.0.0",
195 latestVersion: "1.1.0",
196 updateCommand: "pnpm add -g @openai/codex@latest",
197 canUpdate: true,
198 checkedAt: "2026-07-24T12:00:00.000Z",
199 message: "Update available.",
200 },
201 };
203​
204const setProviders = (providers: ReadonlyArray<ServerProvider>) =>
205 act(async () => appAtomRegistry.set(state.providers, providers));
206​
207function panel(options?: {
208 readonly readOnly?: boolean;
209 readonly targetInstanceId?: ProviderInstanceId;
210}) {
211 return (
212 <RegistryContext.Provider value={appAtomRegistry}>
213 <div className="@container/providers">
214 <EnvironmentProviderSettings
215 environmentId={environmentId}
216 environmentLabel="Remote device"
217 {...(options?.readOnly === undefined ? {} : { readOnly: options.readOnly })}
218 {...(options?.targetInstanceId === undefined
219 ? {}
220 : { targetInstanceId: options.targetInstanceId })}
221 />
222 </div>
223 </RegistryContext.Provider>
224 );
226​
227// The section header and the end of the provider list both offer Add provider.
228​
229async function setup() {
230 await page.viewport(1280, 900);
231 state.settings = DEFAULT_UNIFIED_SETTINGS;
232 state.canManageProviders = true;
233 state.canWriteSettings = true;
234 state.searchTargetId = null;
235 state.providerAuth = null;
236 state.readEnvironmentIds = [];
237 state.updateEnvironmentIds = [];
238 state.mutationEnvironmentIds = [];
239 state.updateSettings.mockReset();
240 state.updateModelPreferences.mockReset();
241 state.toggleFavorite.mockReset();
242 state.mutateProviderInstance.mockReset().mockResolvedValue(AsyncResult.success({}));
243 state.confirm.mockReset().mockResolvedValue(false);
244 state.refresh.mockReset().mockResolvedValue(AsyncResult.success(undefined));
245 state.updateProvider.mockReset().mockResolvedValue(AsyncResult.success(undefined));
246 state.uninstall.mockReset().mockResolvedValue(AsyncResult.success({}));
247 state.acceptUrlAuth.mockReset().mockResolvedValue(AsyncResult.success({ accepted: true }));
248 await setProviders([]);
250​
251describe("EnvironmentProviderSettings routing", () => {
252 it("does not substitute another account when the requested instance was removed", async () => {
253 await setup();
254 await setProviders([provider()]);
255 await using _screen = await render(panel({ targetInstanceId: customId }));
256 await expect
257 .element(page.getByText("This provider instance is no longer available on this device."))
258 .toBeVisible();
259 expect(state.updateSettings).not.toHaveBeenCalled();
260 });
261​
262 it("updates one provider instance without sending a stale whole map", async () => {
263 await setup();
264 state.settings = {
265 ...DEFAULT_UNIFIED_SETTINGS,
266 providerInstances: {
267 [customId]: {
268 driver: ProviderDriverKind.make("codex"),
269 enabled: true,
270 displayName: "Work",
271 },
272 },
273 };
274 await using _screen = await render(panel());
275 await userEvent.click(page.getByRole("switch", { name: "Enable Work" }).first());
276​
277 expect(state.mutateProviderInstance).toHaveBeenCalledWith(
278 {
279 operation: "upsert",
280 instanceId: customId,
281 instance: { driver: ProviderDriverKind.make("codex"), enabled: false, displayName: "Work" },
282 },
283 {},
284 );
285 });
286​
287 it("routes explicit ACP browser authentication consent to the selected environment", async () => {
288 await setup();
289 const instanceId = ProviderInstanceId.make("acpRegistry_antigravity");
290 const action = {
291 elicitationId: "google-login-1",
292 url: "https://accounts.google.com/login",
293 message: "Continue with Google",
294 };
295 state.settings = {
296 ...DEFAULT_UNIFIED_SETTINGS,
297 providerInstances: {
298 [instanceId]: {
299 driver: ProviderDriverKind.make("acpRegistry"),
300 enabled: true,
301 config: { agentId: "antigravity" },
302 },
303 },
304 };
305 await setProviders([
306 {
307 ...provider(),
308 instanceId,
309 driver: ProviderDriverKind.make("acpRegistry"),
310 auth: { status: "unauthenticated", action },
311 },
312 ]);
313 await using _screen = await render(panel({ targetInstanceId: instanceId }));
314 const link = page.getByRole("link", { name: "Continue authentication" });
315 link.element().addEventListener("click", (event) => event.preventDefault());
316 await userEvent.click(link);
317​
318 expect(state.acceptUrlAuth).toHaveBeenCalledWith({
319 environmentId,
320 input: { instanceId, elicitationId: action.elicitationId },
321 });
322 });
323​
324 it("lets a signed-out managed Codex account switch to the existing CLI", async () => {
325 await setup();
326 const codex = ProviderDriverKind.make("codex");
327 state.settings = {
328 ...DEFAULT_UNIFIED_SETTINGS,
329 providerInstances: {
330 [codexId]: {
331 driver: codex,
332 enabled: true,
333 config: { enabled: true, setupMode: "managed" },
334 },
335 },
336 };
337 state.providerAuth = {
338 instanceId: codexId,
339 phase: "idle",
340 flowId: null,
341 authorizationUrl: null,
342 expiresAt: null,
343 message: null,
344 methods: [{ id: "chatgpt-profile:work", name: "Work", description: null, type: "agent" }],
345 };
346 await setProviders([
347 {
348 ...provider(),
349 auth: { status: "unauthenticated" },
350 setup: { canAuthenticate: true, canInstall: true },
351 },
352 ]);
353 await using _screen = await render(panel({ targetInstanceId: codexId }));
354 await expect.element(page.getByRole("button", { name: "Reconnect account" })).toBeVisible();
355 await userEvent.click(page.getByRole("button", { name: "Use existing CLI" }).element());
356​
357 expect(state.mutateProviderInstance).toHaveBeenCalledWith(
358 {
359 operation: "upsert",
360 instanceId: codexId,
361 instance: {
362 driver: codex,
363 enabled: true,
364 config: { enabled: true, setupMode: "existing" },
365 },
366 },
367 {},
368 );
369 });
370});
371​
372describe("EnvironmentProviderSettings instance removal", () => {
373 it("resets a configured default instance only once the user confirms", async () => {
374 await setup();
375 state.settings = {
376 ...DEFAULT_UNIFIED_SETTINGS,
377 providerInstances: {
378 [codexId]: {
379 driver: ProviderDriverKind.make("codex"),
380 enabled: true,
381 config: { binaryPath: "/opt/codex/bin/codex" },
382 },
383 },
384 };
385 await setProviders([provider()]);
386 await using _screen = await render(panel({ targetInstanceId: codexId }));
387 const reset = page.getByRole("button", { name: "Reset Codex provider settings to default" });
388 await userEvent.click(reset);
389​
390 expect(state.mutateProviderInstance).not.toHaveBeenCalled();
391 expect(state.confirm).toHaveBeenCalledOnce();
392​
393 state.confirm.mockResolvedValue(true);
394 await userEvent.click(reset);
395 await vi.waitFor(() =>
396 expect(state.mutateProviderInstance).toHaveBeenCalledWith({
397 operation: "remove",
398 instanceId: codexId,
399 }),
400 );
401 });
402​
403 it("warns that resetting an enabled default-off provider turns it off", async () => {
404 await setup();
405 const antigravityId = ProviderInstanceId.make("antigravity");
406 const antigravity = ProviderDriverKind.make("antigravity");
407 state.settings = {
408 ...DEFAULT_UNIFIED_SETTINGS,
409 providerInstances: {
410 [antigravityId]: {
411 driver: antigravity,
412 enabled: true,
413 config: { binaryPath: "/opt/antigravity/bin/agy" },
414 },
415 },
416 };
417 await setProviders([{ ...provider(), instanceId: antigravityId, driver: antigravity }]);
418 await using _screen = await render(panel({ targetInstanceId: antigravityId }));
419 await userEvent.click(page.getByRole("button", { name: /^Reset .* provider settings/ }));
420​
421 expect(state.confirm).toHaveBeenCalledWith(
422 expect.stringContaining("It will also be turned off."),
423 {
424 variant: "destructive",
425 },
426 );
427 expect(state.mutateProviderInstance).not.toHaveBeenCalled();
428 });
429​
430 it("deletes a custom instance only once the user confirms", async () => {
431 await setup();
432 state.settings = {
433 ...DEFAULT_UNIFIED_SETTINGS,
434 providerInstances: {
435 [customId]: { driver: ProviderDriverKind.make("codex"), enabled: true },
436 },
437 };
438 await using _screen = await render(panel({ targetInstanceId: customId }));
439 const remove = page.getByRole("button", { name: `Delete instance ${customId}` });
440 await userEvent.click(remove);
441​
442 expect(state.mutateProviderInstance).not.toHaveBeenCalled();
443 expect(state.confirm).toHaveBeenCalledOnce();
444​
445 state.confirm.mockResolvedValue(true);
446 await userEvent.click(remove);
447 await vi.waitFor(() =>
448 expect(state.mutateProviderInstance).toHaveBeenCalledWith({
449 operation: "remove",
450 instanceId: customId,
451 }),
452 );
453 });
454});
455​
456describe("EnvironmentProviderSettings health check interval", () => {
457 it("commits interval drafts and allows retrying rejected edits", async () => {
458 await setup();
459 await using _screen = await render(panel());
460 const input = page.getByRole("textbox", { name: "Provider health check interval in seconds" });
461​
462 await userEvent.type(input, "{ArrowUp}{ArrowDown}");
463 expect(
464 state.updateSettings.mock.calls.map(([patch]) =>
465 Duration.toSeconds(patch.backgroundActivity.overrides.providerHealthRefreshInterval),
466 ),
467 ).toEqual([330, 300]);
468 state.updateSettings.mockClear();
469​
470 // Replacing 300 with 120 passes through 30, 3, an empty field, 1 and 12.
471 await userEvent.type(input, "{Backspace}{Backspace}{Backspace}120");
472 await expect.element(input).toHaveValue("120");
473 expect(state.updateSettings).not.toHaveBeenCalled();
474​
475 await userEvent.tab();
476 expect(
477 state.updateSettings.mock.calls.map(([patch]) =>
478 Duration.toSeconds(patch.backgroundActivity.overrides.providerHealthRefreshInterval),
479 ),
480 ).toEqual([120]);
481​
482 await act(() => state.updateSettings.mock.calls.at(-1)?.[1]?.onFailed?.());
483 await expect.element(input).toHaveValue("300");
484 await userEvent.type(input, "{Backspace}{Backspace}{Backspace}120");
485 await userEvent.tab();
486 expect(
487 state.updateSettings.mock.calls.map(([patch]) =>
488 Duration.toSeconds(patch.backgroundActivity.overrides.providerHealthRefreshInterval),
489 ),
490 ).toEqual([120, 120]);
491​
492 const rejectPrevious = state.updateSettings.mock.calls.at(-1)?.[1]?.onFailed;
493 await userEvent.type(input, "{ArrowUp}");
494 await act(() => rejectPrevious?.());
495 await expect.element(input).toHaveValue("150");
496 });
497​
498 it("restores the saved interval when a cleared field loses focus", async () => {
499 await setup();
500 await using _screen = await render(panel());
501 const input = page.getByRole("textbox", { name: "Provider health check interval in seconds" });
502​
503 await userEvent.type(input, "{Backspace}{Backspace}{Backspace}");
504 await userEvent.tab();
505​
506 await expect.element(input).toHaveValue("300");
507 expect(state.updateSettings).not.toHaveBeenCalled();
508 });
509});