Open History to see the last commit
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}));
39
40const settingsSearchState = vi.hoisted(() => ({
41 targetId: null as string | null,
42 effects: [] as Array<() => void>,
43}));
44
45vi.mock("react", async (importOriginal) => {
46 const actual = await importOriginal<typeof import("react")>();
47 const { reactHookHarness } = await import("../../test/reactHookHarness");
48 return {
49 ...actual,
50 useCallback: reactHookHarness.useCallback,
51 useEffect: (effect: () => void) => settingsSearchState.effects.push(effect),
52 useMemo: reactHookHarness.useMemo,
53 useRef: reactHookHarness.useRef,
54 useState: reactHookHarness.useState,
55 };
56});
57
58vi.mock("./settingsLayout", async (importOriginal) => {
59 const actual = await importOriginal<typeof import("./settingsLayout")>();
60 return {
61 ...actual,
62 useSettingsSearchTargetId: () => settingsSearchState.targetId,
63 };
64});
65
66vi.mock("react/compiler-runtime", async () => {
67 const { reactHookHarness } = await import("../../test/reactHookHarness");
68 return { c: reactHookHarness.useMemoCache };
69});
70
71vi.mock("@effect/atom-react", () => ({
72 useAtomValue: () => atoms.providers,
73}));
74
75vi.mock("../../state/server", () => ({
76 EMPTY_SERVER_PROVIDERS: [],
77 serverEnvironment: {
78 providersValueAtom: () => atoms.providersAtom,
79 refreshProviders: atoms.refreshProviders,
80 updateProvider: atoms.updateProvider,
81 uninstallAcpRegistryManagedBinary: atoms.uninstallAcpRegistryManagedBinary,
82 acceptAcpRegistryUrlAuth: atoms.acceptAcpRegistryUrlAuth,
83 },
84}));
85
86vi.mock("../../state/use-atom-command", () => ({
87 useAtomCommand: (atom: symbol) =>
88 atom === atoms.refreshProviders
89 ? commands.refresh
90 : atom === atoms.uninstallAcpRegistryManagedBinary
91 ? commands.uninstall
92 : atom === atoms.acceptAcpRegistryUrlAuth
93 ? commands.acceptUrlAuth
94 : commands.updateProvider,
95}));
96
97vi.mock("../../hooks/useSettings", () => ({
98 useEnvironmentSettings: (environmentId: EnvironmentId) => {
99 settingsState.readEnvironmentIds.push(environmentId);
100 return settingsState.value;
101 },
102 useUpdateEnvironmentSettings: (environmentId: EnvironmentId) => {
103 settingsState.updateEnvironmentIds.push(environmentId);
104 return settingsState.updateSettings;
105 },
106 usePersistEnvironmentProviderInstanceMutation: (environmentId: EnvironmentId) => {
107 settingsState.mutationEnvironmentIds.push(environmentId);
108 return settingsState.mutateProviderInstance;
109 },
110}));
111
112vi.mock("../../environments/primary", () => ({
113 usePrimarySessionState: () => ({ data: null, error: null, isPending: false, refresh: vi.fn() }),
114}));
115
116vi.mock("../../state/session", () => ({
117 useEnvironmentSessionState: () => ({ data: null, hasError: false, isPending: true }),
118}));
119
120vi.mock("../../state/entities", () => ({
121 useProjects: () => [],
122}));
123
124import { EnvironmentProviderSettings } from "./ProviderSettingsPanel";
125
126const environmentId = EnvironmentId.make("remote-device");
127const codexId = ProviderInstanceId.make("codex");
128const customId = ProviderInstanceId.make("codex_work");
129
130function provider(): ServerProvider {
131 return {
132 instanceId: codexId,
133 driver: ProviderDriverKind.make("codex"),
134 enabled: true,
135 installed: true,
136 version: "1.0.0",
137 status: "ready",
138 auth: { status: "authenticated" },
139 checkedAt: "2026-07-24T12:00:00.000Z",
140 models: [],
141 slashCommands: [],
142 skills: [],
143 versionAdvisory: {
144 status: "behind_latest",
145 currentVersion: "1.0.0",
146 latestVersion: "1.1.0",
147 updateCommand: "pnpm add -g @openai/codex@latest",
148 canUpdate: true,
149 checkedAt: "2026-07-24T12:00:00.000Z",
150 message: "Update available.",
151 },
152 };
153}
154
155function renderPanel(options?: {
156 readonly readOnly?: boolean;
157 readonly targetInstanceId?: ProviderInstanceId;
158}): ReactElement<Record<string, unknown>> {
159 hooks.beginRender();
160 return EnvironmentProviderSettings({
161 environmentId,
162 environmentLabel: "Remote device",
163 ...(options?.readOnly === undefined ? {} : { readOnly: options.readOnly }),
164 ...(options?.targetInstanceId === undefined
165 ? {}
166 : { targetInstanceId: options.targetInstanceId }),
167 }) as ReactElement<Record<string, unknown>>;
168}
169
170function isRefreshButton(element: ReactElement<Record<string, unknown>>): boolean {
171 const children = element.props.children;
172 return (
173 Array.isArray(children) &&
174 children.some(
175 (child) =>
176 typeof child === "object" &&
177 child !== null &&
178 (child as ReactElement<Record<string, unknown>>).props?.className === "sr-only" &&
179 (child as ReactElement<Record<string, unknown>>).props?.children ===
180 "Refresh provider status",
181 )
182 );
183}
184
185function isAddProviderButton(element: ReactElement<Record<string, unknown>>): boolean {
186 return element.props["aria-label"] === "Add provider";
187}
188
189async function flushPromises(): Promise<void> {
190 await Promise.resolve();
191 await Promise.resolve();
192}
193
194describe("EnvironmentProviderSettings routing", () => {
195 beforeEach(() => {
196 hooks.reset();
197 atoms.providers = null;
198 settingsState.value = DEFAULT_UNIFIED_SETTINGS;
199 settingsState.readEnvironmentIds = [];
200 settingsState.updateEnvironmentIds = [];
201 settingsState.mutationEnvironmentIds = [];
202 settingsState.updateSettings.mockReset();
203 settingsSearchState.targetId = null;
204 settingsSearchState.effects = [];
205 settingsState.mutateProviderInstance
206 .mockReset()
207 .mockResolvedValue({ _tag: "Success", value: {} });
208 commands.refresh.mockReset().mockResolvedValue({ _tag: "Success" });
209 commands.updateProvider.mockReset().mockResolvedValue({ _tag: "Success" });
210 commands.uninstall.mockReset().mockResolvedValue({ _tag: "Success", value: {} });
211 commands.acceptUrlAuth
212 .mockReset()
213 .mockResolvedValue({ _tag: "Success", value: { accepted: true } });
214 });
215
216 it("coalesces a nullable provider snapshot before rendering array-backed UI", () => {
217 expect(() => renderPanel()).not.toThrow();
218 expect(settingsState.readEnvironmentIds).toEqual([environmentId]);
219 expect(settingsState.updateEnvironmentIds).toEqual([environmentId]);
220 expect(settingsState.mutationEnvironmentIds).toEqual([environmentId]);
221 });
222
223 it("routes refresh and provider update commands to the selected environment", async () => {
224 atoms.providers = [provider()];
225 const panel = renderPanel();
226 const refreshButton = visitElements(panel, isRefreshButton);
227 expect(refreshButton).not.toBeNull();
228 (refreshButton?.props.onClick as (() => void) | undefined)?.();
229 await flushPromises();
230
231 expect(commands.refresh).toHaveBeenCalledWith({
232 environmentId,
233 input: { refreshModels: true },
234 });
235
236 const providerCard = visitElements(
237 panel,
238 (element) =>
239 element.props.instanceId === codexId && typeof element.props.onRunUpdate === "function",
240 );
241 expect(providerCard).not.toBeNull();
242 (providerCard?.props.onRunUpdate as (() => void) | undefined)?.();
243 await flushPromises();
244
245 expect(commands.updateProvider).toHaveBeenCalledWith({
246 environmentId,
247 input: { provider: ProviderDriverKind.make("codex"), instanceId: codexId },
248 });
249 });
250
251 it("opens the requested provider instance instead of the first provider", () => {
252 settingsState.value = {
253 ...DEFAULT_UNIFIED_SETTINGS,
254 providerInstances: {
255 [customId]: { driver: ProviderDriverKind.make("codex"), enabled: true },
256 },
257 };
258 atoms.providers = [provider()];
259 const panel = renderPanel({ targetInstanceId: customId });
260 const editor = visitElements(panel, (element) => element.props.mode === "editor");
261 expect(editor?.props.instanceId).toBe(customId);
262 });
263
264 it("does not substitute another account when the requested instance was removed", () => {
265 atoms.providers = [provider()];
266 const panel = renderPanel({ targetInstanceId: customId });
267 expect(visitElements(panel, (element) => element.props.mode === "editor")).toBeNull();
268 expect(settingsState.updateSettings).not.toHaveBeenCalled();
269 });
270
271 it("keeps provider selection available while write controls are read only", () => {
272 settingsState.value = {
273 ...DEFAULT_UNIFIED_SETTINGS,
274 providerInstances: {
275 [customId]: {
276 driver: ProviderDriverKind.make("codex"),
277 enabled: true,
278 },
279 },
280 };
281 atoms.providers = [provider()];
282 let panel = renderPanel({ readOnly: true });
283
284 const inertWrapper = visitElements(panel, (element) => element.props.inert === true);
285 expect(inertWrapper).not.toBeNull();
286
287 const customRow = visitElements(
288 panel,
289 (element) => element.props.instanceId === customId && element.props.mode === "list",
290 );
291 expect(customRow?.props.readOnly).toBe(true);
292 expect(customRow?.props.onSelect).toBeTypeOf("function");
293 (customRow?.props.onSelect as (() => void) | undefined)?.();
294
295 panel = renderPanel({ readOnly: true });
296 const customEditor = visitElements(
297 panel,
298 (element) => element.props.instanceId === customId && element.props.mode === "editor",
299 );
300 expect(customEditor).not.toBeNull();
301
302 const notice = visitElements(panel, (element) => element.props.title === "Limited permissions");
303 expect(notice).not.toBeNull();
304
305 expect(visitElements(panel, isRefreshButton)).toBeNull();
306 expect(visitElements(panel, isAddProviderButton)).toBeNull();
307 });
308
309 it("keeps the editable layout interactive when not read only", () => {
310 atoms.providers = [provider()];
311 const panel = renderPanel();
312 expect(visitElements(panel, (element) => element.props.inert === true)).toBeNull();
313 expect(
314 visitElements(panel, (element) => element.props.title === "Limited permissions"),
315 ).toBeNull();
316 expect(visitElements(panel, isRefreshButton)).not.toBeNull();
317 expect(visitElements(panel, isAddProviderButton)).not.toBeNull();
318 });
319
320 it("keeps Advanced visible when search targets the provider health interval", () => {
321 let panel = renderPanel();
322 expect(visitElements(panel, (element) => element.props.title === "Advanced")).not.toBeNull();
323 expect(
324 visitElements(panel, (element) => element.props.id === "provider-health-check-interval"),
325 ).not.toBeNull();
326
327 settingsSearchState.targetId = "provider-health-check-interval";
328 panel = renderPanel();
329 expect(visitElements(panel, (element) => element.props.title === "Advanced")).not.toBeNull();
330 expect(
331 visitElements(panel, (element) => element.props.id === "provider-health-check-interval"),
332 ).not.toBeNull();
333 });
334
335 it("deletes and resets provider configuration without erasing shared preferences", async () => {
336 settingsState.value = {
337 ...DEFAULT_UNIFIED_SETTINGS,
338 providerInstances: {
339 [codexId]: {
340 driver: ProviderDriverKind.make("codex"),
341 enabled: false,
342 },
343 [customId]: {
344 driver: ProviderDriverKind.make("codex"),
345 enabled: true,
346 },
347 },
348 providerModelPreferences: {
349 [customId]: { hiddenModels: ["hidden"], modelOrder: ["model"] },
350 },
351 favorites: [{ provider: customId, model: "favorite" }],
352 };
353 let panel = renderPanel();
354 const customRow = visitElements(
355 panel,
356 (element) => element.props.instanceId === customId && element.props.mode === "list",
357 );
358 (customRow?.props.onSelect as (() => void) | undefined)?.();
359 panel = renderPanel();
360 const customCard = visitElements(
361 panel,
362 (element) => element.props.instanceId === customId && element.props.mode === "editor",
363 );
364 expect(customCard).not.toBeNull();
365 (customCard?.props.onDelete as (() => void) | undefined)?.();
366 await flushPromises();
367
368 expect(settingsState.mutateProviderInstance).toHaveBeenLastCalledWith({
369 operation: "remove",
370 instanceId: customId,
371 });
372
373 settingsState.mutateProviderInstance.mockClear();
374 const defaultRow = visitElements(
375 panel,
376 (element) => element.props.instanceId === codexId && element.props.mode === "list",
377 );
378 (defaultRow?.props.onSelect as (() => void) | undefined)?.();
379 panel = renderPanel();
380 const defaultCard = visitElements(
381 panel,
382 (element) => element.props.instanceId === codexId && element.props.mode === "editor",
383 );
384 const resetAction = defaultCard?.props.headerAction;
385 const resetButton = visitElements(
386 resetAction,
387 (element) => typeof element.props.onClick === "function",
388 );
389 expect(resetButton).not.toBeNull();
390 (resetButton?.props.onClick as (() => void) | undefined)?.();
391 await flushPromises();
392
393 const [resetMutation, resetPatch] = settingsState.mutateProviderInstance.mock.lastCall ?? [];
394 expect(resetMutation).toEqual({ operation: "remove", instanceId: codexId });
395 expect(Object.keys(resetPatch ?? {}).sort()).toEqual(["providers"]);
396 expect(resetPatch).not.toHaveProperty("favorites");
397 expect(resetPatch).not.toHaveProperty("providerModelPreferences");
398 });
399
400 it("updates one provider instance without sending a stale whole map", async () => {
401 settingsState.value = {
402 ...DEFAULT_UNIFIED_SETTINGS,
403 providerInstances: {
404 [customId]: {
405 driver: ProviderDriverKind.make("codex"),
406 enabled: true,
407 displayName: "Work",
408 },
409 },
410 };
411 const panel = renderPanel();
412 const card = visitElements(panel, (element) => element.props.instanceId === customId);
413 const next = {
414 driver: ProviderDriverKind.make("codex"),
415 enabled: false,
416 displayName: "Work",
417 };
418 (card?.props.onUpdate as ((instance: typeof next) => void) | undefined)?.(next);
419 await flushPromises();
420
421 expect(settingsState.mutateProviderInstance).toHaveBeenCalledWith(
422 { operation: "upsert", instanceId: customId, instance: next },
423 {},
424 );
425 });
426
427 it("lets the server decide managed ACP cleanup after an atomic delete", async () => {
428 const firstId = ProviderInstanceId.make("acpRegistry_kilo_one");
429 const secondId = ProviderInstanceId.make("acpRegistry_kilo_two");
430 const registryInstance = {
431 driver: ProviderDriverKind.make("acpRegistry"),
432 enabled: true,
433 config: { agentId: "kilo" },
434 };
435 settingsState.value = {
436 ...DEFAULT_UNIFIED_SETTINGS,
437 providerInstances: {
438 [firstId]: registryInstance,
439 [secondId]: registryInstance,
440 },
441 };
442 let panel = renderPanel();
443 const row = visitElements(
444 panel,
445 (element) => element.props.instanceId === firstId && element.props.mode === "list",
446 );
447 (row?.props.onSelect as (() => void) | undefined)?.();
448 panel = renderPanel();
449 const card = visitElements(
450 panel,
451 (element) => element.props.instanceId === firstId && element.props.mode === "editor",
452 );
453 (card?.props.onDelete as (() => void) | undefined)?.();
454 await flushPromises();
455
456 expect(settingsState.mutateProviderInstance).toHaveBeenCalledWith({
457 operation: "remove",
458 instanceId: firstId,
459 });
460 expect(commands.uninstall).toHaveBeenCalledWith({
461 environmentId,
462 input: { agentId: "kilo" },
463 });
464 });
465
466 it("routes explicit ACP browser authentication consent to the selected environment", async () => {
467 const instanceId = ProviderInstanceId.make("acpRegistry_antigravity");
468 const action = {
469 elicitationId: "google-login-1",
470 url: "https://accounts.google.com/login",
471 message: "Continue with Google",
472 };
473 settingsState.value = {
474 ...DEFAULT_UNIFIED_SETTINGS,
475 providerInstances: {
476 [instanceId]: {
477 driver: ProviderDriverKind.make("acpRegistry"),
478 enabled: true,
479 config: { agentId: "antigravity" },
480 },
481 },
482 };
483 atoms.providers = [
484 {
485 ...provider(),
486 instanceId,
487 driver: ProviderDriverKind.make("acpRegistry"),
488 auth: { status: "unauthenticated", action },
489 },
490 ];
491
492 const panel = renderPanel();
493 const card = visitElements(panel, (element) => element.props.instanceId === instanceId);
494 (card?.props.onAcceptUrlAuth as ((candidate: typeof action) => void) | undefined)?.(action);
495 await flushPromises();
496
497 expect(commands.acceptUrlAuth).toHaveBeenCalledWith({
498 environmentId,
499 input: { instanceId, elicitationId: action.elicitationId },
500 });
501 });
502});