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

AcpRegistrySearchStep.browser.test.tsx

282 lines9.1 KB

1import {
2 EnvironmentId,
3 ProviderDriverKind,
4 type AcpRegistrySearchAgent,
5 type AcpRegistrySearchInput,
6} from "@t3tools/contracts";
7import * as Cause from "effect/Cause";
8import { act } from "react";
9import { createRoot, type Root } from "react-dom/client";
10import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
11import { page, userEvent } from "vite-plus/test/browser";
12​
13const state = vi.hoisted(() => ({
14 result: null as { readonly agents: ReadonlyArray<AcpRegistrySearchAgent> } | null,
15 error: null as string | null,
16 isPending: false,
17 canManage: true,
18 refresh: vi.fn(),
19 search: vi.fn(),
20 prepare: vi.fn(),
21}));
22​
23vi.mock(import("../../state/server"), async (original) => {
24 const actual = await original();
25 return {
26 ...actual,
27 serverEnvironment: {
28 ...actual.serverEnvironment,
29 searchAcpRegistry: ((input: unknown) => {
30 state.search(input);
31 return "search";
32 }) as never,
33 },
34 };
35});
36vi.mock(import("../../state/session"), async (original) => ({
37 ...(await original()),
38 useEnvironmentScope: () => state.canManage,
39 readEnvironmentScope: () => state.canManage,
40}));
41vi.mock(import("../../state/query"), async (original) => ({
42 ...(await original()),
43 useEnvironmentQuery: (() => ({
44 data: state.result,
45 error: state.error,
46 isPending: state.isPending,
47 refresh: state.refresh,
48 })) as never,
49}));
50vi.mock(import("../../state/use-atom-command"), async (original) => ({
51 ...(await original()),
52 useAtomCommand: (() => state.prepare) as never,
53}));
54​
55import { AcpRegistrySearchStep } from "./AcpRegistrySearchStep";
56​
57const environmentId = EnvironmentId.make("remote-device");
58const gemini: AcpRegistrySearchAgent = {
59 id: "gemini",
60 name: "Gemini CLI",
61 version: "1.2.3",
62 description: "Google's agent",
63 authors: ["Google <gemini-cli@google.com>", "Contributor"],
64 license: "Apache-2.0",
65 website: "https://example.com/docs",
66 repository: "https://example.com/source",
67 icon: null,
68 distribution: "npx",
69 integrity: "registry",
70};
71​
72const roots: Root[] = [];
73let root: Root;
74​
75function render(options?: {
76 readonly configured?: boolean;
77 readonly onPrepared?: (agent: AcpRegistrySearchAgent) => void;
78}) {
79 return act(async () =>
80 root.render(
81 <AcpRegistrySearchStep
82 environmentId={environmentId}
83 providerInstances={
84 options?.configured
85 ? {
86 acpRegistry_gemini: {
87 driver: ProviderDriverKind.make("acpRegistry"),
88 config: { agentId: "gemini" },
89 },
90 }
91 : {}
92 }
93 onPrepared={options?.onPrepared ?? vi.fn()}
94 onManualConfiguration={vi.fn()}
95 />,
96 ),
97 );
99​
100const searchBox = () => page.getByRole("searchbox", { name: "Search ACP Registry" });
101const lastQuery = () =>
102 (state.search.mock.lastCall?.[0] as { input: { query: string } } | undefined)?.input.query;
103​
104function deferred<T>() {
105 let resolve!: (value: T) => void;
106 const promise = new Promise<T>((done) => {
107 resolve = done;
108 });
109 return { promise, resolve };
111​
112beforeEach(() => {
113 state.canManage = true;
114 state.result = null;
115 state.error = null;
116 state.isPending = false;
117 state.refresh.mockReset();
118 state.search.mockReset();
119 state.prepare.mockReset().mockResolvedValue({
120 _tag: "Success",
121 value: { agentId: "gemini", version: "1.2.3", distribution: "npx", prepared: true },
122 });
123 const container = document.createElement("div");
124 document.body.append(container);
125 root = createRoot(container);
126 roots.push(root);
127});
128​
129afterEach(async () => {
130 vi.useRealTimers();
131 for (const mounted of roots.splice(0)) await act(async () => mounted.unmount());
132 document.body.replaceChildren();
133});
134​
135it("shows the full catalog initially and after clearing a debounced search", async () => {
136 const agents = Array.from({ length: 25 }, (_, index) => ({
137 ...gemini,
138 id: `gemini-${index}`,
139 name: `Gemini CLI ${index + 1}`,
140 }));
141 state.search.mockImplementation(({ input }: { input: AcpRegistrySearchInput }) => {
142 state.result = {
143 agents: agents
144 .filter((agent) => agent.name.toLowerCase().includes(input.query.toLowerCase()))
145 .slice(0, input.limit ?? 20),
146 };
147 });
148 const addButtons = () => page.getByRole("button", { name: /^Add Gemini CLI / }).elements();
149 await render();
150 expect(addButtons()).toHaveLength(25);
151 await expect.element(page.getByRole("button", { name: "Add Gemini CLI 25" })).toBeEnabled();
152​
153 vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
154 await userEvent.fill(searchBox(), " Gemini ");
155 await act(async () => vi.advanceTimersByTime(200));
156 await userEvent.fill(searchBox(), " Gemini CLI ");
157 await act(async () => vi.advanceTimersByTime(299));
158 expect(addButtons()).toHaveLength(25);
159 await act(async () => vi.advanceTimersByTime(1));
160 expect(addButtons()).toHaveLength(20);
161​
162 await userEvent.clear(searchBox());
163 await act(async () => vi.advanceTimersByTime(300));
164 expect(addButtons()).toHaveLength(25);
165 await expect.element(page.getByRole("button", { name: "Add Gemini CLI 25" })).toBeEnabled();
166});
167​
168it("shows the loading, error, and empty states", async () => {
169 state.isPending = true;
170 await render();
171 await expect.element(page.getByText("Searching the registry...")).toBeVisible();
172​
173 state.isPending = false;
174 state.error = "Registry unavailable.";
175 await render();
176 await expect.element(page.getByText("Registry unavailable.")).toBeVisible();
177​
178 state.error = null;
179 state.result = { agents: [] };
180 await render();
181 await expect.element(page.getByText("No compatible agents found")).toBeVisible();
182});
183​
184it("submits a typed query at once and refreshes when the same query is submitted again", async () => {
185 await render();
186 // A slow runner must not let the typing debounce submit the query before Enter does.
187 vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
188 await userEvent.fill(searchBox(), "Codex");
189 await userEvent.keyboard("{Enter}");
190 expect(lastQuery()).toBe("Codex");
191 expect(state.refresh).not.toHaveBeenCalled();
192​
193 state.result = { agents: [gemini] };
194 await render();
195 await userEvent.click(searchBox());
196 await userEvent.keyboard("{Enter}");
197 expect(state.refresh).toHaveBeenCalledOnce();
198​
199 state.isPending = true;
200 await render();
201 await expect
202 .element(page.getByRole("status").filter({ hasText: "Refreshing ACP Registry results." }))
203 .toBeInTheDocument();
204 await expect.element(page.getByRole("button", { name: "Add Gemini CLI" })).toBeVisible();
205});
206​
207it("prepares a result before handing it back to the wizard", async () => {
208 state.prepare.mockResolvedValueOnce({
209 _tag: "Success",
210 value: { agentId: "gemini", version: "2.0.0", distribution: "binary", prepared: true },
211 });
212 state.result = { agents: [gemini] };
213 const onPrepared = vi.fn();
214 await render({ onPrepared });
215​
216 await page.getByRole("button", { name: "Add Gemini CLI" }).click();
217​
218 expect(state.prepare).toHaveBeenCalledWith({ environmentId, input: { agentId: "gemini" } });
219 await vi.waitFor(() =>
220 expect(onPrepared).toHaveBeenCalledWith({
221 ...gemini,
222 version: "2.0.0",
223 distribution: "binary",
224 }),
225 );
226});
227​
228it("shows progress, locks the step while an agent prepares, and reports a failure", async () => {
229 const pending = deferred<unknown>();
230 state.prepare.mockReturnValueOnce(pending.promise);
231 state.result = { agents: [{ ...gemini, distribution: "binary" }] };
232 await render();
233​
234 await page.getByRole("button", { name: "Add Gemini CLI" }).click();
235 await expect.element(page.getByRole("button", { name: "Downloading Gemini CLI" })).toBeDisabled();
236 await expect.element(searchBox()).toBeDisabled();
237​
238 await act(async () =>
239 pending.resolve({ _tag: "Failure", cause: Cause.fail(new Error("Registry download failed.")) }),
240 );
241 await expect.element(page.getByText("Registry download failed.")).toBeVisible();
242 await expect.element(page.getByRole("button", { name: "Add Gemini CLI" })).toBeEnabled();
243});
244​
245it("rechecks the grant before preparing an agent", async () => {
246 state.result = { agents: [gemini] };
247 const onPrepared = vi.fn();
248 await render({ onPrepared });
249 state.canManage = false;
250​
251 await page.getByRole("button", { name: "Add Gemini CLI" }).click();
252​
253 expect(state.prepare).not.toHaveBeenCalled();
254 expect(onPrepared).not.toHaveBeenCalled();
255});
256​
257it("ignores prepare completion after unmount", async () => {
258 const pending = deferred<unknown>();
259 state.prepare.mockReturnValueOnce(pending.promise);
260 state.result = { agents: [gemini] };
261 const onPrepared = vi.fn();
262 await render({ onPrepared });
263​
264 await page.getByRole("button", { name: "Add Gemini CLI" }).click();
265 await act(async () => root.unmount());
266 await act(async () =>
267 pending.resolve({
268 _tag: "Success",
269 value: { agentId: "gemini", version: "1.2.3", distribution: "npx", prepared: true },
270 }),
271 );
272​
273 expect(onPrepared).not.toHaveBeenCalled();
274});
275​
276it("shows an existing registry configuration as already added", async () => {
277 state.result = { agents: [gemini] };
278 await render({ configured: true });
279 await expect
280 .element(page.getByRole("button", { name: "Already added Gemini CLI" }))
281 .toBeDisabled();
282});