Open History to see the last commit
1import type { ReactElement } from "react";
2import { EnvironmentId, ProviderDriverKind, type AcpRegistrySearchAgent } from "@t3tools/contracts";
3import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4
5import { visitElements } from "../../test/reactElementTree";
6import { reactHookHarness as hooks } from "../../test/reactHookHarness";
7
8const atoms = vi.hoisted(() => ({
9 search: Symbol("acp-search"),
10 prepare: Symbol("acp-prepare"),
11}));
12
13const state = vi.hoisted(() => ({
14 result: null as { readonly agents: ReadonlyArray<AcpRegistrySearchAgent> } | null,
15 error: null as string | null,
16 isPending: false,
17 refresh: vi.fn(),
18 search: vi.fn(() => atoms.search),
19 prepare: vi.fn(),
20}));
21
22const lifecycle = vi.hoisted(() => ({
23 cleanups: [] as Array<() => void>,
24}));
25
26vi.mock("react", async (importOriginal) => {
27 const actual = await importOriginal<typeof import("react")>();
28 const { reactHookHarness } = await import("../../test/reactHookHarness");
29 return {
30 ...actual,
31 useEffect: (effect: () => void | (() => void)) => {
32 const cleanup = effect();
33 if (cleanup) lifecycle.cleanups.push(cleanup);
34 },
35 useRef: reactHookHarness.useRef,
36 useLayoutEffect: (effect: () => void | (() => void)) => {
37 const cleanup = effect();
38 if (cleanup) lifecycle.cleanups.push(cleanup);
39 },
40 useState: reactHookHarness.useState,
41 };
42});
43
44vi.mock("react/compiler-runtime", async () => {
45 const { reactHookHarness } = await import("../../test/reactHookHarness");
46 return { c: reactHookHarness.useMemoCache };
47});
48
49vi.mock("../../state/server", () => ({
50 serverEnvironment: {
51 searchAcpRegistry: state.search,
52 prepareAcpRegistryAgent: atoms.prepare,
53 },
54}));
55
56vi.mock("../../state/query", () => ({
57 useEnvironmentQuery: () => ({
58 data: state.result,
59 error: state.error,
60 isPending: state.isPending,
61 refresh: state.refresh,
62 }),
63}));
64
65vi.mock("../../state/use-atom-command", () => ({
66 useAtomCommand: () => state.prepare,
67}));
68
69vi.mock("@t3tools/client-runtime/state/runtime", () => ({
70 isAtomCommandInterrupted: () => false,
71 squashAtomCommandFailure: () => new Error("Prepare failed."),
72}));
73
74import { AcpRegistrySearchStep } from "./AcpRegistrySearchStep";
75
76const environmentId = EnvironmentId.make("remote-device");
77const gemini: AcpRegistrySearchAgent = {
78 id: "gemini",
79 name: "Gemini CLI",
80 version: "1.2.3",
81 description: "Google's agent",
82 authors: ["Google <gemini-cli@google.com>", "Contributor"],
83 license: "Apache-2.0",
84 website: "https://example.com/docs",
85 repository: "https://example.com/source",
86 icon: "https://example.com/icon.png",
87 distribution: "npx",
88 integrity: "registry",
89};
90
91function render(options?: {
92 readonly configured?: boolean;
93 readonly onPrepared?: (agent: AcpRegistrySearchAgent) => void;
94}): ReactElement<Record<string, unknown>> {
95 hooks.beginRender();
96 return AcpRegistrySearchStep({
97 environmentId,
98 providerInstances: options?.configured
99 ? {
100 acpRegistry_gemini: {
101 driver: ProviderDriverKind.make("acpRegistry"),
102 config: { agentId: "gemini" },
103 },
104 }
105 : {},
106 onPrepared: options?.onPrepared ?? vi.fn(),
107 onManualConfiguration: vi.fn(),
108 }) as ReactElement<Record<string, unknown>>;
109}
110
111function findByAriaLabel(
112 tree: ReactElement<Record<string, unknown>>,
113 label: string,
114): ReactElement<Record<string, unknown>> {
115 const found = visitElements(tree, (element) => element.props["aria-label"] === label);
116 expect(found).not.toBeNull();
117 return found!;
118}
119
120describe("AcpRegistrySearchStep", () => {
121 beforeEach(() => {
122 vi.useFakeTimers();
123 hooks.reset();
124 state.result = null;
125 state.error = null;
126 state.isPending = false;
127 state.refresh.mockReset();
128 state.search.mockClear();
129 state.prepare.mockReset().mockResolvedValue({
130 _tag: "Success",
131 value: { agentId: "gemini", version: "1.2.3", distribution: "npx", prepared: true },
132 });
133 lifecycle.cleanups = [];
134 vi.stubGlobal(
135 "fetch",
136 vi.fn(() => new Promise<Response>(() => {})),
137 );
138 });
139 afterEach(() => {
140 for (const cleanup of lifecycle.cleanups) cleanup();
141 vi.useRealTimers();
142 });
143
144 it("loads the catalog immediately and searches only after typing settles", () => {
145 const initial = render();
146 expect(state.search).toHaveBeenLastCalledWith({
147 environmentId,
148 input: { query: "" },
149 });
150
151 const input = findByAriaLabel(initial, "Search ACP Registry");
152 expect(input.props.size).toBe("sm");
153 (input.props.onChange as ((event: { currentTarget: { value: string } }) => void) | undefined)?.(
154 { currentTarget: { value: " Gemini " } },
155 );
156 vi.advanceTimersByTime(200);
157 render();
158 expect(state.search).toHaveBeenLastCalledWith({ environmentId, input: { query: "" } });
159 (input.props.onChange as ((event: { currentTarget: { value: string } }) => void) | undefined)?.(
160 {
161 currentTarget: { value: " Gemini CLI " },
162 },
163 );
164 vi.advanceTimersByTime(299);
165 render();
166 expect(state.search).toHaveBeenLastCalledWith({ environmentId, input: { query: "" } });
167 vi.advanceTimersByTime(1);
168 render();
169 expect(state.search).toHaveBeenLastCalledWith({
170 environmentId,
171 input: { query: "Gemini CLI" },
172 });
173 (input.props.onChange as ((event: { currentTarget: { value: string } }) => void) | undefined)?.(
174 {
175 currentTarget: { value: "" },
176 },
177 );
178 vi.advanceTimersByTime(300);
179 render();
180 expect(state.search).toHaveBeenLastCalledWith({ environmentId, input: { query: "" } });
181 });
182
183 it("renders deterministic loading, error, and empty states", () => {
184 state.isPending = true;
185 expect(
186 visitElements(render(), (element) => element.props.children === "Searching the registry..."),
187 ).not.toBeNull();
188
189 state.isPending = false;
190 state.error = "Registry unavailable.";
191 expect(
192 visitElements(render(), (element) => element.props.children === "Registry unavailable."),
193 ).not.toBeNull();
194
195 state.error = null;
196 state.result = { agents: [] };
197 expect(
198 visitElements(render(), (element) => element.props.children === "No compatible agents found"),
199 ).not.toBeNull();
200 });
201
202 it("keeps same-query refreshes visible and announced while retaining results", () => {
203 const first = render();
204 const input = findByAriaLabel(first, "Search ACP Registry");
205 (input.props.onChange as ((event: { currentTarget: { value: string } }) => void) | undefined)?.(
206 {
207 currentTarget: { value: "Codex" },
208 },
209 );
210 const draft = render();
211 const searchForm = visitElements(draft, (element) => element.type === "form");
212 (searchForm?.props.onSubmit as ((event: { preventDefault: () => void }) => void) | undefined)?.(
213 {
214 preventDefault: vi.fn(),
215 },
216 );
217
218 state.result = { agents: [gemini] };
219 const resultTree = render();
220 expect(state.search).toHaveBeenCalledWith({
221 environmentId,
222 input: { query: "Codex" },
223 });
224 const form = visitElements(resultTree, (element) => element.type === "form");
225 (form?.props.onSubmit as ((event: { preventDefault: () => void }) => void) | undefined)?.({
226 preventDefault: vi.fn(),
227 });
228 expect(state.refresh).toHaveBeenCalledOnce();
229
230 state.isPending = true;
231 const refreshingTree = render();
232 expect(
233 visitElements(
234 refreshingTree,
235 (element) =>
236 element.props.role === "status" &&
237 element.props.children === "Refreshing ACP Registry results.",
238 ),
239 ).not.toBeNull();
240 expect(findByAriaLabel(refreshingTree, "Add Gemini CLI")).not.toBeNull();
241 });
242
243 it("prepares a result before handing it back to the wizard", async () => {
244 state.prepare.mockResolvedValueOnce({
245 _tag: "Success",
246 value: { agentId: "gemini", version: "2.0.0", distribution: "binary", prepared: true },
247 });
248 state.result = { agents: [gemini] };
249 const onPrepared = vi.fn();
250 const tree = render({ onPrepared });
251
252 const add = findByAriaLabel(tree, "Add Gemini CLI");
253 (add.props.onClick as (() => void) | undefined)?.();
254 await Promise.resolve();
255 await Promise.resolve();
256
257 expect(state.prepare).toHaveBeenCalledWith({
258 environmentId,
259 input: { agentId: "gemini" },
260 });
261 expect(onPrepared).toHaveBeenCalledWith({
262 ...gemini,
263 version: "2.0.0",
264 distribution: "binary",
265 });
266 });
267
268 it("ignores a stale prepare completion", async () => {
269 let resolveFirst!: (value: { readonly _tag: "Success"; readonly value: unknown }) => void;
270 let resolveSecond!: (value: { readonly _tag: "Success"; readonly value: unknown }) => void;
271 state.prepare
272 .mockImplementationOnce(
273 () =>
274 new Promise((resolve) => {
275 resolveFirst = resolve;
276 }),
277 )
278 .mockImplementationOnce(
279 () =>
280 new Promise((resolve) => {
281 resolveSecond = resolve;
282 }),
283 );
284 state.result = { agents: [gemini] };
285 const onPrepared = vi.fn();
286 const tree = render({ onPrepared });
287 const add = findByAriaLabel(tree, "Add Gemini CLI");
288
289 (add.props.onClick as (() => void) | undefined)?.();
290 (add.props.onClick as (() => void) | undefined)?.();
291 resolveFirst({ _tag: "Success", value: {} });
292 await Promise.resolve();
293 expect(onPrepared).not.toHaveBeenCalled();
294
295 resolveSecond({ _tag: "Success", value: {} });
296 await Promise.resolve();
297 expect(onPrepared).toHaveBeenCalledOnce();
298 });
299
300 it("ignores prepare completion after unmount", async () => {
301 let resolvePrepare!: (value: { readonly _tag: "Success"; readonly value: unknown }) => void;
302 state.prepare.mockImplementationOnce(
303 () =>
304 new Promise((resolve) => {
305 resolvePrepare = resolve;
306 }),
307 );
308 state.result = { agents: [gemini] };
309 const onPrepared = vi.fn();
310 const tree = render({ onPrepared });
311
312 const add = findByAriaLabel(tree, "Add Gemini CLI");
313 (add.props.onClick as (() => void) | undefined)?.();
314 for (const cleanup of lifecycle.cleanups) cleanup();
315 resolvePrepare({ _tag: "Success", value: {} });
316 await Promise.resolve();
317
318 expect(onPrepared).not.toHaveBeenCalled();
319 });
320
321 it("renders existing registry configuration as already added", () => {
322 state.result = { agents: [gemini] };
323 const tree = render({ configured: true });
324 const added = findByAriaLabel(tree, "Already added Gemini CLI");
325
326 expect(added.props.disabled).toBe(true);
327 });
328});