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

AcpRegistrySearchStep.browser.test.tsx

262 lines8.4 KB

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