Open History to see the last commit
1import { RegistryContext } from "@effect/atom-react";
2import {
3 DEFAULT_UNIFIED_SETTINGS,
4 EnvironmentId,
5 ProviderDriverKind,
6 ProviderInstanceId,
7 type ServerProvider,
8 type UnifiedSettings,
9} from "@t3tools/contracts";
10import { AsyncResult, type Atom } from "effect/reactivity";
11import type { ReactNode } from "react";
12import { describe, expect, it, vi } from "vite-plus/test";
13import { page, userEvent } from "vite-plus/test/browser";
14
15import "~/index.css";
16import { act, render } from "../../../test/render";
17
18const state = vi.hoisted(() => ({
19 providers: null as unknown as Atom.Writable<ReadonlyArray<ServerProvider>>,
20 settings: null as unknown as UnifiedSettings,
21 canManageProviders: true,
22 canWriteSettings: true,
23 searchTargetId: null as string | null,
24 readEnvironmentIds: [] as string[],
25 updateEnvironmentIds: [] as string[],
26 mutationEnvironmentIds: [] as string[],
27 refresh: vi.fn(),
28 updateProvider: vi.fn(),
29 uninstall: vi.fn(),
30 acceptUrlAuth: vi.fn(),
31 updateSettings: vi.fn(),
32 updateModelPreferences: vi.fn(),
33 toggleFavorite: vi.fn(),
34 mutateProviderInstance: vi.fn(),
35}));
36
37vi.mock(import("../../state/server"), async (original) => {
38 const actual = await original();
39 const { Atom } = await import("effect/reactivity");
40 const providers = Atom.make<ReadonlyArray<ServerProvider>>([]).pipe(Atom.keepAlive);
41 state.providers = providers;
42 const config = Atom.make(null);
43 const commandLabels = {
44 refreshProviders: "refresh",
45 updateProvider: "update",
46 uninstallAcpRegistryManagedBinary: "uninstall",
47 acceptAcpRegistryUrlAuth: "accept-url-auth",
48 } as const;
49 const labelled = Object.fromEntries(
50 Object.entries(commandLabels).map(([key, label]) => [
51 key,
52 { ...actual.serverEnvironment[key as keyof typeof commandLabels], label },
53 ]),
54 );
55 return {
56 ...actual,
57 providersIgnoringCheckedAtAtom: (() => providers) as never,
58 serverEnvironment: {
59 ...actual.serverEnvironment,
60 ...labelled,
61 configValueAtom: (() => config) as never,
62 providersValueAtom: (() => providers) as never,
63 } as never,
64 };
65});
66vi.mock(import("../../state/use-atom-command"), async (original) => ({
67 ...(await original()),
68 useAtomCommand: ((command: { label?: string }) =>
69 ({
70 refresh: state.refresh,
71 update: state.updateProvider,
72 uninstall: state.uninstall,
73 "accept-url-auth": state.acceptUrlAuth,
74 })[command.label ?? ""] ?? vi.fn()) as never,
75}));
76vi.mock(import("../../state/query"), async (original) => ({
77 ...(await original()),
78 useEnvironmentQuery: (() => ({
79 data: null,
80 error: null,
81 isPending: false,
82 refresh: vi.fn(),
83 })) as never,
84}));
85vi.mock(import("../../hooks/useSettings"), async (original) => ({
86 ...(await original()),
87 useEnvironmentSettings: ((environmentId: string) => {
88 state.readEnvironmentIds.push(environmentId);
89 return state.settings;
90 }) as never,
91 useUpdateEnvironmentSettings: ((environmentId: string) => {
92 state.updateEnvironmentIds.push(environmentId);
93 return state.updateSettings;
94 }) as never,
95 useUpdateEnvironmentModelPreferences: (() => state.updateModelPreferences) as never,
96 useToggleEnvironmentModelFavorite: (() => state.toggleFavorite) as never,
97 usePersistEnvironmentProviderInstanceMutation: ((environmentId: string) => {
98 state.mutationEnvironmentIds.push(environmentId);
99 return state.mutateProviderInstance;
100 }) as never,
101}));
102vi.mock(import("../../state/session"), async (original) => {
103 const scope = (environmentId: string, requested: string) =>
104 environmentId === "remote-device" &&
105 (requested === "providers:manage"
106 ? state.canManageProviders
107 : requested === "settings:write"
108 ? state.canWriteSettings
109 : requested === "orchestration:read");
110 return {
111 ...(await original()),
112 useEnvironmentScope: scope as never,
113 readEnvironmentScope: scope as never,
114 };
115});
116vi.mock(import("../../state/entities"), async (original) => ({
117 ...(await original()),
118 useProjects: (() => []) as never,
119}));
120vi.mock(import("./settingsLayout"), async (original) => ({
121 ...(await original()),
122 useSettingsSearchTargetId: () => state.searchTargetId,
123 // The real row reads write permission and overrides from live environment state.
124 SettingsRow: (({
125 id,
126 title,
127 description,
128 status,
129 control,
130 children,
131 }: {
132 id?: string;
133 title: ReactNode;
134 description?: ReactNode;
135 status?: ReactNode;
136 control?: ReactNode;
137 children?: ReactNode;
138 }) => (
139 <div id={id}>
140 <h4>{title}</h4>
141 {description}
142 {status}
143 {control}
144 {children}
145 </div>
146 )) as never,
147}));
148// Its own data flows are covered by its suite; this one is about the panel.
149vi.mock(import("./UsageProviderSettings"), async (original) => ({
150 ...(await original()),
151 UsageProviderSettings: (() => null) as never,
152}));
153vi.mock(import("../ProviderUpdatesAction"), async (original) => ({
154 ...(await original()),
155 ProviderUpdatesAction: (() => null) as never,
156}));
157
158import { appAtomRegistry } from "~/rpc/atomRegistry";
159import { EnvironmentProviderSettings } from "./ProviderSettingsPanel";
160
161const environmentId = EnvironmentId.make("remote-device");
162const codexId = ProviderInstanceId.make("codex");
163const customId = ProviderInstanceId.make("codex_work");
164
165function provider(): ServerProvider {
166 return {
167 instanceId: codexId,
168 driver: ProviderDriverKind.make("codex"),
169 enabled: true,
170 installed: true,
171 version: "1.0.0",
172 status: "ready",
173 auth: { status: "authenticated" },
174 checkedAt: "2026-07-24T12:00:00.000Z",
175 models: [{ slug: "chosen", name: "Chosen", isCustom: false, capabilities: null }],
176 slashCommands: [],
177 skills: [],
178 versionAdvisory: {
179 status: "behind_latest",
180 currentVersion: "1.0.0",
181 latestVersion: "1.1.0",
182 updateCommand: "pnpm add -g @openai/codex@latest",
183 canUpdate: true,
184 checkedAt: "2026-07-24T12:00:00.000Z",
185 message: "Update available.",
186 },
187 };
188}
189
190const setProviders = (providers: ReadonlyArray<ServerProvider>) =>
191 act(async () => appAtomRegistry.set(state.providers, providers));
192
193function panel(options?: {
194 readonly readOnly?: boolean;
195 readonly targetInstanceId?: ProviderInstanceId;
196}) {
197 return (
198 <RegistryContext.Provider value={appAtomRegistry}>
199 <div className="@container/providers">
200 <EnvironmentProviderSettings
201 environmentId={environmentId}
202 environmentLabel="Remote device"
203 {...(options?.readOnly === undefined ? {} : { readOnly: options.readOnly })}
204 {...(options?.targetInstanceId === undefined
205 ? {}
206 : { targetInstanceId: options.targetInstanceId })}
207 />
208 </div>
209 </RegistryContext.Provider>
210 );
211}
212
213// The section header and the end of the provider list both offer Add provider.
214
215async function setup() {
216 await page.viewport(1280, 900);
217 state.settings = DEFAULT_UNIFIED_SETTINGS;
218 state.canManageProviders = true;
219 state.canWriteSettings = true;
220 state.searchTargetId = null;
221 state.readEnvironmentIds = [];
222 state.updateEnvironmentIds = [];
223 state.mutationEnvironmentIds = [];
224 state.updateSettings.mockReset();
225 state.updateModelPreferences.mockReset();
226 state.toggleFavorite.mockReset();
227 state.mutateProviderInstance.mockReset().mockResolvedValue(AsyncResult.success({}));
228 state.refresh.mockReset().mockResolvedValue(AsyncResult.success(undefined));
229 state.updateProvider.mockReset().mockResolvedValue(AsyncResult.success(undefined));
230 state.uninstall.mockReset().mockResolvedValue(AsyncResult.success({}));
231 state.acceptUrlAuth.mockReset().mockResolvedValue(AsyncResult.success({ accepted: true }));
232 await setProviders([]);
233}
234
235describe("EnvironmentProviderSettings routing", () => {
236 it("does not substitute another account when the requested instance was removed", async () => {
237 await setup();
238 await setProviders([provider()]);
239 await using _screen = await render(panel({ targetInstanceId: customId }));
240 await expect
241 .element(page.getByText("This provider instance is no longer available on this device."))
242 .toBeVisible();
243 expect(state.updateSettings).not.toHaveBeenCalled();
244 });
245
246 it("updates one provider instance without sending a stale whole map", async () => {
247 await setup();
248 state.settings = {
249 ...DEFAULT_UNIFIED_SETTINGS,
250 providerInstances: {
251 [customId]: {
252 driver: ProviderDriverKind.make("codex"),
253 enabled: true,
254 displayName: "Work",
255 },
256 },
257 };
258 await using _screen = await render(panel());
259 await userEvent.click(page.getByRole("switch", { name: "Enable Work" }).first());
260
261 expect(state.mutateProviderInstance).toHaveBeenCalledWith(
262 {
263 operation: "upsert",
264 instanceId: customId,
265 instance: { driver: ProviderDriverKind.make("codex"), enabled: false, displayName: "Work" },
266 },
267 {},
268 );
269 });
270
271 it("routes explicit ACP browser authentication consent to the selected environment", async () => {
272 await setup();
273 const instanceId = ProviderInstanceId.make("acpRegistry_antigravity");
274 const action = {
275 elicitationId: "google-login-1",
276 url: "https://accounts.google.com/login",
277 message: "Continue with Google",
278 };
279 state.settings = {
280 ...DEFAULT_UNIFIED_SETTINGS,
281 providerInstances: {
282 [instanceId]: {
283 driver: ProviderDriverKind.make("acpRegistry"),
284 enabled: true,
285 config: { agentId: "antigravity" },
286 },
287 },
288 };
289 await setProviders([
290 {
291 ...provider(),
292 instanceId,
293 driver: ProviderDriverKind.make("acpRegistry"),
294 auth: { status: "unauthenticated", action },
295 },
296 ]);
297 await using _screen = await render(panel({ targetInstanceId: instanceId }));
298 const link = page.getByRole("link", { name: "Continue authentication" });
299 link.element().addEventListener("click", (event) => event.preventDefault());
300 await userEvent.click(link);
301
302 expect(state.acceptUrlAuth).toHaveBeenCalledWith({
303 environmentId,
304 input: { instanceId, elicitationId: action.elicitationId },
305 });
306 });
307});