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

ProviderSettingsPanel.environment.test.tsx

620 lines21.1 KB

1import type { ReactElement } from "react";
2import {
3 DEFAULT_UNIFIED_SETTINGS,
4 EnvironmentId,
5 ProviderDriverKind,
6 ProviderInstanceId,
7 type ServerProvider,
8 type UnifiedSettings,
9} from "@t3tools/contracts";
10import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
11​
12import { visitElements } from "../../test/reactElementTree";
13import { reactHookHarness as hooks } from "../../test/reactHookHarness";
14​
15const atoms = vi.hoisted(() => ({
16 providers: null as ReadonlyArray<ServerProvider> | null,
17 providersAtom: Symbol("providers"),
18 refreshProviders: Symbol("refreshProviders"),
19 updateProvider: Symbol("updateProvider"),
20 uninstallAcpRegistryManagedBinary: Symbol("uninstallAcpRegistryManagedBinary"),
21 acceptAcpRegistryUrlAuth: Symbol("acceptAcpRegistryUrlAuth"),
22}));
23​
24const commands = vi.hoisted(() => ({
25 refresh: vi.fn(),
26 updateProvider: vi.fn(),
27 uninstall: vi.fn(),
28 acceptUrlAuth: vi.fn(),
29}));
30​
31const settingsState = vi.hoisted(() => ({
32 value: null as UnifiedSettings | null,
33 readEnvironmentIds: [] as EnvironmentId[],
34 updateEnvironmentIds: [] as EnvironmentId[],
35 mutationEnvironmentIds: [] as EnvironmentId[],
36 updateSettings: vi.fn(),
37 mutateProviderInstance: vi.fn(),
38 updateClientSettings: vi.fn(),
39}));
40​
41const settingsSearchState = vi.hoisted(() => ({
42 targetId: null as string | null,
43 effects: [] as Array<() => void>,
44}));
45​
46vi.mock("react", async (importOriginal) => {
47 const actual = await importOriginal<typeof import("react")>();
48 const { reactHookHarness } = await import("../../test/reactHookHarness");
49 return {
50 ...actual,
51 useCallback: reactHookHarness.useCallback,
52 useEffect: (effect: () => void) => settingsSearchState.effects.push(effect),
53 useMemo: reactHookHarness.useMemo,
54 useRef: reactHookHarness.useRef,
55 useState: reactHookHarness.useState,
56 };
57});
58​
59vi.mock("./settingsLayout", async (importOriginal) => {
60 const actual = await importOriginal<typeof import("./settingsLayout")>();
61 return {
62 ...actual,
63 useSettingsSearchTargetId: () => settingsSearchState.targetId,
64 };
65});
66​
67vi.mock("./SettingsScopeSentence", () => ({ SettingsScopeSentence: () => null }));
68vi.mock("react/compiler-runtime", async () => {
69 const { reactHookHarness } = await import("../../test/reactHookHarness");
70 return { c: reactHookHarness.useMemoCache };
71});
72​
73vi.mock("@effect/atom-react", () => ({
74 useAtomValue: () => atoms.providers,
75}));
76​
77vi.mock("../../state/server", () => ({
78 EMPTY_SERVER_PROVIDERS: [],
79 serverEnvironment: {
80 providersValueAtom: () => atoms.providersAtom,
81 refreshProviders: atoms.refreshProviders,
82 updateProvider: atoms.updateProvider,
83 uninstallAcpRegistryManagedBinary: atoms.uninstallAcpRegistryManagedBinary,
84 acceptAcpRegistryUrlAuth: atoms.acceptAcpRegistryUrlAuth,
85 },
86}));
87​
88vi.mock("../../state/use-atom-command", () => ({
89 useAtomCommand: (atom: symbol) =>
90 atom === atoms.refreshProviders
91 ? commands.refresh
92 : atom === atoms.uninstallAcpRegistryManagedBinary
93 ? commands.uninstall
94 : atom === atoms.acceptAcpRegistryUrlAuth
95 ? commands.acceptUrlAuth
96 : commands.updateProvider,
97}));
98​
99vi.mock("../../hooks/useSettings", () => ({
100 useUpdateClientSettings: () => settingsState.updateClientSettings,
101 useEnvironmentSettings: (environmentId: EnvironmentId) => {
102 settingsState.readEnvironmentIds.push(environmentId);
103 return settingsState.value;
104 },
105 useUpdateEnvironmentSettings: (environmentId: EnvironmentId) => {
106 settingsState.updateEnvironmentIds.push(environmentId);
107 return settingsState.updateSettings;
108 },
109 usePersistEnvironmentProviderInstanceMutation: (environmentId: EnvironmentId) => {
110 settingsState.mutationEnvironmentIds.push(environmentId);
111 return settingsState.mutateProviderInstance;
112 },
113}));
114​
115vi.mock("../../environments/primary", () => ({
116 usePrimarySessionState: () => ({ data: null, error: null, isPending: false, refresh: vi.fn() }),
117}));
118​
119vi.mock("../../state/session", () => ({
120 useEnvironmentSessionState: () => ({ data: null, hasError: false, isPending: true }),
121}));
122​
123vi.mock("../../state/entities", () => ({
124 useProjects: () => [],
125}));
126​
127import { EnvironmentProviderSettings } from "./ProviderSettingsPanel";
128​
129const environmentId = EnvironmentId.make("remote-device");
130const codexId = ProviderInstanceId.make("codex");
131const customId = ProviderInstanceId.make("codex_work");
132​
133function provider(): ServerProvider {
134 return {
135 instanceId: codexId,
136 driver: ProviderDriverKind.make("codex"),
137 enabled: true,
138 installed: true,
139 version: "1.0.0",
140 status: "ready",
141 auth: { status: "authenticated" },
142 checkedAt: "2026-07-24T12:00:00.000Z",
143 models: [],
144 slashCommands: [],
145 skills: [],
146 versionAdvisory: {
147 status: "behind_latest",
148 currentVersion: "1.0.0",
149 latestVersion: "1.1.0",
150 updateCommand: "pnpm add -g @openai/codex@latest",
151 canUpdate: true,
152 checkedAt: "2026-07-24T12:00:00.000Z",
153 message: "Update available.",
154 },
155 };
157​
158function renderPanel(options?: {
159 readonly readOnly?: boolean;
160 readonly targetInstanceId?: ProviderInstanceId;
161}): ReactElement<Record<string, unknown>> {
162 hooks.beginRender();
163 return EnvironmentProviderSettings({
164 environmentId,
165 environmentLabel: "Remote device",
166 ...(options?.readOnly === undefined ? {} : { readOnly: options.readOnly }),
167 ...(options?.targetInstanceId === undefined
168 ? {}
169 : { targetInstanceId: options.targetInstanceId }),
170 }) as ReactElement<Record<string, unknown>>;
172​
173function isRefreshButton(element: ReactElement<Record<string, unknown>>): boolean {
174 const children = element.props.children;
175 return (
176 Array.isArray(children) &&
177 children.some(
178 (child) =>
179 typeof child === "object" &&
180 child !== null &&
181 (child as ReactElement<Record<string, unknown>>).props?.className === "sr-only" &&
182 (child as ReactElement<Record<string, unknown>>).props?.children ===
183 "Refresh provider status",
184 )
185 );
187​
188function isAddProviderButton(element: ReactElement<Record<string, unknown>>): boolean {
189 return element.props["aria-label"] === "Add provider";
191​
192async function flushPromises(): Promise<void> {
193 await Promise.resolve();
194 await Promise.resolve();
196​
197describe("EnvironmentProviderSettings routing", () => {
198 beforeEach(() => {
199 hooks.reset();
200 atoms.providers = null;
201 settingsState.value = DEFAULT_UNIFIED_SETTINGS;
202 settingsState.readEnvironmentIds = [];
203 settingsState.updateEnvironmentIds = [];
204 settingsState.mutationEnvironmentIds = [];
205 settingsState.updateSettings.mockReset();
206 settingsState.updateClientSettings.mockReset();
207 settingsSearchState.targetId = null;
208 settingsSearchState.effects = [];
209 settingsState.mutateProviderInstance
210 .mockReset()
211 .mockResolvedValue({ _tag: "Success", value: {} });
212 commands.refresh.mockReset().mockResolvedValue({ _tag: "Success" });
213 commands.updateProvider.mockReset().mockResolvedValue({ _tag: "Success" });
214 commands.uninstall.mockReset().mockResolvedValue({ _tag: "Success", value: {} });
215 commands.acceptUrlAuth
216 .mockReset()
217 .mockResolvedValue({ _tag: "Success", value: { accepted: true } });
218 });
219​
220 it("shows Codex and Claude while hiding untouched disabled provider slots", () => {
221 const panel = renderPanel();
222 for (const driver of ["codex", "claudeAgent"] as const) {
223 expect(
224 visitElements(
225 panel,
226 (element) => element.props.instanceId === driver && element.props.mode === "list",
227 ),
228 ).not.toBeNull();
229 }
230 for (const driver of ["cursor", "grok", "pi", "opencode", "antigravity"] as const) {
231 expect(
232 visitElements(
233 panel,
234 (element) => element.props.instanceId === driver && element.props.mode === "list",
235 ),
236 ).toBeNull();
237 }
238 });
239​
240 it("keeps explicitly configured providers visible when disabled", () => {
241 const grokId = ProviderInstanceId.make("grok");
242 settingsState.value = {
243 ...DEFAULT_UNIFIED_SETTINGS,
244 providerInstances: {
245 [grokId]: { driver: ProviderDriverKind.make("grok"), enabled: false },
246 },
247 };
248 const panel = renderPanel();
249 expect(
250 visitElements(
251 panel,
252 (element) => element.props.instanceId === grokId && element.props.mode === "list",
253 ),
254 ).not.toBeNull();
255 });
256​
257 it("keeps legacy provider configuration visible when disabled", () => {
258 settingsState.value = {
259 ...DEFAULT_UNIFIED_SETTINGS,
260 providers: {
261 ...DEFAULT_UNIFIED_SETTINGS.providers,
262 grok: {
263 ...DEFAULT_UNIFIED_SETTINGS.providers.grok,
264 enabled: false,
265 binaryPath: "/custom/grok",
266 },
267 },
268 };
269 const panel = renderPanel();
270 expect(
271 visitElements(
272 panel,
273 (element) => element.props.instanceId === "grok" && element.props.mode === "list",
274 ),
275 ).not.toBeNull();
276 });
277​
278 it("coalesces a nullable provider snapshot before rendering array-backed UI", () => {
279 expect(() => renderPanel()).not.toThrow();
280 expect(settingsState.readEnvironmentIds).toEqual([environmentId]);
281 expect(settingsState.updateEnvironmentIds).toEqual([environmentId]);
282 expect(settingsState.mutationEnvironmentIds).toEqual([environmentId]);
283 });
284​
285 it("routes refresh and provider update commands to the selected environment", async () => {
286 atoms.providers = [provider()];
287 const panel = renderPanel();
288 const refreshButton = visitElements(panel, isRefreshButton);
289 expect(refreshButton).not.toBeNull();
290 (refreshButton?.props.onClick as (() => void) | undefined)?.();
291 await flushPromises();
292​
293 expect(commands.refresh).toHaveBeenCalledWith({
294 environmentId,
295 input: { refreshModels: true },
296 });
297​
298 const providerCard = visitElements(
299 panel,
300 (element) =>
301 element.props.instanceId === codexId && typeof element.props.onRunUpdate === "function",
302 );
303 expect(providerCard).not.toBeNull();
304 (providerCard?.props.onRunUpdate as (() => void) | undefined)?.();
305 await flushPromises();
306​
307 expect(commands.updateProvider).toHaveBeenCalledWith({
308 environmentId,
309 input: { provider: ProviderDriverKind.make("codex"), instanceId: codexId },
310 });
311 });
312​
313 it("opens the requested provider instance instead of the first provider", () => {
314 settingsState.value = {
315 ...DEFAULT_UNIFIED_SETTINGS,
316 providerInstances: {
317 [customId]: { driver: ProviderDriverKind.make("codex"), enabled: true },
318 },
319 };
320 atoms.providers = [provider()];
321 const panel = renderPanel({ targetInstanceId: customId });
322 const editor = visitElements(panel, (element) => element.props.mode === "editor");
323 expect(editor?.props.instanceId).toBe(customId);
324 });
325​
326 it.each([
327 ["onFavoriteModelsChange", { favorites: [{ provider: codexId, model: "chosen" }] }],
328 [
329 "onHiddenModelsChange",
330 { providerModelPreferences: { [codexId]: { hiddenModels: ["chosen"], modelOrder: [] } } },
331 ],
332 [
333 "onModelOrderChange",
334 { providerModelPreferences: { [codexId]: { hiddenModels: [], modelOrder: ["chosen"] } } },
335 ],
336 ])("saves %s on this device without changing the selected server", (action, expected) => {
337 atoms.providers = [provider()];
338 const panel = renderPanel();
339 const editor = visitElements(
340 panel,
341 (element) => element.props.instanceId === codexId && element.props.mode === "editor",
342 );
343 expect(editor).not.toBeNull();
344 if (!editor) throw new Error("Provider editor was not rendered");
345 (editor.props[action] as (models: string[]) => void)(["chosen"]);
346 expect(settingsState.updateClientSettings).toHaveBeenCalledExactlyOnceWith(expected);
347 expect(settingsState.updateSettings).not.toHaveBeenCalled();
348 });
349​
350 it("does not substitute another account when the requested instance was removed", () => {
351 atoms.providers = [provider()];
352 const panel = renderPanel({ targetInstanceId: customId });
353 expect(visitElements(panel, (element) => element.props.mode === "editor")).toBeNull();
354 expect(settingsState.updateSettings).not.toHaveBeenCalled();
355 });
356​
357 it("keeps provider selection available while write controls are read only", () => {
358 settingsState.value = {
359 ...DEFAULT_UNIFIED_SETTINGS,
360 providerInstances: {
361 [customId]: {
362 driver: ProviderDriverKind.make("codex"),
363 enabled: true,
364 },
365 },
366 };
367 atoms.providers = [provider()];
368 let panel = renderPanel({ readOnly: true });
369​
370 const inertWrapper = visitElements(panel, (element) => element.props.inert === true);
371 expect(inertWrapper).not.toBeNull();
372​
373 const customRow = visitElements(
374 panel,
375 (element) => element.props.instanceId === customId && element.props.mode === "list",
376 );
377 expect(customRow?.props.readOnly).toBe(true);
378 expect(customRow?.props.onSelect).toBeTypeOf("function");
379 (customRow?.props.onSelect as (() => void) | undefined)?.();
380​
381 panel = renderPanel({ readOnly: true });
382 const customEditor = visitElements(
383 panel,
384 (element) => element.props.instanceId === customId && element.props.mode === "editor",
385 );
386 expect(customEditor).not.toBeNull();
387​
388 const notice = visitElements(panel, (element) => element.props.title === "Limited permissions");
389 expect(notice).not.toBeNull();
390​
391 expect(visitElements(panel, isRefreshButton)).toBeNull();
392 expect(visitElements(panel, isAddProviderButton)).toBeNull();
393 });
394​
395 it("keeps the editable layout interactive when not read only", () => {
396 atoms.providers = [provider()];
397 const panel = renderPanel();
398 expect(visitElements(panel, (element) => element.props.inert === true)).toBeNull();
399 expect(
400 visitElements(panel, (element) => element.props.title === "Limited permissions"),
401 ).toBeNull();
402 expect(visitElements(panel, isRefreshButton)).not.toBeNull();
403 expect(visitElements(panel, isAddProviderButton)).not.toBeNull();
404 });
405​
406 it("keeps Advanced visible when search targets the provider health interval", () => {
407 let panel = renderPanel();
408 expect(visitElements(panel, (element) => element.props.title === "Advanced")).not.toBeNull();
409 expect(
410 visitElements(panel, (element) => element.props.id === "provider-health-check-interval"),
411 ).not.toBeNull();
412​
413 settingsSearchState.targetId = "provider-health-check-interval";
414 panel = renderPanel();
415 expect(visitElements(panel, (element) => element.props.title === "Advanced")).not.toBeNull();
416 expect(
417 visitElements(panel, (element) => element.props.id === "provider-health-check-interval"),
418 ).not.toBeNull();
419 });
420​
421 it("deletes and resets provider configuration without erasing shared preferences", async () => {
422 settingsState.value = {
423 ...DEFAULT_UNIFIED_SETTINGS,
424 providerInstances: {
425 [codexId]: {
426 driver: ProviderDriverKind.make("codex"),
427 enabled: false,
428 },
429 [customId]: {
430 driver: ProviderDriverKind.make("codex"),
431 enabled: true,
432 },
433 },
434 providerModelPreferences: {
435 [customId]: { hiddenModels: ["hidden"], modelOrder: ["model"] },
436 },
437 favorites: [{ provider: customId, model: "favorite" }],
438 };
439 let panel = renderPanel();
440 const customRow = visitElements(
441 panel,
442 (element) => element.props.instanceId === customId && element.props.mode === "list",
443 );
444 (customRow?.props.onSelect as (() => void) | undefined)?.();
445 panel = renderPanel();
446 const customCard = visitElements(
447 panel,
448 (element) => element.props.instanceId === customId && element.props.mode === "editor",
449 );
450 expect(customCard).not.toBeNull();
451 (customCard?.props.onDelete as (() => void) | undefined)?.();
452 await flushPromises();
453​
454 expect(settingsState.mutateProviderInstance).toHaveBeenLastCalledWith({
455 operation: "remove",
456 instanceId: customId,
457 });
458​
459 settingsState.mutateProviderInstance.mockClear();
460 const defaultRow = visitElements(
461 panel,
462 (element) => element.props.instanceId === codexId && element.props.mode === "list",
463 );
464 (defaultRow?.props.onSelect as (() => void) | undefined)?.();
465 panel = renderPanel();
466 const defaultCard = visitElements(
467 panel,
468 (element) => element.props.instanceId === codexId && element.props.mode === "editor",
469 );
470 const resetAction = defaultCard?.props.headerAction;
471 const resetButton = visitElements(
472 resetAction,
473 (element) => typeof element.props.onClick === "function",
474 );
475 expect(resetButton).not.toBeNull();
476 (resetButton?.props.onClick as (() => void) | undefined)?.();
477 await flushPromises();
478​
479 const [resetMutation, resetPatch] = settingsState.mutateProviderInstance.mock.lastCall ?? [];
480 expect(resetMutation).toEqual({ operation: "remove", instanceId: codexId });
481 expect(Object.keys(resetPatch ?? {}).sort()).toEqual(["providers"]);
482 expect(resetPatch).not.toHaveProperty("favorites");
483 expect(resetPatch).not.toHaveProperty("providerModelPreferences");
484 });
485​
486 it("updates one provider instance without sending a stale whole map", async () => {
487 settingsState.value = {
488 ...DEFAULT_UNIFIED_SETTINGS,
489 providerInstances: {
490 [customId]: {
491 driver: ProviderDriverKind.make("codex"),
492 enabled: true,
493 displayName: "Work",
494 },
495 },
496 };
497 const panel = renderPanel();
498 const card = visitElements(panel, (element) => element.props.instanceId === customId);
499 const next = {
500 driver: ProviderDriverKind.make("codex"),
501 enabled: false,
502 displayName: "Work",
503 };
504 (card?.props.onUpdate as ((instance: typeof next) => void) | undefined)?.(next);
505 await flushPromises();
506​
507 expect(settingsState.mutateProviderInstance).toHaveBeenCalledWith(
508 { operation: "upsert", instanceId: customId, instance: next },
509 {},
510 );
511 });
512​
513 it("lets the server decide managed ACP cleanup after an atomic delete", async () => {
514 const firstId = ProviderInstanceId.make("acpRegistry_kilo_one");
515 const secondId = ProviderInstanceId.make("acpRegistry_kilo_two");
516 const registryInstance = {
517 driver: ProviderDriverKind.make("acpRegistry"),
518 enabled: true,
519 config: { agentId: "kilo" },
520 };
521 settingsState.value = {
522 ...DEFAULT_UNIFIED_SETTINGS,
523 providerInstances: {
524 [firstId]: registryInstance,
525 [secondId]: registryInstance,
526 },
527 };
528 let panel = renderPanel();
529 const row = visitElements(
530 panel,
531 (element) => element.props.instanceId === firstId && element.props.mode === "list",
532 );
533 (row?.props.onSelect as (() => void) | undefined)?.();
534 panel = renderPanel();
535 const card = visitElements(
536 panel,
537 (element) => element.props.instanceId === firstId && element.props.mode === "editor",
538 );
539 (card?.props.onDelete as (() => void) | undefined)?.();
540 await flushPromises();
541​
542 expect(settingsState.mutateProviderInstance).toHaveBeenCalledWith({
543 operation: "remove",
544 instanceId: firstId,
545 });
546 expect(commands.uninstall).toHaveBeenCalledWith({
547 environmentId,
548 input: { agentId: "kilo" },
549 });
550 });
551​
552 it("keeps the signed-in ACP account visible when login methods are no longer advertised", () => {
553 const instanceId = ProviderInstanceId.make("acpRegistry_devin");
554 settingsState.value = {
555 ...DEFAULT_UNIFIED_SETTINGS,
556 providerInstances: {
557 [instanceId]: {
558 driver: ProviderDriverKind.make("acpRegistry"),
559 enabled: true,
560 config: { agentId: "devin" },
561 },
562 },
563 };
564 atoms.providers = [
565 {
566 ...provider(),
567 instanceId,
568 driver: ProviderDriverKind.make("acpRegistry"),
569 auth: { status: "authenticated", canLogout: false },
570 setup: { canAuthenticate: false, canInstall: false },
571 },
572 ];
573 const panel = renderPanel({ targetInstanceId: instanceId });
574 expect(
575 visitElements(
576 panel,
577 (element) =>
578 typeof element.type === "function" &&
579 element.type.name === "ProviderAuthenticationSection",
580 ),
581 ).not.toBeNull();
582 });
583​
584 it("routes explicit ACP browser authentication consent to the selected environment", async () => {
585 const instanceId = ProviderInstanceId.make("acpRegistry_antigravity");
586 const action = {
587 elicitationId: "google-login-1",
588 url: "https://accounts.google.com/login",
589 message: "Continue with Google",
590 };
591 settingsState.value = {
592 ...DEFAULT_UNIFIED_SETTINGS,
593 providerInstances: {
594 [instanceId]: {
595 driver: ProviderDriverKind.make("acpRegistry"),
596 enabled: true,
597 config: { agentId: "antigravity" },
598 },
599 },
600 };
601 atoms.providers = [
602 {
603 ...provider(),
604 instanceId,
605 driver: ProviderDriverKind.make("acpRegistry"),
606 auth: { status: "unauthenticated", action },
607 },
608 ];
609​
610 const panel = renderPanel();
611 const card = visitElements(panel, (element) => element.props.instanceId === instanceId);
612 (card?.props.onAcceptUrlAuth as ((candidate: typeof action) => void) | undefined)?.(action);
613 await flushPromises();
614​
615 expect(commands.acceptUrlAuth).toHaveBeenCalledWith({
616 environmentId,
617 input: { instanceId, elicitationId: action.elicitationId },
618 });
619 });
620});