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

AddProviderInstanceDialog.environment.browser.test.tsx

308 lines10.6 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("includes the explicitly added default accent color when creating a provider", async () => {
174 setup();
175 await using _screen = await render(dialog());
176 await click("Show more");
177 await click("Use Kilo Code");
178 await act(async () =>
179 document
180 .querySelector<HTMLButtonElement>('button[aria-label="Add accent color for Kilo Code"]')!
181 .click(),
182 );
183 await click("Add color");
184 await click("Continue to sign-in");
185​
186 expect(settingsHooks.mutate).toHaveBeenCalledWith({
187 operation: "create",
188 instanceId: "acpRegistry_kilo_code",
189 instance: expect.objectContaining({ accentColor: "#2563eb" }),
190 });
191 });
192​
193 it("keeps fx and the ACP Registry under Show more", async () => {
194 setup();
195 await using _screen = await render(dialog());
196 expect(radio("Codex")).toBeDefined();
197 expect(radio("fx")).toBeUndefined();
198 expect(document.body.textContent).not.toContain("Use Kilo Code");
199​
200 await click("Show more");
201 button("Use Kilo Code");
202 await act(async () => radio("fx")!.click());
203 await click("Next");
204 await click("Next");
205 await click("Add instance");
206 expect(settingsHooks.mutate).toHaveBeenCalledWith({
207 operation: "create",
208 instanceId: "fx",
209 instance: { driver: "fx", enabled: true, displayName: "fx" },
210 });
211 });
212​
213 it("awaits an atomic create before closing and retains prepared ACP metadata", async () => {
214 setup();
215 const mutation = deferred<{ readonly _tag: "Success"; readonly value: unknown }>();
216 settingsHooks.mutate.mockReturnValueOnce(mutation.promise);
217 await using _screen = await render(dialog());
218 await click("Show more");
219 await click("Use Kilo Code");
220​
221 expect(document.body.textContent).toContain("v4.2.0 · binary");
222 await click("Continue to sign-in");
223 expect(settingsHooks.mutate).toHaveBeenCalledWith({
224 operation: "create",
225 instanceId: "acpRegistry_kilo_code",
226 instance: {
227 driver: ProviderDriverKind.make("acpRegistry"),
228 enabled: true,
229 displayName: "Kilo Code",
230 config: {
231 agentId: "kilo",
232 distribution: "auto",
233 registryIconUrl: "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg",
234 },
235 },
236 });
237 expect(signInStep()).toBeNull();
238​
239 await act(async () => mutation.resolve({ _tag: "Success", value: {} }));
240 expect(actions.onOpenChange).not.toHaveBeenCalled();
241 expect(signInStep()?.textContent).toContain("remote-device/acpRegistry_kilo_code");
242 expect(settingsHooks.mutate).toHaveBeenCalledTimes(1);
243 await click("Finish sign-in");
244 expect(actions.onOpenChange).toHaveBeenCalledWith(false);
245 });
246​
247 it("creates a local command in the selected environment without a sign-in step", async () => {
248 setup();
249 await using _screen = await render(dialog());
250 await click("Show more");
251 await click("Use local command");
252 await click("Next");
253 expect(document.body.textContent).toContain("Executable is required.");
254 expect(settingsHooks.mutate).not.toHaveBeenCalled();
255​
256 await type("#add-provider-acpRegistry-manual-commandPath", "dsh");
257 const commandArgs = ["--profile", "acp", " literal $(value) ; ", ""];
258 for (const [index, argument] of commandArgs.entries()) {
259 await click("Add argument");
260 if (argument) await type(`input[aria-label="Argument ${index + 1}"]`, argument);
261 }
262 await click("Add variable");
263 await type('input[aria-label="Environment variable name 1"]', "DSH_PROFILE");
264 await act(async () =>
265 document
266 .querySelector<HTMLButtonElement>(
267 'button[aria-label="Mark environment variable DSH_PROFILE as sensitive"]',
268 )!
269 .click(),
270 );
271 await type('input[aria-label="Environment variable value 1"]', "work");
272 await click("Next");
273 await type("#add-provider-label", "Deepseek Harness");
274 await click("Add instance");
275​
276 expect(settingsHooks.useMutation).toHaveBeenCalledWith(remoteEnvironmentId);
277 expect(settingsHooks.mutate).toHaveBeenCalledWith({
278 operation: "create",
279 instanceId: "acpRegistry_deepseek_harness",
280 instance: {
281 driver: "acpRegistry",
282 enabled: true,
283 displayName: "Deepseek Harness",
284 config: { source: "local", commandPath: "dsh", commandArgs },
285 environment: [
286 expect.objectContaining({ name: "DSH_PROFILE", value: "work", sensitive: false }),
287 ],
288 },
289 });
290 expect(actions.onOpenChange).toHaveBeenCalledWith(false);
291 expect(signInStep()).toBeNull();
292 });
293​
294 it("rejects a queued save after the provider grant is revoked", async () => {
295 setup();
296 await using screen = await prepareCodexInstance();
297 const save = button("Add instance");
298 actions.canManageProviders = false;
299 // Click before React renders the revoked grant.
300 await act(async () => save.click());
301​
302 expect(settingsHooks.mutate).not.toHaveBeenCalled();
303 expect(actions.toast).not.toHaveBeenCalled();
304 expect(actions.onOpenChange).not.toHaveBeenCalled();
305 await screen.rerender(dialog());
306 expect(button("Add instance").disabled).toBe(true);
307 });
308});