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

ProviderSettingsPanel.environment.browser.test.tsx

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