Open History to see the last commit
1import { EnvironmentId, ProviderDriverKind, type AcpRegistrySearchAgent } from "@t3tools/contracts";
2import { act } from "react";
3import { createRoot, type Root } from "react-dom/client";
4import { userEvent } from "vite-plus/test/browser";
5import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
6
7const actions = vi.hoisted(() => ({
8 toast: vi.fn(),
9 onOpenChange: vi.fn(),
10 canManageProviders: true,
11}));
12const settingsHooks = vi.hoisted(() => ({
13 read: vi.fn(() => ({ providerInstances: {} })),
14 mutate: vi.fn(),
15 useMutation: vi.fn(),
16}));
17const preparedAgent = vi.hoisted((): AcpRegistrySearchAgent => ({
18 id: "kilo",
19 name: "Kilo Code",
20 version: "4.2.0",
21 description: "Kilo ACP agent",
22 authors: ["Kilo"],
23 license: "Apache-2.0",
24 website: null,
25 repository: null,
26 icon: "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg",
27 distribution: "binary",
28 integrity: "sha256",
29}));
30
31vi.mock(import("@t3tools/client-runtime/state/runtime"), async (original) => ({
32 ...(await original()),
33 squashAtomCommandFailure: () => new Error("The settings update failed."),
34}));
35vi.mock(import("../../hooks/useSettings"), async (original) => ({
36 ...(await original()),
37 useEnvironmentSettings: settingsHooks.read as never,
38 usePersistEnvironmentProviderInstanceMutation: settingsHooks.useMutation as never,
39}));
40vi.mock(import("../../state/session"), async (original) => {
41 const hasScope = (environmentId: EnvironmentId, scope: string) =>
42 environmentId === "remote-device" && scope === "providers:manage" && actions.canManageProviders;
43 return {
44 ...(await original()),
45 useEnvironmentScope: hasScope as never,
46 readEnvironmentScope: hasScope as never,
47 };
48});
49vi.mock(import("../ui/toast"), async (original) => {
50 const actual = await original();
51 return { ...actual, toastManager: { ...actual.toastManager, add: actions.toast } };
52});
53// The registry search and the sign-in step talk to the environment over RPC; these
54// stand-ins expose the choices a user makes there.
55vi.mock(import("./AcpRegistrySearchStep"), async (original) => ({
56 ...(await original()),
57 AcpRegistrySearchStep: ((props: {
58 onPrepared: (agent: AcpRegistrySearchAgent) => void;
59 onManualConfiguration: () => void;
60 onLocalConfiguration: () => void;
61 }) => (
62 <div>
63 <button type="button" onClick={() => props.onPrepared(preparedAgent)}>
64 Use Kilo Code
65 </button>
66 <button type="button" onClick={props.onManualConfiguration}>
67 Enter registry agent
68 </button>
69 <button type="button" onClick={props.onLocalConfiguration}>
70 Use local command
71 </button>
72 </div>
73 )) as never,
74}));
75vi.mock(import("./ProviderWizardAuthenticationStep"), async (original) => ({
76 ...(await original()),
77 ProviderWizardAuthenticationStep: (props: {
78 environmentId: string;
79 instanceId: string;
80 onFinish: () => void;
81 }) => (
82 <section aria-label="Sign-in step">
83 {props.environmentId}/{props.instanceId}
84 <button type="button" onClick={props.onFinish}>
85 Finish sign-in
86 </button>
87 </section>
88 ),
89}));
90
91import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog";
92
93const remoteEnvironmentId = EnvironmentId.make("remote-device");
94
95function deferred<T>() {
96 let resolve!: (value: T) => void;
97 const promise = new Promise<T>((done) => {
98 resolve = done;
99 });
100 return { promise, resolve };
101}
102
103let root: Root;
104
105function render(onOpenChange = actions.onOpenChange) {
106 return act(async () =>
107 root.render(
108 <AddProviderInstanceDialog
109 open
110 environmentId={remoteEnvironmentId}
111 environmentLabel="Remote device"
112 onOpenChange={onOpenChange}
113 />,
114 ),
115 );
116}
117function button(label: string) {
118 const found = [...document.querySelectorAll("button")].find(
119 (element) => element.textContent?.trim() === label,
120 );
121 expect(found, `button ${label}`).toBeDefined();
122 return found!;
123}
124const click = (label: string) => act(async () => button(label).click());
125const input = (selector: string) => {
126 const found = document.querySelector<HTMLInputElement>(selector);
127 expect(found, selector).not.toBeNull();
128 return found!;
129};
130async function type(selector: string, value: string) {
131 await act(async () => userEvent.fill(input(selector), value));
132 await act(async () => input(selector).blur());
133}
134const signInStep = () => document.querySelector('[aria-label="Sign-in step"]');
135
136async function prepareCodexInstance() {
137 await render();
138 await click("Configure manually");
139 await type("#add-provider-label", "Work");
140 await click("Next");
141}
142
143describe("AddProviderInstanceDialog environment routing", () => {
144 beforeEach(() => {
145 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
146 actions.canManageProviders = true;
147 actions.toast.mockReset();
148 actions.onOpenChange.mockReset();
149 settingsHooks.read.mockReset().mockReturnValue({ providerInstances: {} });
150 settingsHooks.mutate.mockReset().mockResolvedValue({ _tag: "Success", value: {} });
151 settingsHooks.useMutation.mockReset().mockReturnValue(settingsHooks.mutate);
152 root = createRoot(document.createElement("div"));
153 });
154 afterEach(async () => {
155 await act(async () => root.unmount());
156 vi.unstubAllGlobals();
157 });
158
159 it("creates a provider with its default identity without typing", async () => {
160 await render();
161 const grok = [...document.querySelectorAll('[role="radio"]')].find((radio) =>
162 radio.textContent?.includes("Grok"),
163 ) as HTMLElement;
164 await act(async () => grok.click());
165 await click("Next");
166 await click("Next");
167 await click("Add instance");
168 expect(settingsHooks.mutate).toHaveBeenCalledWith({
169 operation: "create",
170 instanceId: "grok",
171 instance: { driver: "grok", enabled: true, displayName: "Grok" },
172 });
173 });
174
175 it("chooses an unused identity for another account without replacing configured instances", async () => {
176 settingsHooks.read.mockReturnValue({
177 providerInstances: { codex_2: { driver: "codex", enabled: false } },
178 });
179 await render();
180 await click("Configure manually");
181 await click("Next");
182 await click("Add instance");
183 expect(settingsHooks.mutate).toHaveBeenCalledWith({
184 operation: "create",
185 instanceId: "codex_3",
186 instance: {
187 driver: "codex",
188 enabled: true,
189 displayName: "Codex",
190 config: { setupMode: "existing" },
191 },
192 });
193 });
194
195 it("reads and writes settings through the supplied environment", async () => {
196 await render();
197
198 expect(settingsHooks.read).toHaveBeenCalledWith(remoteEnvironmentId);
199 expect(settingsHooks.useMutation).toHaveBeenCalledWith(remoteEnvironmentId);
200 });
201
202 it("awaits an atomic create before closing and retains prepared ACP metadata", async () => {
203 const mutation = deferred<{ readonly _tag: "Success"; readonly value: unknown }>();
204 settingsHooks.mutate.mockReturnValueOnce(mutation.promise);
205 await render();
206 await click("Use Kilo Code");
207
208 expect(document.body.textContent).toContain("v4.2.0 · binary");
209 await click("Continue to sign-in");
210 expect(settingsHooks.mutate).toHaveBeenCalledWith({
211 operation: "create",
212 instanceId: "acpRegistry_kilo_code",
213 instance: {
214 driver: ProviderDriverKind.make("acpRegistry"),
215 enabled: true,
216 displayName: "Kilo Code",
217 config: {
218 agentId: "kilo",
219 distribution: "auto",
220 registryIconUrl: "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg",
221 },
222 },
223 });
224 expect(signInStep()).toBeNull();
225
226 await act(async () => mutation.resolve({ _tag: "Success", value: {} }));
227 expect(actions.onOpenChange).not.toHaveBeenCalled();
228 expect(signInStep()?.textContent).toContain("remote-device/acpRegistry_kilo_code");
229 expect(settingsHooks.mutate).toHaveBeenCalledTimes(1);
230 await click("Finish sign-in");
231 expect(actions.onOpenChange).toHaveBeenCalledWith(false);
232 });
233
234 it("configures a manually entered registry agent from the first provider screen", async () => {
235 await render();
236 await click("Enter registry agent");
237 await type("#add-provider-acpRegistry-manual-agentId", "devin");
238 await click("Next");
239 await click("Continue to sign-in");
240 expect(settingsHooks.mutate).toHaveBeenCalledWith({
241 operation: "create",
242 instanceId: "acpRegistry_custom",
243 instance: {
244 driver: "acpRegistry",
245 enabled: true,
246 config: { agentId: "devin" },
247 },
248 });
249 expect(signInStep()).not.toBeNull();
250 });
251
252 it("creates a local command in the selected environment without a sign-in step", async () => {
253 await render();
254 await click("Use local command");
255 await click("Next");
256 expect(document.body.textContent).toContain("Executable is required.");
257 expect(settingsHooks.mutate).not.toHaveBeenCalled();
258
259 await type("#add-provider-acpRegistry-manual-commandPath", "dsh");
260 const commandArgs = ["--profile", "acp", " literal $(value) ; ", ""];
261 for (const [index, argument] of commandArgs.entries()) {
262 await click("Add argument");
263 if (argument) await type(`input[aria-label="Argument ${index + 1}"]`, argument);
264 }
265 await click("Add variable");
266 await type('input[aria-label="Environment variable name 1"]', "DSH_PROFILE");
267 await act(async () =>
268 document
269 .querySelector<HTMLButtonElement>(
270 'button[aria-label="Mark environment variable DSH_PROFILE as sensitive"]',
271 )!
272 .click(),
273 );
274 await type('input[aria-label="Environment variable value 1"]', "work");
275 await click("Next");
276 await type("#add-provider-label", "Deepseek Harness");
277 await click("Add instance");
278
279 expect(settingsHooks.useMutation).toHaveBeenCalledWith(remoteEnvironmentId);
280 expect(settingsHooks.mutate).toHaveBeenCalledWith({
281 operation: "create",
282 instanceId: "acpRegistry_deepseek_harness",
283 instance: {
284 driver: "acpRegistry",
285 enabled: true,
286 displayName: "Deepseek Harness",
287 config: { source: "local", commandPath: "dsh", commandArgs },
288 environment: [
289 expect.objectContaining({ name: "DSH_PROFILE", value: "work", sensitive: false }),
290 ],
291 },
292 });
293 expect(actions.onOpenChange).toHaveBeenCalledWith(false);
294 expect(signInStep()).toBeNull();
295 });
296
297 it("keeps the dialog open when the atomic upsert fails", async () => {
298 settingsHooks.mutate.mockResolvedValueOnce({ _tag: "Failure", cause: new Error("Conflict") });
299 await render();
300 await click("Use Kilo Code");
301 await click("Continue to sign-in");
302
303 expect(actions.onOpenChange).not.toHaveBeenCalled();
304 expect(actions.toast).toHaveBeenCalledWith(
305 expect.objectContaining({ type: "error", title: "Could not add provider instance" }),
306 );
307 expect(button("Continue to sign-in").disabled).toBe(false);
308 });
309
310 it("adds an instance with the selected environment's provider grant alone", async () => {
311 await prepareCodexInstance();
312 await click("Add instance");
313
314 expect(settingsHooks.mutate).toHaveBeenCalledWith({
315 operation: "create",
316 instanceId: "codex_work",
317 instance: {
318 driver: "codex",
319 enabled: true,
320 displayName: "Work",
321 config: { setupMode: "existing" },
322 },
323 });
324 expect(actions.toast).toHaveBeenCalledWith(
325 expect.objectContaining({ type: "success", title: "Provider instance added" }),
326 );
327 expect(actions.onOpenChange).toHaveBeenCalledWith(false);
328 });
329
330 it("rejects a queued save after the provider grant is revoked", async () => {
331 await prepareCodexInstance();
332 const save = button("Add instance");
333 actions.canManageProviders = false;
334 // The rendered button is still enabled; the click must recheck the live grant.
335 await act(async () => save.click());
336
337 expect(settingsHooks.mutate).not.toHaveBeenCalled();
338 expect(actions.toast).not.toHaveBeenCalled();
339 expect(actions.onOpenChange).not.toHaveBeenCalled();
340 await render();
341 expect(button("Add instance").disabled).toBe(true);
342 });
343
344 it("keeps a denied draft available when the provider grant arrives", async () => {
345 actions.canManageProviders = false;
346 await prepareCodexInstance();
347 expect(button("Add instance").disabled).toBe(true);
348 expect(settingsHooks.mutate).not.toHaveBeenCalled();
349
350 actions.canManageProviders = true;
351 await render();
352 expect(button("Add instance").disabled).toBe(false);
353 await click("Add instance");
354 expect(settingsHooks.mutate).toHaveBeenCalledOnce();
355 expect(actions.onOpenChange).toHaveBeenCalledWith(false);
356 });
357});