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

ProviderSettingsPanel.environment.test.tsx

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