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

AddProviderInstanceDialog.environment.test.tsx

424 lines14.8 KB

1import { EnvironmentId, ProviderDriverKind, type AcpRegistrySearchAgent } from "@t3tools/contracts";
2import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
3​
4import { visitElements } from "../../test/reactElementTree";
5import { reactHookHarness as hooks } from "../../test/reactHookHarness";
6​
7const actions = vi.hoisted(() => ({
8 update: vi.fn(),
9 toast: vi.fn(),
10 onOpenChange: vi.fn(),
11 canManageProviders: true,
12}));
13​
14const settingsHooks = vi.hoisted(() => ({
15 read: vi.fn(() => ({ providerInstances: {} })),
16 mutate: vi.fn(),
17 useMutation: vi.fn(),
18}));
19​
20vi.mock("react", async (importOriginal) => {
21 const actual = await importOriginal<typeof import("react")>();
22 const { reactHookHarness } = await import("../../test/reactHookHarness");
23 return {
24 ...actual,
25 useMemo: reactHookHarness.useMemo,
26 useState: reactHookHarness.useState,
27 };
28});
29​
30vi.mock("react/compiler-runtime", async () => {
31 const { reactHookHarness } = await import("../../test/reactHookHarness");
32 return { c: reactHookHarness.useMemoCache };
33});
34​
35vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => ({
36 ...(await importOriginal<typeof import("@t3tools/client-runtime/state/runtime")>()),
37 squashAtomCommandFailure: () => new Error("The settings update failed."),
38}));
39​
40vi.mock("../../hooks/useSettings", () => ({
41 useEnvironmentSettings: settingsHooks.read,
42 usePersistEnvironmentProviderInstanceMutation: settingsHooks.useMutation,
43}));
44​
45vi.mock("../../state/session", async (importOriginal) => {
46 const actual = await importOriginal<typeof import("../../state/session")>();
47 const hasScope = (environmentId: EnvironmentId, scope: string) =>
48 environmentId === "remote-device" && scope === "providers:manage" && actions.canManageProviders;
49 return { ...actual, useEnvironmentScope: hasScope, readEnvironmentScope: hasScope };
50});
51​
52vi.mock("../ui/toast", () => ({ toastManager: { add: actions.toast } }));
53​
54import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog";
55​
56const remoteEnvironmentId = EnvironmentId.make("remote-device");
57const preparedAgent: AcpRegistrySearchAgent = {
58 id: "kilo",
59 name: "Kilo Code",
60 version: "4.2.0",
61 description: "Kilo ACP agent",
62 authors: ["Kilo"],
63 license: "Apache-2.0",
64 website: null,
65 repository: null,
66 icon: "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg",
67 distribution: "binary",
68 integrity: "sha256",
69};
70​
71function render(onOpenChange = vi.fn()) {
72 hooks.beginRender();
73 return AddProviderInstanceDialog({
74 open: true,
75 environmentId: remoteEnvironmentId,
76 environmentLabel: "Remote device",
77 onOpenChange,
78 });
80​
81function findByChildren(tree: ReturnType<typeof render>, children: string) {
82 const result = visitElements(tree, (element) => element.props.children === children);
83 expect(result).not.toBeNull();
84 return result!;
86​
87async function selectPreparedAcp() {
88 const searchStep = render();
89 const search = visitElements(
90 searchStep,
91 (element) =>
92 typeof element.type === "function" && element.type.name === "AcpRegistrySearchStep",
93 );
94 expect(search).not.toBeNull();
95 (search?.props.onPrepared as ((agent: AcpRegistrySearchAgent) => void) | undefined)?.(
96 preparedAgent,
97 );
99​
100function renderDialog() {
101 hooks.beginRender();
102 return AddProviderInstanceDialog({
103 open: true,
104 environmentId: remoteEnvironmentId,
105 environmentLabel: "Remote device",
106 onOpenChange: actions.onOpenChange,
107 });
109​
110function button(dialog: unknown, label: string) {
111 const element = visitElements(
112 dialog,
113 (entry) => entry.props.children === label && typeof entry.props.onClick === "function",
114 );
115 if (!element) throw new Error(`Missing button: ${label}`);
116 return element;
118​
119function prepareInstance() {
120 let dialog = renderDialog();
121 (button(dialog, "Configure manually").props.onClick as () => void)();
122 dialog = renderDialog();
123 const label = visitElements(dialog, (entry) => entry.props.placeholder === "e.g. Work");
124 if (!label) throw new Error("Missing instance label input.");
125 (label.props.onChange as (event: { target: { value: string } }) => void)({
126 target: { value: "Work" },
127 });
128 dialog = renderDialog();
129 (button(dialog, "Next").props.onClick as () => void)();
130 return renderDialog();
132​
133describe("AddProviderInstanceDialog environment routing", () => {
134 beforeEach(() => {
135 hooks.reset();
136 actions.canManageProviders = true;
137 actions.toast.mockReset();
138 actions.onOpenChange.mockReset();
139 settingsHooks.read.mockReset().mockReturnValue({ providerInstances: {} });
140 settingsHooks.mutate.mockReset().mockResolvedValue({ _tag: "Success", value: {} });
141 settingsHooks.useMutation.mockReset().mockReturnValue(settingsHooks.mutate);
142 });
143​
144 it("creates a provider with its default identity without typing", async () => {
145 let tree = render();
146 const group = visitElements(
147 tree,
148 (element) => element.props["aria-labelledby"] === "add-instance-driver-label",
149 );
150 (group!.props.onValueChange as (value: string) => void)("grok");
151 tree = render();
152 (findByChildren(tree, "Next").props.onClick as () => void)();
153 tree = render();
154 (findByChildren(tree, "Next").props.onClick as () => void)();
155 tree = render();
156 (findByChildren(tree, "Add instance").props.onClick as () => void)();
157 await Promise.resolve();
158 expect(settingsHooks.mutate).toHaveBeenCalledWith({
159 operation: "create",
160 instanceId: "grok",
161 instance: { driver: "grok", enabled: true, displayName: "Grok" },
162 });
163 });
164​
165 it("chooses an unused identity for another account without replacing configured instances", async () => {
166 settingsHooks.read.mockReturnValue({
167 providerInstances: {
168 codex_2: { driver: "codex", enabled: false },
169 },
170 });
171 let tree = render();
172 (findByChildren(tree, "Configure manually").props.onClick as () => void)();
173 tree = render();
174 (findByChildren(tree, "Next").props.onClick as () => void)();
175 tree = render();
176 (findByChildren(tree, "Add instance").props.onClick as () => void)();
177 await Promise.resolve();
178 expect(settingsHooks.mutate).toHaveBeenCalledWith({
179 operation: "create",
180 instanceId: "codex_3",
181 instance: {
182 driver: "codex",
183 enabled: true,
184 displayName: "Codex",
185 config: { setupMode: "existing" },
186 },
187 });
188 });
189​
190 it("reads and writes settings through the supplied environment", () => {
191 render();
192​
193 expect(settingsHooks.read).toHaveBeenCalledWith(remoteEnvironmentId);
194 expect(settingsHooks.useMutation).toHaveBeenCalledWith(remoteEnvironmentId);
195 });
196​
197 it("awaits an atomic create before closing and retains prepared ACP metadata", async () => {
198 const onOpenChange = vi.fn();
199 let resolveMutation!: (value: { readonly _tag: "Success"; readonly value: unknown }) => void;
200 settingsHooks.mutate.mockReturnValueOnce(
201 new Promise((resolve) => {
202 resolveMutation = resolve;
203 }),
204 );
205 await selectPreparedAcp();
206​
207 const identityStep = render(onOpenChange);
208 expect(
209 visitElements(identityStep, (element) => {
210 const content = JSON.stringify(element.props.children);
211 return content?.includes("4.2.0") === true && content.includes("binary");
212 }),
213 ).not.toBeNull();
214 (
215 findByChildren(identityStep, "Continue to sign-in").props.onClick as (() => void) | undefined
216 )?.();
217 expect(settingsHooks.mutate).toHaveBeenCalledWith({
218 operation: "create",
219 instanceId: "acpRegistry_kilo_code",
220 instance: {
221 driver: ProviderDriverKind.make("acpRegistry"),
222 enabled: true,
223 displayName: "Kilo Code",
224 config: {
225 agentId: "kilo",
226 distribution: "auto",
227 registryIconUrl: "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg",
228 },
229 },
230 });
231 expect(onOpenChange).not.toHaveBeenCalled();
232​
233 resolveMutation({ _tag: "Success", value: {} });
234 await Promise.resolve();
235 await Promise.resolve();
236 expect(onOpenChange).not.toHaveBeenCalled();
237 const signInStep = render(onOpenChange);
238 const authentication = visitElements(
239 signInStep,
240 (element) =>
241 typeof element.type === "function" &&
242 element.type.name === "ProviderWizardAuthenticationStep",
243 );
244 expect(authentication?.props.instanceId).toBe("acpRegistry_kilo_code");
245 expect(authentication?.props.environmentId).toBe(remoteEnvironmentId);
246 expect(settingsHooks.mutate).toHaveBeenCalledTimes(1);
247 (authentication!.props.onFinish as () => void)();
248 expect(onOpenChange).toHaveBeenCalledWith(false);
249 });
250​
251 it("configures a manually entered registry agent from the first provider screen", async () => {
252 let tree = render();
253 const search = visitElements(
254 tree,
255 (element) =>
256 typeof element.type === "function" && element.type.name === "AcpRegistrySearchStep",
257 );
258 (search!.props.onManualConfiguration as () => void)();
259 tree = render();
260 const configuration = visitElements(
261 tree,
262 (element) => element.props.idPrefix === "add-provider-acpRegistry-manual",
263 );
264 (configuration!.props.onChange as (value: Record<string, unknown>) => void)({
265 agentId: "devin",
266 });
267 tree = render();
268 (findByChildren(tree, "Next").props.onClick as () => void)();
269 tree = render();
270 (findByChildren(tree, "Continue to sign-in").props.onClick as () => void)();
271 await Promise.resolve();
272 await Promise.resolve();
273 expect(settingsHooks.mutate).toHaveBeenCalledWith({
274 operation: "create",
275 instanceId: "acpRegistry_custom",
276 instance: {
277 driver: "acpRegistry",
278 enabled: true,
279 config: { agentId: "devin" },
280 },
281 });
282 tree = render();
283 expect(
284 visitElements(
285 tree,
286 (element) =>
287 typeof element.type === "function" &&
288 element.type.name === "ProviderWizardAuthenticationStep",
289 ),
290 ).not.toBeNull();
291 });
292​
293 it("creates a local command in the selected environment without a sign-in step", async () => {
294 const onOpenChange = vi.fn();
295 let tree = render(onOpenChange);
296 const search = visitElements(
297 tree,
298 (element) =>
299 typeof element.type === "function" && element.type.name === "AcpRegistrySearchStep",
300 );
301 (search!.props.onLocalConfiguration as () => void)();
302 tree = render(onOpenChange);
303 (findByChildren(tree, "Next").props.onClick as () => void)();
304 tree = render(onOpenChange);
305 expect(findByChildren(tree, "Executable is required.")).not.toBeNull();
306 expect(settingsHooks.mutate).not.toHaveBeenCalled();
307​
308 const configuration = visitElements(
309 tree,
310 (element) => element.props.idPrefix === "add-provider-acpRegistry-manual",
311 );
312 const commandArgs = ["--profile", "acp", " literal $(value) ; ", ""];
313 (configuration!.props.onChange as (value: Record<string, unknown>) => void)({
314 source: "local",
315 commandPath: "dsh",
316 commandArgs,
317 });
318 const environmentEditor = visitElements(
319 tree,
320 (element) =>
321 typeof element.type === "function" && element.type.name === "ProviderEnvironmentSection",
322 );
323 const environment = [{ name: "DSH_PROFILE", value: "work", sensitive: false }];
324 (environmentEditor!.props.onChange as (value: typeof environment) => void)(environment);
325 tree = render(onOpenChange);
326 (findByChildren(tree, "Next").props.onClick as () => void)();
327 tree = render(onOpenChange);
328 const label = visitElements(tree, (element) => element.props.id === "add-provider-label");
329 (label!.props.onChange as (event: { target: { value: string } }) => void)({
330 target: { value: "Deepseek Harness" },
331 });
332 tree = render(onOpenChange);
333 (findByChildren(tree, "Add instance").props.onClick as () => void)();
334 await Promise.resolve();
335 await Promise.resolve();
336​
337 expect(settingsHooks.useMutation).toHaveBeenCalledWith(remoteEnvironmentId);
338 expect(settingsHooks.mutate).toHaveBeenCalledWith({
339 operation: "create",
340 instanceId: "acpRegistry_deepseek_harness",
341 instance: {
342 driver: "acpRegistry",
343 enabled: true,
344 displayName: "Deepseek Harness",
345 config: { source: "local", commandPath: "dsh", commandArgs },
346 environment,
347 },
348 });
349 expect(onOpenChange).toHaveBeenCalledWith(false);
350 tree = render(onOpenChange);
351 expect(
352 visitElements(
353 tree,
354 (element) =>
355 typeof element.type === "function" &&
356 element.type.name === "ProviderWizardAuthenticationStep",
357 ),
358 ).toBeNull();
359 });
360​
361 it("keeps the dialog open when the atomic upsert fails", async () => {
362 settingsHooks.mutate.mockResolvedValueOnce({ _tag: "Failure", cause: new Error("Conflict") });
363 const onOpenChange = vi.fn();
364 await selectPreparedAcp();
365​
366 const identityStep = render(onOpenChange);
367 (
368 findByChildren(identityStep, "Continue to sign-in").props.onClick as (() => void) | undefined
369 )?.();
370 await Promise.resolve();
371 await Promise.resolve();
372​
373 expect(onOpenChange).not.toHaveBeenCalled();
374 });
375​
376 it("adds an instance with the selected environment's provider grant alone", async () => {
377 const dialog = prepareInstance();
378 (button(dialog, "Add instance").props.onClick as () => void)();
379​
380 await Promise.resolve();
381 expect(settingsHooks.mutate).toHaveBeenCalledWith({
382 operation: "create",
383 instanceId: "codex_work",
384 instance: {
385 driver: "codex",
386 enabled: true,
387 displayName: "Work",
388 config: { setupMode: "existing" },
389 },
390 });
391 expect(actions.toast).toHaveBeenCalledWith(
392 expect.objectContaining({ type: "success", title: "Provider instance added" }),
393 );
394 expect(actions.onOpenChange).toHaveBeenCalledWith(false);
395 });
396​
397 it("rejects a queued save after the provider grant is revoked", () => {
398 const dialog = prepareInstance();
399 const save = button(dialog, "Add instance").props.onClick as () => void;
400 actions.canManageProviders = false;
401 save();
402​
403 expect(settingsHooks.mutate).not.toHaveBeenCalled();
404 expect(actions.toast).not.toHaveBeenCalled();
405 expect(actions.onOpenChange).not.toHaveBeenCalled();
406 expect(button(renderDialog(), "Add instance").props.disabled).toBe(true);
407 });
408​
409 it("keeps a denied draft available when the provider grant arrives", async () => {
410 actions.canManageProviders = false;
411 let dialog = prepareInstance();
412 (button(dialog, "Add instance").props.onClick as () => void)();
413 expect(settingsHooks.mutate).not.toHaveBeenCalled();
414 expect(actions.toast).not.toHaveBeenCalled();
415​
416 actions.canManageProviders = true;
417 dialog = renderDialog();
418 expect(button(dialog, "Add instance").props.disabled).toBe(false);
419 (button(dialog, "Add instance").props.onClick as () => void)();
420 await Promise.resolve();
421 expect(settingsHooks.mutate).toHaveBeenCalledOnce();
422 expect(actions.onOpenChange).toHaveBeenCalledWith(false);
423 });
424});