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

AddProviderInstanceDialog.environment.browser.test.tsx

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