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

AddProviderInstanceDialog.environment.browser.test.tsx

264 lines9.2 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});
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 };
102​
103const dialog = () => (
104 <AddProviderInstanceDialog
105 open
106 environmentId={remoteEnvironmentId}
107 environmentLabel="Remote device"
108 onOpenChange={actions.onOpenChange}
109 />
110);
111function button(label: string) {
112 const found = [...document.querySelectorAll("button")].find(
113 (element) => element.textContent?.trim() === label,
114 );
115 expect(found, `button ${label}`).toBeDefined();
116 return found!;
118const click = (label: string) => act(async () => button(label).click());
119const input = (selector: string) => {
120 const found = document.querySelector<HTMLInputElement>(selector);
121 expect(found, selector).not.toBeNull();
122 return found!;
123};
124async function type(selector: string, value: string) {
125 await userEvent.fill(input(selector), value);
126 await act(async () => input(selector).blur());
128const signInStep = () => document.querySelector('[aria-label="Sign-in step"]');
129​
130async function prepareCodexInstance() {
131 await using stack = new AsyncDisposableStack();
132 const screen = stack.use(await render(dialog()));
133 await click("Configure manually");
134 await type("#add-provider-label", "Work");
135 await click("Next");
136 stack.move();
137 return screen;
139​
140function setup() {
141 actions.canManageProviders = true;
142 actions.toast.mockReset();
143 actions.onOpenChange.mockReset();
144 settingsHooks.read.mockReset().mockReturnValue({ providerInstances: {} });
145 settingsHooks.mutate.mockReset().mockResolvedValue({ _tag: "Success", value: {} });
146 settingsHooks.useMutation.mockReset().mockReturnValue(settingsHooks.mutate);
148​
149describe("AddProviderInstanceDialog environment routing", () => {
150 it("chooses an unused identity for another account without replacing configured instances", async () => {
151 setup();
152 settingsHooks.read.mockReturnValue({
153 providerInstances: { codex_2: { driver: "codex", enabled: false } },
154 });
155 await using _screen = await render(dialog());
156 await click("Configure manually");
157 await click("Next");
158 await click("Add instance");
159 expect(settingsHooks.mutate).toHaveBeenCalledWith({
160 operation: "create",
161 instanceId: "codex_3",
162 instance: {
163 driver: "codex",
164 enabled: true,
165 displayName: "Codex",
166 config: { setupMode: "existing" },
167 },
168 });
169 });
170​
171 it("awaits an atomic create before closing and retains prepared ACP metadata", async () => {
172 setup();
173 const mutation = deferred<{ readonly _tag: "Success"; readonly value: unknown }>();
174 settingsHooks.mutate.mockReturnValueOnce(mutation.promise);
175 await using _screen = await render(dialog());
176 await click("Use Kilo Code");
177​
178 expect(document.body.textContent).toContain("v4.2.0 · binary");
179 await click("Continue to sign-in");
180 expect(settingsHooks.mutate).toHaveBeenCalledWith({
181 operation: "create",
182 instanceId: "acpRegistry_kilo_code",
183 instance: {
184 driver: ProviderDriverKind.make("acpRegistry"),
185 enabled: true,
186 displayName: "Kilo Code",
187 config: {
188 agentId: "kilo",
189 distribution: "auto",
190 registryIconUrl: "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg",
191 },
192 },
193 });
194 expect(signInStep()).toBeNull();
195​
196 await act(async () => mutation.resolve({ _tag: "Success", value: {} }));
197 expect(actions.onOpenChange).not.toHaveBeenCalled();
198 expect(signInStep()?.textContent).toContain("remote-device/acpRegistry_kilo_code");
199 expect(settingsHooks.mutate).toHaveBeenCalledTimes(1);
200 await click("Finish sign-in");
201 expect(actions.onOpenChange).toHaveBeenCalledWith(false);
202 });
203​
204 it("creates a local command in the selected environment without a sign-in step", async () => {
205 setup();
206 await using _screen = await render(dialog());
207 await click("Use local command");
208 await click("Next");
209 expect(document.body.textContent).toContain("Executable is required.");
210 expect(settingsHooks.mutate).not.toHaveBeenCalled();
211​
212 await type("#add-provider-acpRegistry-manual-commandPath", "dsh");
213 const commandArgs = ["--profile", "acp", " literal $(value) ; ", ""];
214 for (const [index, argument] of commandArgs.entries()) {
215 await click("Add argument");
216 if (argument) await type(`input[aria-label="Argument ${index + 1}"]`, argument);
217 }
218 await click("Add variable");
219 await type('input[aria-label="Environment variable name 1"]', "DSH_PROFILE");
220 await act(async () =>
221 document
222 .querySelector<HTMLButtonElement>(
223 'button[aria-label="Mark environment variable DSH_PROFILE as sensitive"]',
224 )!
225 .click(),
226 );
227 await type('input[aria-label="Environment variable value 1"]', "work");
228 await click("Next");
229 await type("#add-provider-label", "Deepseek Harness");
230 await click("Add instance");
231​
232 expect(settingsHooks.useMutation).toHaveBeenCalledWith(remoteEnvironmentId);
233 expect(settingsHooks.mutate).toHaveBeenCalledWith({
234 operation: "create",
235 instanceId: "acpRegistry_deepseek_harness",
236 instance: {
237 driver: "acpRegistry",
238 enabled: true,
239 displayName: "Deepseek Harness",
240 config: { source: "local", commandPath: "dsh", commandArgs },
241 environment: [
242 expect.objectContaining({ name: "DSH_PROFILE", value: "work", sensitive: false }),
243 ],
244 },
245 });
246 expect(actions.onOpenChange).toHaveBeenCalledWith(false);
247 expect(signInStep()).toBeNull();
248 });
249​
250 it("rejects a queued save after the provider grant is revoked", async () => {
251 setup();
252 await using screen = await prepareCodexInstance();
253 const save = button("Add instance");
254 actions.canManageProviders = false;
255 // The rendered button is still enabled; the click must recheck the live grant.
256 await act(async () => save.click());
257​
258 expect(settingsHooks.mutate).not.toHaveBeenCalled();
259 expect(actions.toast).not.toHaveBeenCalled();
260 expect(actions.onOpenChange).not.toHaveBeenCalled();
261 await screen.rerender(dialog());
262 expect(button("Add instance").disabled).toBe(true);
263 });
264});