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

AddProviderInstanceDialog.environment.browser.test.tsx

288 lines9.9 KB

1import { EnvironmentId, ProviderDriverKind, type AcpRegistrySearchAgent } from "@t3tools/contracts";
2import { userEvent } from "vite-plus/test/browser";
3import { describe, expect, it, vi } from "vite-plus/test";
4​
5import { act, render } from "../../../test/render";
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});
53vi.mock(import("./AcpRegistrySearchStep"), async (original) => ({
54 ...(await original()),
55 AcpRegistrySearchStep: ((props: {
56 onPrepared: (agent: AcpRegistrySearchAgent) => void;
57 onManualConfiguration: () => void;
58 onLocalConfiguration: () => void;
59 }) => (
60 <div>
61 <button type="button" onClick={() => props.onPrepared(preparedAgent)}>
62 Use Kilo Code
63 </button>
64 <button type="button" onClick={props.onManualConfiguration}>
65 Enter registry agent
66 </button>
67 <button type="button" onClick={props.onLocalConfiguration}>
68 Use local command
69 </button>
70 </div>
71 )) as never,
72}));
73vi.mock(import("./ProviderWizardAuthenticationStep"), async (original) => ({
74 ...(await original()),
75 ProviderWizardAuthenticationStep: (props: {
76 environmentId: string;
77 instanceId: string;
78 onFinish: () => void;
79 }) => (
80 <section aria-label="Sign-in step">
81 {props.environmentId}/{props.instanceId}
82 <button type="button" onClick={props.onFinish}>
83 Finish sign-in
84 </button>
85 </section>
86 ),
87}));
88​
89import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog";
90​
91const remoteEnvironmentId = EnvironmentId.make("remote-device");
92​
93function deferred<T>() {
94 let resolve!: (value: T) => void;
95 const promise = new Promise<T>((done) => {
96 resolve = done;
97 });
98 return { promise, resolve };
100​
101const dialog = () => (
102 <AddProviderInstanceDialog
103 open
104 environmentId={remoteEnvironmentId}
105 environmentLabel="Remote device"
106 onOpenChange={actions.onOpenChange}
107 />
108);
109function button(label: string) {
110 const found = [...document.querySelectorAll("button")].find(
111 (element) => element.textContent?.trim() === label,
112 );
113 expect(found, `button ${label}`).toBeDefined();
114 return found!;
116const click = (label: string) => act(async () => button(label).click());
117const radio = (label: string) =>
118 [...document.querySelectorAll<HTMLElement>('[role="radio"]')].find(
119 (element) => element.textContent?.trim() === label,
120 );
121const input = (selector: string) => {
122 const found = document.querySelector<HTMLInputElement>(selector);
123 expect(found, selector).not.toBeNull();
124 return found!;
125};
126async function type(selector: string, value: string) {
127 await userEvent.fill(input(selector), value);
128 await act(async () => input(selector).blur());
130const signInStep = () => document.querySelector('[aria-label="Sign-in step"]');
131​
132async function prepareCodexInstance() {
133 await using stack = new AsyncDisposableStack();
134 const screen = stack.use(await render(dialog()));
135 await click("Configure manually");
136 await type("#add-provider-label", "Work");
137 await click("Next");
138 stack.move();
139 return screen;
141​
142function setup() {
143 actions.canManageProviders = true;
144 actions.toast.mockReset();
145 actions.onOpenChange.mockReset();
146 settingsHooks.read.mockReset().mockReturnValue({ providerInstances: {} });
147 settingsHooks.mutate.mockReset().mockResolvedValue({ _tag: "Success", value: {} });
148 settingsHooks.useMutation.mockReset().mockReturnValue(settingsHooks.mutate);
150​
151describe("AddProviderInstanceDialog environment routing", () => {
152 it("chooses an unused identity for another account without replacing configured instances", async () => {
153 setup();
154 settingsHooks.read.mockReturnValue({
155 providerInstances: { codex_2: { driver: "codex", enabled: false } },
156 });
157 await using _screen = await render(dialog());
158 await click("Configure manually");
159 await click("Next");
160 await click("Add instance");
161 expect(settingsHooks.mutate).toHaveBeenCalledWith({
162 operation: "create",
163 instanceId: "codex_3",
164 instance: {
165 driver: "codex",
166 enabled: true,
167 displayName: "Codex",
168 config: { setupMode: "existing" },
169 },
170 });
171 });
172​
173 it("keeps fx and the ACP Registry under Show more", async () => {
174 setup();
175 await using _screen = await render(dialog());
176 expect(radio("Codex")).toBeDefined();
177 expect(radio("fx")).toBeUndefined();
178 expect(document.body.textContent).not.toContain("Use Kilo Code");
179​
180 await click("Show more");
181 button("Use Kilo Code");
182 await act(async () => radio("fx")!.click());
183 await click("Next");
184 await click("Next");
185 await click("Add instance");
186 expect(settingsHooks.mutate).toHaveBeenCalledWith({
187 operation: "create",
188 instanceId: "fx",
189 instance: { driver: "fx", enabled: true, displayName: "fx" },
190 });
191 });
192​
193 it("awaits an atomic create before closing and retains prepared ACP metadata", async () => {
194 setup();
195 const mutation = deferred<{ readonly _tag: "Success"; readonly value: unknown }>();
196 settingsHooks.mutate.mockReturnValueOnce(mutation.promise);
197 await using _screen = await render(dialog());
198 await click("Show more");
199 await click("Use Kilo Code");
200​
201 expect(document.body.textContent).toContain("v4.2.0 · binary");
202 await click("Continue to sign-in");
203 expect(settingsHooks.mutate).toHaveBeenCalledWith({
204 operation: "create",
205 instanceId: "acpRegistry_kilo_code",
206 instance: {
207 driver: ProviderDriverKind.make("acpRegistry"),
208 enabled: true,
209 displayName: "Kilo Code",
210 config: {
211 agentId: "kilo",
212 distribution: "auto",
213 registryIconUrl: "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg",
214 },
215 },
216 });
217 expect(signInStep()).toBeNull();
218​
219 await act(async () => mutation.resolve({ _tag: "Success", value: {} }));
220 expect(actions.onOpenChange).not.toHaveBeenCalled();
221 expect(signInStep()?.textContent).toContain("remote-device/acpRegistry_kilo_code");
222 expect(settingsHooks.mutate).toHaveBeenCalledTimes(1);
223 await click("Finish sign-in");
224 expect(actions.onOpenChange).toHaveBeenCalledWith(false);
225 });
226​
227 it("creates a local command in the selected environment without a sign-in step", async () => {
228 setup();
229 await using _screen = await render(dialog());
230 await click("Show more");
231 await click("Use local command");
232 await click("Next");
233 expect(document.body.textContent).toContain("Executable is required.");
234 expect(settingsHooks.mutate).not.toHaveBeenCalled();
235​
236 await type("#add-provider-acpRegistry-manual-commandPath", "dsh");
237 const commandArgs = ["--profile", "acp", " literal $(value) ; ", ""];
238 for (const [index, argument] of commandArgs.entries()) {
239 await click("Add argument");
240 if (argument) await type(`input[aria-label="Argument ${index + 1}"]`, argument);
241 }
242 await click("Add variable");
243 await type('input[aria-label="Environment variable name 1"]', "DSH_PROFILE");
244 await act(async () =>
245 document
246 .querySelector<HTMLButtonElement>(
247 'button[aria-label="Mark environment variable DSH_PROFILE as sensitive"]',
248 )!
249 .click(),
250 );
251 await type('input[aria-label="Environment variable value 1"]', "work");
252 await click("Next");
253 await type("#add-provider-label", "Deepseek Harness");
254 await click("Add instance");
255​
256 expect(settingsHooks.useMutation).toHaveBeenCalledWith(remoteEnvironmentId);
257 expect(settingsHooks.mutate).toHaveBeenCalledWith({
258 operation: "create",
259 instanceId: "acpRegistry_deepseek_harness",
260 instance: {
261 driver: "acpRegistry",
262 enabled: true,
263 displayName: "Deepseek Harness",
264 config: { source: "local", commandPath: "dsh", commandArgs },
265 environment: [
266 expect.objectContaining({ name: "DSH_PROFILE", value: "work", sensitive: false }),
267 ],
268 },
269 });
270 expect(actions.onOpenChange).toHaveBeenCalledWith(false);
271 expect(signInStep()).toBeNull();
272 });
273​
274 it("rejects a queued save after the provider grant is revoked", async () => {
275 setup();
276 await using screen = await prepareCodexInstance();
277 const save = button("Add instance");
278 actions.canManageProviders = false;
279 // Click before React renders the revoked grant.
280 await act(async () => save.click());
281​
282 expect(settingsHooks.mutate).not.toHaveBeenCalled();
283 expect(actions.toast).not.toHaveBeenCalled();
284 expect(actions.onOpenChange).not.toHaveBeenCalled();
285 await screen.rerender(dialog());
286 expect(button("Add instance").disabled).toBe(true);
287 });
288});