@devries-cameron20 / t3code Mirror · read-only / commits / c20eab44e1
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 23, 05:30 UTC

test(web): pr-and-diff tests run in a real browser (#20901)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 17, 2026 at 05:55 UTC c20eab44e1d9e97a96df21699434032e9da16cbd
5 files changed +781 -962
apps/web/src/components/diffs/StyledDiffCodeView.browser.test.tsx renamed
+133 -168
@@ -1,4 +1,3 @@
1 -import type * as NodeWorkerThreads from "node:worker_threads";
1 import {
2 FileRenderer,
3 getSharedHighlighter,
@@ -15,14 +14,15 @@ import {
14 useLayoutEffect,
15 useRef,
16 useState,
17 + type ReactElement,
18 type Ref,
19 } from "react";
20 -import { create, type ReactTestRenderer } from "react-test-renderer";
20 +import { createRoot, type Root } from "react-dom/client";
21 import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
22
23 const testState = vi.hoisted(() => ({
24 - workers: [] as NodeWorkerThreads.Worker[],
25 - terminations: [] as Promise<number>[],
24 + workers: [] as Worker[],
25 + terminations: 0,
26 requests: [] as WorkerRequest[],
27 pools: new Map<WorkerPoolManager, Promise<void>>(),
28 renderPools: [] as (WorkerPoolManager | undefined)[],
@@ -32,43 +32,32 @@ const testState = vi.hoisted(() => ({
32 onInitializationHeld: undefined as (() => void) | undefined,
33 }));
34
35 -vi.mock("../../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
36 -
37 -vi.mock("@pierre/diffs/worker/worker.js?worker", async () => {
38 - const { Worker } = await import("node:worker_threads");
39 - const moduleUrl = import.meta.resolve("@pierre/diffs/worker/worker.js");
35 +vi.mock(import("../../hooks/useTheme"), async (original) => ({
36 + ...(await original()),
37 + useTheme: (() => ({ resolvedTheme: "dark" })) as never,
38 +}));
39
40 +// Wraps Pierre's real worker so the suite can count workers, read requests and hold startup.
41 +// Vite's `?worker` export is a factory that returns a plain Worker, so this patches the instance.
42 +vi.mock("@pierre/diffs/worker/worker.js?worker", async (original) => {
43 + const actual = await original<{ default: new () => Worker }>();
44 return {
42 - default: class {
43 - worker: NodeWorkerThreads.Worker;
44 -
45 - constructor() {
46 - if (testState.failWorkers) throw new Error("Worker creation failed");
47 - this.worker = new Worker(
48 - `const { parentPort, workerData } = require("node:worker_threads");
49 - globalThis.self = {
50 - addEventListener(type, listener) {
51 - if (type === "message") parentPort.on("message", data => listener({ data }));
52 - if (type === "error") process.on("uncaughtException", listener);
53 - }
54 - };
55 - globalThis.postMessage = data => parentPort.postMessage(data);
56 - import(workerData.moduleUrl);`,
57 - { eval: true, workerData: { moduleUrl }, execArgv: [] },
58 - );
59 - testState.workers.push(this.worker);
60 - }
61 -
62 - addEventListener(
63 - type: "message" | "error",
64 - listener: (event: { data: WorkerResponse } | Error) => void,
65 - ) {
66 - if (type === "error") {
67 - this.worker.on("error", listener);
45 + ...actual,
46 + default: function TestDiffsWorker() {
47 + if (testState.failWorkers) throw new Error("Worker creation failed");
48 + const worker = new actual.default();
49 + testState.workers.push(worker);
50 + const addEventListener = worker.addEventListener.bind(worker);
51 + const postMessage = worker.postMessage.bind(worker);
52 + const terminate = worker.terminate.bind(worker);
53 + worker.addEventListener = (type: string, listener: EventListenerOrEventListenerObject) => {
54 + if (type !== "message" || typeof listener !== "function") {
55 + addEventListener(type, listener);
56 return;
57 }
70 - this.worker.on("message", (data: WorkerResponse) => {
71 - const deliver = () => listener({ data });
58 + addEventListener("message", (event) => {
59 + const data = (event as MessageEvent<WorkerResponse>).data;
60 + const deliver = () => listener(event);
61 if (
62 testState.holdInitialization &&
63 data.type === "success" &&
@@ -80,27 +69,28 @@ vi.mock("@pierre/diffs/worker/worker.js?worker", async () => {
69 deliver();
70 }
71 });
83 - }
84 -
85 - postMessage(message: WorkerRequest) {
72 + };
73 + worker.postMessage = (message: WorkerRequest) => {
74 testState.requests.push(message);
87 - this.worker.postMessage(message, []);
88 - }
89 -
90 - terminate() {
91 - testState.terminations.push(this.worker.terminate());
92 - }
75 + postMessage(message);
76 + };
77 + worker.terminate = () => {
78 + testState.terminations += 1;
79 + terminate();
80 + };
81 + return worker;
82 },
83 };
84 });
85
97 -vi.mock("@pierre/diffs/react", async (importOriginal) => ({
98 - ...(await importOriginal<typeof import("@pierre/diffs/react")>()),
99 - CodeView: (props: CodeViewProps<undefined, undefined>) => {
100 - return props.items?.map((item) =>
86 +// Pierre's real viewer virtualizes into a shadow root; this stand-in renders each file through
87 +// the same worker pool and keeps the highlighted HTML readable.
88 +vi.mock(import("@pierre/diffs/react"), async (original) => ({
89 + ...(await original()),
90 + CodeView: ((props: CodeViewProps<undefined, undefined>) =>
91 + props.items?.map((item) =>
92 item.type === "file" ? <FileOutput key={item.id} file={item.file} /> : null,
102 - );
103 - },
93 + )) as never,
94 }));
95
96 import { StyledDiffCodeView } from "./StyledDiffCodeView";
@@ -152,12 +142,33 @@ function renderViews(count: number) {
142 );
143 }
144
155 -describe("code-view worker lifecycle", () => {
156 - let renderer: ReactTestRenderer | undefined;
145 +const roots: Root[] = [];
146 +
147 +function mount(element: ReactElement) {
148 + const container = document.createElement("div");
149 + document.body.append(container);
150 + const root = createRoot(container);
151 + roots.push(root);
152 + return {
153 + root,
154 + render: (next: ReactElement) => act(async () => root.render(next)),
155 + initial: act(async () => root.render(element)),
156 + };
157 +}
158
159 +async function unmountAll() {
160 + for (const root of roots.splice(0)) await act(async () => root.unmount());
161 + document.body.replaceChildren();
162 +}
163 +
164 +const codeFile = (name: string) =>
165 + document.querySelector(`[data-code-file="${name}"]`)?.textContent ?? "";
166 +const loadingViews = () => document.querySelectorAll('[role="status"]').length;
167 +
168 +describe("code-view worker lifecycle", () => {
169 beforeEach(() => {
170 testState.workers = [];
160 - testState.terminations = [];
171 + testState.terminations = 0;
172 testState.requests = [];
173 testState.pools.clear();
174 testState.renderPools = [];
@@ -165,14 +176,10 @@ describe("code-view worker lifecycle", () => {
176 testState.holdInitialization = false;
177 testState.heldResponses = [];
178 testState.onInitializationHeld = undefined;
168 - vi.stubGlobal("window", {});
169 - vi.stubGlobal("navigator", { hardwareConcurrency: 2 });
179 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
180 + // Pins the pool at two workers whatever machine runs the suite.
181 + Object.defineProperty(navigator, "hardwareConcurrency", { configurable: true, value: 2 });
182 vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
172 - vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) =>
173 - setImmediate(() => callback(0)),
174 - );
175 - vi.stubGlobal("cancelAnimationFrame", clearImmediate);
183 const initialize = WorkerPoolManager.prototype.initialize;
184 vi.spyOn(WorkerPoolManager.prototype, "initialize").mockImplementation(function (
185 this: WorkerPoolManager,
@@ -185,85 +192,71 @@ describe("code-view worker lifecycle", () => {
192 });
193
194 afterEach(async () => {
188 - await act(async () => renderer?.unmount());
189 - renderer = undefined;
195 + await unmountAll();
196 await vi.runOnlyPendingTimersAsync();
191 - await Promise.all(testState.terminations);
197 vi.useRealTimers();
198 vi.restoreAllMocks();
199 vi.unstubAllGlobals();
200 + delete (navigator as { hardwareConcurrency?: number }).hardwareConcurrency;
201 });
202
203 it("starts on demand, keeps quick reopens warm, and expires the last closed pool", async () => {
198 - await act(async () => {
199 - renderer = create(renderViews(0));
200 - });
201 - const mounted = renderer!;
202 - const button = mounted.root.findByType("button");
204 + const view = mount(renderViews(0));
205 + await view.initial;
206 + const button = document.querySelector("button")!;
207 expect(testState.workers).toHaveLength(0);
208 expect(testState.pools.size).toBe(0);
205 - await act(async () => {
206 - (button.props as { onClick(): void }).onClick();
207 - mounted.update(renderViews(1));
208 - });
209 + await act(async () => button.click());
210 + await view.render(renderViews(1));
211 const pool = [...testState.pools.keys()][0]!;
212 await act(async () => testState.pools.get(pool));
213 expect(pool.isInitialized()).toBe(true);
214 expect(testState.workers).toHaveLength(2);
213 - expect(mounted.root.findByProps({ "data-code-file": "notes.txt" }).children.join("")).toContain(
214 - "Plain text is ready.",
215 - );
215 + await vi.waitFor(() => expect(codeFile("notes.txt")).toContain("Plain text is ready."));
216 expect(testState.requests.filter((request) => request.type === "file")).toHaveLength(0);
217
218 - await act(async () => mounted.update(renderViews(2)));
218 + await view.render(renderViews(2));
219 await act(async () => pool.primeFileHighlightCache(files[1]!));
220 expect(testState.pools.size).toBe(1);
221 expect(testState.workers).toHaveLength(2);
222 expect(new Set(testState.renderPools)).toEqual(new Set([pool]));
223 expect(pool.getFileResultCache(files[1]!)).toBeDefined();
224 - expect(mounted.root.findByProps({ "data-code-file": "answer.ts" }).children.join("")).toContain(
225 - "answer",
226 - );
224 + await vi.waitFor(() => expect(codeFile("answer.ts")).toContain("answer"));
225
228 - await act(async () => mounted.update(renderViews(1)));
226 + await view.render(renderViews(1));
227 expect(pool.getStats().totalWorkers).toBe(2);
230 - expect(testState.terminations).toHaveLength(0);
231 - await act(async () => mounted.update(renderViews(0)));
228 + expect(testState.terminations).toBe(0);
229 + await view.render(renderViews(0));
230 await vi.advanceTimersByTimeAsync(29_999);
231 expect(pool.getStats().totalWorkers).toBe(2);
234 - expect(testState.terminations).toHaveLength(0);
232 + expect(testState.terminations).toBe(0);
233
236 - await act(async () => mounted.update(renderViews(1)));
234 + await view.render(renderViews(1));
235 expect(testState.pools.size).toBe(1);
236 expect(testState.workers).toHaveLength(2);
239 - expect(mounted.root.findAllByProps({ role: "status" })).toHaveLength(0);
237 + expect(loadingViews()).toBe(0);
238 expect(pool.getFileResultCache(files[1]!)).toBeDefined();
239 await vi.advanceTimersByTimeAsync(30_000);
240 expect(pool.getStats().totalWorkers).toBe(2);
241
244 - await act(async () => mounted.update(renderViews(0)));
242 + await view.render(renderViews(0));
243 await vi.advanceTimersByTimeAsync(30_000);
246 - await Promise.all(testState.terminations);
244 expect(pool.getStats().totalWorkers).toBe(0);
248 - expect(testState.terminations).toHaveLength(2);
245 + expect(testState.terminations).toBe(2);
246
250 - await act(async () => mounted.update(renderViews(1)));
247 + await view.render(renderViews(1));
248 const reopenedPool = [...testState.pools.keys()][1]!;
249 await act(async () => testState.pools.get(reopenedPool));
250 expect(reopenedPool.isInitialized()).toBe(true);
251 expect(testState.workers).toHaveLength(4);
255 - expect(mounted.root.findByType("button")).toBe(button);
256 - expect(button.children).toEqual(["Edited draft"]);
257 - expect(mounted.root.findByProps({ "data-code-file": "notes.txt" }).children.join("")).toContain(
258 - "Plain text is ready.",
259 - );
252 + expect(document.querySelector("button")).toBe(button);
253 + expect(button.textContent).toBe("Edited draft");
254 + await vi.waitFor(() => expect(codeFile("notes.txt")).toContain("Plain text is ready."));
255 });
256
257 it("renders through Pierre's main-thread fallback when worker creation fails", async () => {
258 testState.failWorkers = true;
264 - await act(async () => {
265 - renderer = create(renderViews(1));
266 - });
259 + await mount(renderViews(1)).initial;
260 const pool = [...testState.pools.keys()][0]!;
261 await act(async () => {
262 await expect(testState.pools.get(pool)).rejects.toMatchObject({ _tag: "DiffWorkerError" });
@@ -275,9 +268,7 @@ describe("code-view worker lifecycle", () => {
268 });
269 expect(pool.isWorkingPool()).toBe(false);
270 expect(testState.workers).toHaveLength(0);
278 - expect(
279 - renderer!.root.findByProps({ "data-code-file": "notes.txt" }).children.join(""),
280 - ).toContain("Plain text is ready.");
271 + await vi.waitFor(() => expect(codeFile("notes.txt")).toContain("Plain text is ready."));
272 });
273
274 it("keeps an initializing pool until its last view closes and ignores late responses", async () => {
@@ -285,34 +276,32 @@ describe("code-view worker lifecycle", () => {
276 const held = new Promise<void>((resolve) => {
277 testState.onInitializationHeld = resolve;
278 });
288 - await act(async () => {
289 - renderer = create(renderViews(2));
290 - });
279 + const view = mount(renderViews(2));
280 + await view.initial;
281 const pool = [...testState.pools.keys()][0]!;
282 const pending = testState.pools.get(pool)!;
283 await held;
284 expect(pool.isInitialized()).toBe(false);
285 expect(testState.pools.size).toBe(1);
296 - expect(renderer!.root.findAllByProps({ role: "status" })).toHaveLength(2);
286 + expect(loadingViews()).toBe(2);
287 expect(testState.renderPools).toHaveLength(0);
288
299 - await act(async () => renderer!.update(renderViews(1)));
289 + await view.render(renderViews(1));
290 expect(pool.getStats().totalWorkers).toBe(2);
301 - expect(testState.terminations).toHaveLength(0);
302 - await act(async () => renderer!.update(renderViews(0)));
291 + expect(testState.terminations).toBe(0);
292 + await view.render(renderViews(0));
293 // Pierre gives up on a held startup after 10 seconds; the idle timer then tears the pool down.
294 const timedOut = expect(pending).rejects.toThrow("worker initialization timed out");
295 await vi.advanceTimersByTimeAsync(30_000);
296 await timedOut;
307 - await Promise.all(testState.terminations);
297 await act(async () => {
298 for (const deliver of testState.heldResponses) deliver();
299 });
300 expect(pool.getStats().totalWorkers).toBe(0);
301 expect(testState.workers).toHaveLength(2);
313 - expect(testState.terminations).toHaveLength(2);
302 + expect(testState.terminations).toBe(2);
303 expect(testState.renderPools).toHaveLength(0);
315 - expect(renderer!.root.findAllByType("pre")).toHaveLength(0);
304 + expect(document.querySelectorAll("pre")).toHaveLength(0);
305 });
306 });
307
@@ -418,7 +407,8 @@ function RevealViews({
407 }
408
409 describe("code-view file reveals", () => {
421 - let renderer: ReactTestRenderer | undefined;
410 + let view: ReturnType<typeof mount>;
411 + const reveal = () => act(async () => document.querySelector("button")!.click());
412
413 beforeEach(() => {
414 revealCalls.length = 0;
@@ -426,64 +416,48 @@ describe("code-view file reveals", () => {
416 });
417
418 afterEach(async () => {
429 - await act(async () => renderer?.unmount());
430 - renderer = undefined;
419 + await unmountAll();
420 vi.unstubAllGlobals();
421 });
422
423 it("does not replay a handled tree click or scroll an old handle when a selected file remounts the view", async () => {
435 - await act(async () => {
436 - renderer = create(<RevealViews scope="first" visible selectedFile="external-a" />);
437 - });
438 - await act(async () => {
439 - (renderer!.root.findByType("button").props as { onClick(): void }).onClick();
440 - });
424 + view = mount(<RevealViews scope="first" visible selectedFile="external-a" />);
425 + await view.initial;
426 + await reveal();
427 expect(revealCalls.at(-1)?.fileKey).toBe("tree-file");
428 revealCalls.length = 0;
429
444 - await act(async () => {
445 - renderer!.update(
446 - <RevealViews scope="second" visible selectedFile="external-b" requestId={1} />,
447 - );
448 - });
430 + await view.render(
431 + <RevealViews scope="second" visible selectedFile="external-b" requestId={1} />,
432 + );
433 expect(revealCalls).toEqual([
434 { scope: "second", fileKey: "external-b", mounted: true, collapsed: false },
435 ]);
436 });
437
438 it("waits for a live viewer and applies each pending tree click only once", async () => {
455 - await act(async () => {
456 - renderer = create(<RevealViews scope="diff" visible={false} selectedFile="external" />);
457 - });
458 - await act(async () => {
459 - (renderer!.root.findByType("button").props as { onClick(): void }).onClick();
460 - });
439 + view = mount(<RevealViews scope="diff" visible={false} selectedFile="external" />);
440 + await view.initial;
441 + await reveal();
442 expect(revealCalls).toEqual([]);
443
463 - await act(async () => {
464 - renderer!.update(<RevealViews scope="diff" visible selectedFile="external" />);
465 - });
444 + await view.render(<RevealViews scope="diff" visible selectedFile="external" />);
445 expect(revealCalls.map((call) => call.fileKey)).toEqual(["external", "tree-file"]);
446 revealCalls.length = 0;
468 - await act(async () => {
469 - renderer!.update(<RevealViews scope="diff" visible={false} selectedFile="external" />);
470 - });
471 - await act(async () => {
472 - renderer!.update(<RevealViews scope="diff" visible selectedFile="external" />);
473 - });
447 + await view.render(<RevealViews scope="diff" visible={false} selectedFile="external" />);
448 + await view.render(<RevealViews scope="diff" visible selectedFile="external" />);
449 expect(revealCalls).toEqual([
450 { scope: "diff", fileKey: "external", mounted: true, collapsed: false },
451 ]);
452
453 revealCalls.length = 0;
454 + // A click that lands in the same update that hides the viewer waits for it to return.
455 await act(async () => {
480 - (renderer!.root.findByType("button").props as { onClick(): void }).onClick();
481 - renderer!.update(<RevealViews scope="diff" visible={false} selectedFile="external" />);
456 + document.querySelector("button")!.click();
457 + view.root.render(<RevealViews scope="diff" visible={false} selectedFile="external" />);
458 });
459 expect(revealCalls).toEqual([]);
484 - await act(async () => {
485 - renderer!.update(<RevealViews scope="diff" visible selectedFile="external" />);
486 - });
460 + await view.render(<RevealViews scope="diff" visible selectedFile="external" />);
461 expect(revealCalls).toEqual([
462 { scope: "diff", fileKey: "external", mounted: true, collapsed: false },
463 { scope: "diff", fileKey: "tree-file", mounted: true, collapsed: false },
@@ -491,36 +465,27 @@ describe("code-view file reveals", () => {
465 });
466
467 it("cancels pending tree clicks when an external selection or diff scope changes", async () => {
494 - await act(async () => {
495 - renderer = create(<RevealViews scope="first" visible={false} selectedFile="external-a" />);
496 - });
497 - await act(async () => {
498 - (renderer!.root.findByType("button").props as { onClick(): void }).onClick();
499 - });
500 - await act(async () => {
501 - renderer!.update(
502 - <RevealViews scope="first" visible selectedFile="external-b" requestId={1} />,
503 - );
504 - });
468 + view = mount(<RevealViews scope="first" visible={false} selectedFile="external-a" />);
469 + await view.initial;
470 + await reveal();
471 + await view.render(
472 + <RevealViews scope="first" visible selectedFile="external-b" requestId={1} />,
473 + );
474 expect(revealCalls.map((call) => call.fileKey)).toEqual(["external-b"]);
475 revealCalls.length = 0;
476
508 - await act(async () => renderer!.update(<RevealViews scope="first" visible={false} />));
509 - await act(async () => {
510 - (renderer!.root.findByType("button").props as { onClick(): void }).onClick();
511 - });
512 - await act(async () => renderer!.update(<RevealViews scope="second" visible={false} />));
513 - await act(async () => renderer!.update(<RevealViews scope="first" visible />));
477 + await view.render(<RevealViews scope="first" visible={false} />);
478 + await reveal();
479 + await view.render(<RevealViews scope="second" visible={false} />);
480 + await view.render(<RevealViews scope="first" visible />);
481 expect(revealCalls).toEqual([]);
482 });
483
484 it("reveals after a collapsed file expands and honors another click on the same file", async () => {
518 - await act(async () => {
519 - renderer = create(<RevealViews scope="diff" visible />);
520 - });
521 - const reveal = renderer!.root.findByType("button").props as { onClick(): void };
522 - await act(async () => reveal.onClick());
523 - await act(async () => reveal.onClick());
485 + view = mount(<RevealViews scope="diff" visible />);
486 + await view.initial;
487 + await reveal();
488 + await reveal();
489 expect(revealCalls).toEqual([
490 { scope: "diff", fileKey: "tree-file", mounted: true, collapsed: false },
491 { scope: "diff", fileKey: "tree-file", mounted: true, collapsed: false },
apps/web/src/components/pullRequest/PullRequestDetailPanel.browser.test.tsx new
+388
@@ -0,0 +1,388 @@
1 +import {
2 + EnvironmentId,
3 + ProjectId,
4 + SourceControlProviderKind,
5 + ThreadId,
6 + type PullRequestDetailView,
7 + type ScopedThreadRef,
8 + type ThreadPullRequestLink,
9 +} from "@t3tools/contracts";
10 +import { act, type ComponentProps } from "react";
11 +import { createRoot, type Root } from "react-dom/client";
12 +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
13 +import { page } from "vite-plus/test/browser";
14 +import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
15 +
16 +import "~/index.css";
17 +
18 +const { newThread, prepareThread, refresh } = vi.hoisted(() => ({
19 + newThread: vi.fn(),
20 + prepareThread: vi.fn(),
21 + refresh: vi.fn(),
22 +}));
23 +
24 +vi.mock(import("~/state/session"), async (original) => ({
25 + ...(await original()),
26 + useEnvironmentScope: () => true,
27 + readEnvironmentScope: () => true,
28 +}));
29 +vi.mock(import("~/hooks/useSettings"), async (original) => ({
30 + ...(await original()),
31 + useEnvironmentSettings: (() => undefined) as never,
32 +}));
33 +vi.mock(import("~/hooks/useHandleNewThread"), async (original) => ({
34 + ...(await original()),
35 + useNewThreadHandler: (() => newThread) as never,
36 +}));
37 +vi.mock(import("~/lib/sourceControlActions"), async (original) => ({
38 + ...(await original()),
39 + usePreparePullRequestThreadAction: (() => ({
40 + run: prepareThread,
41 + isAllowed: true,
42 + error: null,
43 + })) as never,
44 +}));
45 +vi.mock(import("~/state/use-atom-command"), async (original) => ({
46 + ...(await original()),
47 + useAtomCommand: (() => vi.fn()) as never,
48 +}));
49 +vi.mock(import("~/state/pullRequests"), async (original) => {
50 + const actual = await original();
51 + const { Atom } = await import("effect/reactivity");
52 + const cannotWriteGuides = Atom.make(false);
53 + return {
54 + ...actual,
55 + pullRequestEnvironment: {
56 + ...actual.pullRequestEnvironment,
57 + detail: (() => "detail") as never,
58 + activity: (() => "activity") as never,
59 + reviewGuide: (() => "review-guide") as never,
60 + generateReviewGuide: {
61 + ...actual.pullRequestEnvironment.generateReviewGuide,
62 + permissionAtom: () => cannotWriteGuides,
63 + },
64 + },
65 + };
66 +});
67 +vi.mock(import("~/state/query"), async (original) => ({
68 + ...(await original()),
69 + useEnvironmentQuery: ((query: unknown) => ({
70 + data: query === "detail" ? detail : null,
71 + dataUpdatedAt: 0,
72 + failure: null,
73 + isPending: false,
74 + isSuccess: true,
75 + error: null,
76 + refresh,
77 + })) as never,
78 +}));
79 +vi.mock(import("~/state/usePullRequestStack"), async (original) => ({
80 + ...(await original()),
81 + usePullRequestStack: (() => ({
82 + data: null,
83 + isSuccess: true,
84 + isPending: false,
85 + error: null,
86 + refresh,
87 + })) as never,
88 +}));
89 +// The real tabs load diffs, markdown and checks from the environment; these stand-ins
90 +// expose the actions they hand back to the panel and a tall scroller.
91 +vi.mock(import("./PullRequestSummaryTab"), async (original) => ({
92 + ...(await original()),
93 + PullRequestSummaryTab: (({
94 + onFixFinding,
95 + scrollerRef,
96 + }: ComponentProps<typeof import("./PullRequestSummaryTab").PullRequestSummaryTab>) => (
97 + <div ref={scrollerRef} data-testid="summary-scroller" className="h-full overflow-y-auto">
98 + <button
99 + type="button"
100 + onClick={() =>
101 + onFixFinding?.({
102 + kind: "check",
103 + check: { name: "Unit tests", status: "failure", description: "Test failed", url: null },
104 + })
105 + }
106 + >
107 + Fix check
108 + </button>
109 + <div data-testid="nested-scroller" className="h-40 overflow-y-auto">
110 + <div className="h-[2000px]" />
111 + </div>
112 + <div className="h-[3000px]" />
113 + </div>
114 + )) as never,
115 +}));
116 +vi.mock(import("./PullRequestCodeTab"), async (original) => ({
117 + ...(await original()),
118 + default: (({
119 + onAddToAgentSelection,
120 + scrollerRef,
121 + }: ComponentProps<typeof import("./PullRequestCodeTab").default>) => (
122 + <div ref={scrollerRef} data-testid="code-scroller" className="h-full overflow-y-auto">
123 + <button
124 + type="button"
125 + onClick={() =>
126 + onAddToAgentSelection?.({
127 + request: "Fix this line",
128 + comment: {
129 + id: "note-1",
130 + sectionId: "file:a.ts",
131 + sectionTitle: "a.ts",
132 + filePath: "a.ts",
133 + startIndex: 0,
134 + endIndex: 0,
135 + rangeLabel: "L1",
136 + text: "Please fix",
137 + diff: "+broken()",
138 + },
139 + })
140 + }
141 + >
142 + Add to agent
143 + </button>
144 + <div className="h-[3000px]" />
145 + </div>
146 + )) as never,
147 +}));
148 +
149 +import { PullRequestDetailPanel } from "./PullRequestDetailPanel";
150 +import { pullRequestPanelContext } from "./pullRequestDetail.logic";
151 +
152 +const detail: PullRequestDetailView = {
153 + provider: SourceControlProviderKind.make("github"),
154 + projectId: ProjectId.make("project"),
155 + projectTitle: "Project",
156 + workspaceRoot: "/workspace",
157 + repository: "owner/repo",
158 + number: 1,
159 + title: "Test pull request",
160 + body: "Original description",
161 + url: "https://github.com/owner/repo/pull/1",
162 + author: { login: "author", name: null, avatarUrl: null },
163 + viewer: "author",
164 + state: "open",
165 + isDraft: false,
166 + mergeability: "conflicting",
167 + additions: 1,
168 + deletions: 0,
169 + changedFiles: 1,
170 + headBranch: "feature",
171 + baseBranch: "main",
172 + createdAt: "2026-09-01T00:00:00Z",
173 + updatedAt: "2026-09-01T00:00:00Z",
174 + mergedAt: null,
175 + closedAt: null,
176 + reviewers: [],
177 + labels: [],
178 + checks: [{ name: "Unit tests", status: "success", description: null, url: null }],
179 + comments: [],
180 + commentCount: 0,
181 + commentsTruncated: false,
182 + reviewThreads: [],
183 + commits: [],
184 + mergeCapabilities: { merge: false, squash: false, rebase: false },
185 + capabilities: {
186 + diff: true,
187 + comment: false,
188 + search: true,
189 + actions: [],
190 + mergeMethods: [],
191 + review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
192 + reviewers: { request: false, listCandidates: false },
193 + edit: { changeRequest: true, comment: false },
194 + },
195 + viewerPermissions: {
196 + actions: [],
197 + comment: false,
198 + resolve: false,
199 + verdicts: [],
200 + requestReviewers: false,
201 + },
202 +};
203 +
204 +const threadRef: ScopedThreadRef = {
205 + environmentId: EnvironmentId.make("env-1"),
206 + threadId: ThreadId.make("thread-1"),
207 +};
208 +const draftId = DraftId.make("draft-1");
209 +const newDraftId = DraftId.make("new-draft");
210 +const shortcutContext = () => ({
211 + terminalFocus: false,
212 + terminalOpen: false,
213 + previewFocus: false,
214 + previewOpen: false,
215 + isWeb: true,
216 + isDesktop: false,
217 +});
218 +
219 +const roots: Root[] = [];
220 +
221 +function render(props: Partial<ComponentProps<typeof PullRequestDetailPanel>> = {}) {
222 + const container = document.createElement("div");
223 + container.className = "flex h-[700px] w-[900px]";
224 + document.body.append(container);
225 + const root = createRoot(container);
226 + roots.push(root);
227 + return act(async () =>
228 + root.render(
229 + <PullRequestDetailPanel
230 + environmentId={threadRef.environmentId}
231 + reference={detail}
232 + context="page"
233 + shortcutsEnabled={false}
234 + getShortcutContext={shortcutContext}
235 + {...props}
236 + />,
237 + ),
238 + );
239 +}
240 +
241 +beforeEach(() => {
242 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
243 + useComposerDraftStore.setState({ draftsByThreadKey: {} });
244 + newThread
245 + .mockReset()
246 + .mockResolvedValue({ draftId: newDraftId, threadId: ThreadId.make("new-thread") });
247 + prepareThread.mockReset().mockResolvedValue({
248 + _tag: "Success",
249 + value: { branch: "feature", worktreePath: "/workspace/pr" },
250 + });
251 +});
252 +afterEach(async () => {
253 + for (const root of roots.splice(0)) await act(async () => root.unmount());
254 + document.body.replaceChildren();
255 + vi.unstubAllGlobals();
256 +});
257 +
258 +const surface = { projectId: detail.projectId, repository: detail.repository, number: 1 };
259 +const link = (number: number, source: ThreadPullRequestLink["source"]): ThreadPullRequestLink => ({
260 + host: "github.com",
261 + repository: detail.repository,
262 + number,
263 + url: `https://github.com/${detail.repository}/pull/${number}`,
264 + source,
265 + linkedAt: "2026-09-01T00:00:00Z",
266 + snapshot: null,
267 + stack: null,
268 +});
269 +const stackThread = {
270 + projectId: detail.projectId,
271 + pullRequests: [link(3, "manual"), link(2, "stack"), link(1, "stack")],
272 + linkedPullRequest: { ...surface, number: 3, url: link(3, "manual").url },
273 +};
274 +const unrelatedThread = {
275 + projectId: detail.projectId,
276 + pullRequests: [link(9, "created")],
277 + linkedPullRequest: { ...surface, number: 9, url: link(9, "created").url },
278 +};
279 +
280 +const tab = (name: string) => page.getByRole("button", { name, exact: true });
281 +
282 +async function runAction(action: string) {
283 + if (action === "Add to agent") {
284 + await tab("Code").click();
285 + }
286 + if (["Ask a question", "Explain this PR"].includes(action) || action.startsWith("Fix findings")) {
287 + await page.getByRole("button", { name: "More pull request actions" }).click();
288 + // Menu items carry a description under their label.
289 + await page.getByRole("menuitem", { name: new RegExp(`^${action}`) }).click();
290 + return;
291 + }
292 + await page.getByRole("button", { name: action, exact: true }).click();
293 +}
294 +
295 +describe.each([
296 + ["own PR, a lower layer of the thread's stack", stackThread, threadRef],
297 + ["another PR beside the current thread", unrelatedThread, threadRef],
298 + ["PR beside an unsent draft", null, draftId],
299 + ["standalone PR page", null, undefined],
300 +] as const)("%s", (_name, thread, target) => {
301 + const context = thread ? pullRequestPanelContext(thread, surface) : "page";
302 + const renderPanel = () =>
303 + render({ context, ...(target ? { composerDraftTarget: target, threadRef } : {}) });
304 +
305 + it(`${thread === stackThread ? "hides" : "offers"} the checkout`, async () => {
306 + await renderPanel();
307 + await expect.element(page.getByText("Test pull request").first()).toBeVisible();
308 + expect(page.getByRole("button", { name: "Check out" }).elements()).toHaveLength(
309 + thread === stackThread ? 0 : 1,
310 + );
311 + });
312 +
313 + it.each([
314 + "Resolve conflicts",
315 + "Ask a question",
316 + "Explain this PR",
317 + "Fix findings in this thread",
318 + "Fix check",
319 + "Add to agent",
320 + ])("%s writes to the correct composer", async (action) => {
321 + if (target) useComposerDraftStore.getState().setPrompt(target, "Keep my draft");
322 + await renderPanel();
323 + await runAction(target ? action : action.replace("in this thread", "in a thread"));
324 + const draft = () => useComposerDraftStore.getState().getComposerDraft(target ?? newDraftId);
325 + await vi.waitFor(() => {
326 + if (action === "Resolve conflicts")
327 + expect(draft()?.prompt).toContain("resolve every conflict");
328 + else if (action === "Fix check") expect(draft()?.prompt).toContain("Fix the failing check");
329 + else if (action.startsWith("Fix findings"))
330 + expect(draft()?.prompt).toContain("Fix the actionable findings");
331 + else expect(draft()?.reviewComments?.length).toBeGreaterThan(0);
332 + });
333 + if (action === "Add to agent") {
334 + expect(draft()?.prompt).toContain("Fix this line");
335 + expect(draft()?.reviewComments).toEqual(
336 + expect.arrayContaining([expect.objectContaining({ id: "note-1", diff: "+broken()" })]),
337 + );
338 + }
339 + if (target) {
340 + expect(draft()?.prompt).toContain("Keep my draft");
341 + expect(newThread).not.toHaveBeenCalled();
342 + expect(prepareThread).not.toHaveBeenCalled();
343 + } else {
344 + expect(newThread).toHaveBeenCalled();
345 + }
346 + });
347 +});
348 +
349 +it("folds the title only for the active tab's own scroller", async () => {
350 + await render();
351 + const title = page.getByRole("heading", { level: 1, name: "Test pull request" });
352 + await expect.element(title).toBeVisible();
353 + const titleFold = () => title.element().closest("[inert]") !== null;
354 + const scrollTo = async (testId: string, top: number) => {
355 + const scroller = page.getByTestId(testId).element() as HTMLElement;
356 + await act(async () => {
357 + scroller.scrollTop = top;
358 + scroller.dispatchEvent(new Event("scroll"));
359 + });
360 + return scroller;
361 + };
362 +
363 + await scrollTo("nested-scroller", 600);
364 + expect(titleFold()).toBe(false);
365 +
366 + const summary = await scrollTo("summary-scroller", 600);
367 + await vi.waitFor(() => expect(titleFold()).toBe(true));
368 + // Folding the header keeps the content under the reader's eye.
369 + expect(summary.scrollTop).toBeLessThan(600);
370 +
371 + await scrollTo("summary-scroller", 0);
372 + await vi.waitFor(() => expect(titleFold()).toBe(false));
373 + await scrollTo("summary-scroller", 600);
374 + await vi.waitFor(() => expect(titleFold()).toBe(true));
375 +
376 + await tab("Code").click();
377 + await expect.element(page.getByTestId("code-scroller")).toBeInTheDocument();
378 + await vi.waitFor(() => expect(titleFold()).toBe(false));
379 + await scrollTo("code-scroller", 600);
380 + await vi.waitFor(() => expect(titleFold()).toBe(true));
381 +
382 + await tab("Summary").click();
383 + await vi.waitFor(() => expect(titleFold()).toBe(true));
384 + await scrollTo("summary-scroller", 0);
385 + await vi.waitFor(() => expect(titleFold()).toBe(false));
386 + await tab("Code").click();
387 + await vi.waitFor(() => expect(titleFold()).toBe(true));
388 +});
apps/web/src/components/pullRequest/PullRequestDetailPanel.test.tsx deleted
-435
@@ -1,435 +0,0 @@
1 -import { SourceControlProviderKind } from "@t3tools/contracts";
2 -import {
3 - EnvironmentId,
4 - ProjectId,
5 - ThreadId,
6 - type ScopedThreadRef,
7 - type PullRequestDetailView,
8 - type ThreadPullRequestLink,
9 -} from "@t3tools/contracts";
10 -import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
11 -import { act, type ReactNode, type ReactElement, type ComponentProps } from "react";
12 -import { create, type ReactTestRenderer } from "react-test-renderer";
13 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
14 -import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
15 -
16 -const { newThread, prepareThread, refresh, Wrapper, Trigger } = vi.hoisted(() => ({
17 - newThread: vi.fn(),
18 - prepareThread: vi.fn(),
19 - refresh: vi.fn(),
20 - Wrapper: ({ children }: { children?: ReactNode }) => children,
21 - Trigger: ({ children, render }: { children?: ReactNode; render?: ReactElement }) => (
22 - <>
23 - {render}
24 - {children}
25 - </>
26 - ),
27 -}));
28 -vi.mock("~/state/session", async (original) => ({
29 - ...(await original<typeof import("~/state/session")>()),
30 - useEnvironmentScope: () => true,
31 - readEnvironmentScope: () => true,
32 -}));
33 -vi.mock("@effect/atom-react", () => ({ useAtomValue: () => [] }));
34 -vi.mock("~/state/server", () => ({ primaryServerKeybindingsAtom: {} }));
35 -vi.mock("~/state/entities", () => ({ useProjects: () => [], useServerConfigs: () => new Map() }));
36 -vi.mock("~/state/environments", () => ({
37 - useEnvironments: () => ({ environments: [] }),
38 - usePrimaryEnvironmentId: () => EnvironmentId.make("env-1"),
39 -}));
40 -vi.mock("~/hooks/useSettings", () => ({
41 - useEnvironmentSettings: () => undefined,
42 - useClientSettings: (select: (settings: typeof DEFAULT_CLIENT_SETTINGS) => unknown) =>
43 - select(DEFAULT_CLIENT_SETTINGS),
44 -}));
45 -vi.mock("~/hooks/useLiveRefresh", () => ({ useLiveRefresh: () => {} }));
46 -vi.mock("~/hooks/useHandleNewThread", () => ({ useNewThreadHandler: () => newThread }));
47 -vi.mock("~/lib/sourceControlActions", () => ({
48 - usePreparePullRequestThreadAction: () => ({ run: prepareThread, isAllowed: true, error: null }),
49 -}));
50 -vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
51 -vi.mock("~/state/pullRequests", async (importOriginal) => ({
52 - ...(await importOriginal<typeof import("~/state/pullRequests")>()),
53 - pullRequestEnvironment: {
54 - detail: () => "detail",
55 - activity: () => "activity",
56 -
57 - reviewGuide: () => "review-guide",
58 - generateReviewGuide: { permissionAtom: () => "generate-review-guide" },
59 - },
60 - usePullRequestTurnRefresh: () => 0,
61 - useSharedPullRequestSummary: () => null,
62 -}));
63 -vi.mock("~/state/vcs", () => ({ vcsEnvironment: { listRefs: () => null } }));
64 -vi.mock("~/state/query", () => ({
65 - useEnvironmentQuery: (query: string) => ({
66 - data: query === "detail" ? detail : null,
67 - isPending: false,
68 - isSuccess: true,
69 - error: null,
70 - refresh,
71 - }),
72 -}));
73 -vi.mock("~/state/usePullRequestStack", () => ({
74 - usePullRequestStack: () => ({
75 - data: null,
76 - isSuccess: true,
77 - isPending: false,
78 - error: null,
79 - refresh,
80 - }),
81 -}));
82 -vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn(), update: vi.fn() } }));
83 -vi.mock("../ui/tooltip", () => ({
84 - TooltipProvider: Wrapper,
85 - Tooltip: Wrapper,
86 - TooltipTrigger: Trigger,
87 - TooltipPopup: () => null,
88 -}));
89 -vi.mock("../ui/menu", () => ({
90 - Menu: Wrapper,
91 - MenuPopup: Wrapper,
92 - MenuTrigger: Trigger,
93 - MenuItem: "button",
94 - MenuRadioGroup: Wrapper,
95 - MenuRadioItem: "button",
96 - MenuSeparator: () => null,
97 - MenuShortcut: () => null,
98 -}));
99 -vi.mock("../ui/alert-dialog", () => ({
100 - AlertDialog: () => null,
101 - AlertDialogPopup: Wrapper,
102 - AlertDialogHeader: Wrapper,
103 - AlertDialogTitle: Wrapper,
104 - AlertDialogDescription: Wrapper,
105 - AlertDialogFooter: Wrapper,
106 - AlertDialogClose: Wrapper,
107 -}));
108 -vi.mock("./PullRequestMarkdown", () => ({
109 - PullRequestMarkdownContext: Wrapper,
110 - PullRequestMarkdown: () => null,
111 -}));
112 -vi.mock("~/browser/useOpenLink", () => ({ useOpenLink: () => vi.fn() }));
113 -vi.mock("./PullRequestThreadLinks", () => ({ PullRequestThreadLinks: () => null }));
114 -vi.mock("./PullRequestSummaryTab", () => ({
115 - PullRequestSummaryTab: ({
116 - onFixFinding,
117 - scrollerRef,
118 - }: ComponentProps<typeof import("./PullRequestSummaryTab").PullRequestSummaryTab>) => (
119 - <div ref={scrollerRef} data-test-scroll="summary">
120 - <button
121 - onClick={() =>
122 - onFixFinding?.({
123 - kind: "check",
124 - check: { name: "Unit tests", status: "failure", description: "Test failed", url: null },
125 - })
126 - }
127 - >
128 - Fix check
129 - </button>
130 - </div>
131 - ),
132 -}));
133 -
134 -vi.mock("./PullRequestGuideTab", () => ({ PullRequestGuideTab: () => null }));
135 -vi.mock("./PullRequestCodeTab", () => ({
136 - default: ({
137 - onAddToAgentSelection,
138 - scrollerRef,
139 - }: ComponentProps<typeof import("./PullRequestCodeTab").default>) => (
140 - <div ref={scrollerRef} data-test-scroll="code">
141 - <button
142 - onClick={() =>
143 - onAddToAgentSelection?.({
144 - request: "Fix this line",
145 - comment: {
146 - id: "note-1",
147 - sectionId: "file:a.ts",
148 - sectionTitle: "a.ts",
149 - filePath: "a.ts",
150 - startIndex: 0,
151 - endIndex: 0,
152 - rangeLabel: "L1",
153 - text: "Please fix",
154 - diff: "+broken()",
155 - },
156 - })
157 - }
158 - >
159 - Add to agent
160 - </button>
161 - </div>
162 - ),
163 -}));
164 -
165 -import { PullRequestDetailPanel } from "./PullRequestDetailPanel";
166 -import { pullRequestPanelContext } from "./pullRequestDetail.logic";
167 -
168 -const detail: PullRequestDetailView = {
169 - provider: SourceControlProviderKind.make("github"),
170 - projectId: ProjectId.make("project"),
171 - projectTitle: "Project",
172 - workspaceRoot: "/workspace",
173 - repository: "owner/repo",
174 - number: 1,
175 - title: "Test pull request",
176 - body: "Original description",
177 - url: "https://github.com/owner/repo/pull/1",
178 - author: { login: "author", name: null, avatarUrl: null },
179 - viewer: "author",
180 - state: "open",
181 - isDraft: false,
182 - mergeability: "conflicting",
183 - additions: 1,
184 - deletions: 0,
185 - changedFiles: 1,
186 - headBranch: "feature",
187 - baseBranch: "main",
188 - createdAt: "2026-09-01T00:00:00Z",
189 - updatedAt: "2026-09-01T00:00:00Z",
190 - mergedAt: null,
191 - closedAt: null,
192 - reviewers: [],
193 - labels: [],
194 - checks: [{ name: "Unit tests", status: "success", description: null, url: null }],
195 - comments: [],
196 - commentCount: 0,
197 - commentsTruncated: false,
198 - reviewThreads: [],
199 - commits: [],
200 - mergeCapabilities: { merge: false, squash: false, rebase: false },
201 - capabilities: {
202 - diff: true,
203 - comment: false,
204 - search: true,
205 - actions: [],
206 - mergeMethods: [],
207 - review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
208 - reviewers: { request: false, listCandidates: false },
209 - edit: { changeRequest: true, comment: false },
210 - },
211 - viewerPermissions: {
212 - actions: [],
213 - comment: false,
214 - resolve: false,
215 - verdicts: [],
216 - requestReviewers: false,
217 - },
218 -};
219 -
220 -const threadRef: ScopedThreadRef = {
221 - environmentId: EnvironmentId.make("env-1"),
222 - threadId: ThreadId.make("thread-1"),
223 -};
224 -const draftId = DraftId.make("draft-1");
225 -const newDraftId = DraftId.make("new-draft");
226 -let renderer: ReactTestRenderer;
227 -
228 -beforeEach(() => {
229 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
230 - vi.stubGlobal("window", { addEventListener: vi.fn(), removeEventListener: vi.fn() });
231 - useComposerDraftStore.setState({ draftsByThreadKey: {} });
232 - newThread
233 - .mockReset()
234 - .mockResolvedValue({ draftId: newDraftId, threadId: ThreadId.make("new-thread") });
235 - prepareThread.mockReset().mockResolvedValue({
236 - _tag: "Success",
237 - value: { branch: "feature", worktreePath: "/workspace/pr" },
238 - });
239 -});
240 -afterEach(() => {
241 - act(() => renderer?.unmount());
242 - vi.unstubAllGlobals();
243 -});
244 -
245 -async function click(label: string) {
246 - const button = renderer.root
247 - .findAllByType("button")
248 - .find(
249 - (node) =>
250 - node.props["aria-label"] === label ||
251 - node.findAll((child) => child.children.includes(label)).length > 0,
252 - );
253 - expect(button, label).toBeDefined();
254 - await act(async () =>
255 - button!.props.onClick({
256 - nativeEvent: new Event("click"),
257 - preventDefault() {},
258 - stopPropagation() {},
259 - }),
260 - );
261 -}
262 -
263 -const actions = [
264 - "Resolve conflicts",
265 - "Ask a question",
266 - "Explain this PR",
267 - "Fix findings in this thread",
268 - "Fix check",
269 - "Add to agent",
270 -];
271 -
272 -const surface = { projectId: detail.projectId, repository: detail.repository, number: 1 };
273 -const link = (number: number, source: ThreadPullRequestLink["source"]): ThreadPullRequestLink => ({
274 - host: "github.com",
275 - repository: detail.repository,
276 - number,
277 - url: `https://github.com/${detail.repository}/pull/${number}`,
278 - source,
279 - linkedAt: "2026-09-01T00:00:00Z",
280 - snapshot: null,
281 - stack: null,
282 -});
283 -const stackThread = {
284 - projectId: detail.projectId,
285 - pullRequests: [link(3, "manual"), link(2, "stack"), link(1, "stack")],
286 -
287 - linkedPullRequest: { ...surface, number: 3, url: link(3, "manual").url },
288 -};
289 -const unrelatedThread = {
290 - projectId: detail.projectId,
291 - pullRequests: [link(9, "created")],
292 - linkedPullRequest: { ...surface, number: 9, url: link(9, "created").url },
293 -};
294 -
295 -describe.each([
296 - ["own PR, a lower layer of the thread's stack", stackThread, threadRef],
297 - ["another PR beside the current thread", unrelatedThread, threadRef],
298 - ["PR beside an unsent draft", null, draftId],
299 - ["standalone PR page", null, undefined],
300 -] as const)("%s", (_name, thread, target) => {
301 - const context = thread ? pullRequestPanelContext(thread, surface) : "page";
302 -
303 - function render() {
304 - renderer = create(
305 - <PullRequestDetailPanel
306 - environmentId={threadRef.environmentId}
307 - reference={detail}
308 - context={context}
309 - {...(target ? { composerDraftTarget: target, threadRef } : {})}
310 - shortcutsEnabled={false}
311 - getShortcutContext={() => ({
312 - terminalFocus: false,
313 - terminalOpen: false,
314 - previewFocus: false,
315 - previewOpen: false,
316 - isWeb: true,
317 - isDesktop: false,
318 - })}
319 - />,
320 - );
321 - }
322 -
323 - it(`${thread === stackThread ? "hides" : "offers"} the checkout`, async () => {
324 - await act(async () => render());
325 - const checkout = renderer.root
326 - .findAllByType("button")
327 - .filter((node) => node.props["aria-label"] === "Check out");
328 - expect(checkout).toHaveLength(thread === stackThread ? 0 : 1);
329 - });
330 -
331 - it.each(actions)("%s writes to the correct composer", async (action) => {
332 - if (target) useComposerDraftStore.getState().setPrompt(target, "Keep my draft");
333 - await act(async () => render());
334 - if (action === "Add to agent") await click("Code");
335 - await click(target ? action : action.replace("in this thread", "in a thread"));
336 - const draft = useComposerDraftStore.getState().getComposerDraft(target ?? newDraftId);
337 - if (action === "Resolve conflicts") expect(draft?.prompt).toContain("resolve every conflict");
338 - else if (action === "Fix check") expect(draft?.prompt).toContain("Fix the failing check");
339 - else if (action.startsWith("Fix findings"))
340 - expect(draft?.prompt).toContain("Fix the actionable findings");
341 - else expect(draft?.reviewComments?.length).toBeGreaterThan(0);
342 - if (action === "Add to agent") {
343 - expect(draft?.prompt).toContain("Fix this line");
344 - expect(draft?.reviewComments).toEqual(
345 - expect.arrayContaining([expect.objectContaining({ id: "note-1", diff: "+broken()" })]),
346 - );
347 - }
348 - if (target) {
349 - expect(draft?.prompt).toContain("Keep my draft");
350 - expect(newThread).not.toHaveBeenCalled();
351 - expect(prepareThread).not.toHaveBeenCalled();
352 - } else {
353 - expect(newThread).toHaveBeenCalled();
354 - }
355 - });
356 -});
357 -
358 -it("changes the title only for the active tab's main scroller", async () => {
359 - const scrollers = new Map<string, { scrollTop: number; scrollHeight: number }>();
360 - await act(async () => {
361 - renderer = create(
362 - <PullRequestDetailPanel
363 - environmentId={threadRef.environmentId}
364 - reference={detail}
365 - context="page"
366 - shortcutsEnabled={false}
367 - getShortcutContext={() => ({
368 - terminalFocus: false,
369 - terminalOpen: false,
370 - previewFocus: false,
371 - previewOpen: false,
372 - isWeb: true,
373 - isDesktop: false,
374 - })}
375 - />,
376 - {
377 - createNodeMock: (element) => {
378 - const props = element.props as Record<string, unknown>;
379 - const name = props["data-test-scroll"] as string | undefined;
380 - if (name) {
381 - const scroller = { scrollTop: 0, scrollHeight: 300 };
382 - scrollers.set(name, scroller);
383 - return scroller;
384 - }
385 - return { scrollHeight: props.inert === false ? 100 : 20 };
386 - },
387 - },
388 - );
389 - });
390 -
391 - const mainScroll = renderer.root.findByProps({
392 - className: "relative flex min-h-0 flex-1 flex-col overflow-hidden",
393 - });
394 - const titleFold = () => {
395 - let node = renderer.root.findByType("h1");
396 - while (typeof node.props.inert !== "boolean") node = node.parent!;
397 - return node;
398 - };
399 - const summary = scrollers.get("summary")!;
400 - const nested = { scrollTop: 200 };
401 - await act(async () => mainScroll.props.onScrollCapture({ target: nested }));
402 - expect(titleFold().props.inert).toBe(false);
403 - summary.scrollTop = 180;
404 - nested.scrollTop = 0;
405 - await act(async () => {
406 - mainScroll.props.onScrollCapture({ target: summary });
407 - mainScroll.props.onScrollCapture({ target: nested });
408 - });
409 - expect(titleFold().props.inert).toBe(true);
410 - expect(summary.scrollTop).toBe(100);
411 - expect(nested.scrollTop).toBe(0);
412 -
413 - await act(async () => mainScroll.props.onScrollCapture({ target: { scrollTop: 0 } }));
414 - expect(titleFold().props.inert).toBe(true);
415 - summary.scrollTop = 0;
416 - await act(async () => mainScroll.props.onScrollCapture({ target: summary }));
417 - expect(titleFold().props.inert).toBe(false);
418 -
419 - await click("Code");
420 - const code = scrollers.get("code")!;
421 - summary.scrollTop = 180;
422 - await act(async () => mainScroll.props.onScrollCapture({ target: summary }));
423 - expect(titleFold().props.inert).toBe(false);
424 - code.scrollTop = 180;
425 - await act(async () => mainScroll.props.onScrollCapture({ target: code }));
426 - expect(titleFold().props.inert).toBe(true);
427 - expect(code.scrollTop).toBe(100);
428 - await click("Summary");
429 - expect(titleFold().props.inert).toBe(false);
430 - await click("Code");
431 - expect(titleFold().props.inert).toBe(true);
432 - code.scrollTop = 0;
433 - await act(async () => mainScroll.props.onScrollCapture({ target: code }));
434 - expect(titleFold().props.inert).toBe(false);
435 -});
apps/web/src/components/settings/AcpRegistrySearchStep.browser.test.tsx new
+260
@@ -0,0 +1,260 @@
1 +import { EnvironmentId, ProviderDriverKind, type AcpRegistrySearchAgent } from "@t3tools/contracts";
2 +import * as Cause from "effect/Cause";
3 +import { act } from "react";
4 +import { createRoot, type Root } from "react-dom/client";
5 +import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
6 +import { page, userEvent } from "vite-plus/test/browser";
7 +
8 +const 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 +
18 +vi.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 +});
31 +vi.mock(import("../../state/session"), async (original) => ({
32 + ...(await original()),
33 + useEnvironmentScope: () => state.canManage,
34 + readEnvironmentScope: () => state.canManage,
35 +}));
36 +vi.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 +}));
45 +vi.mock(import("../../state/use-atom-command"), async (original) => ({
46 + ...(await original()),
47 + useAtomCommand: (() => state.prepare) as never,
48 +}));
49 +
50 +import { AcpRegistrySearchStep } from "./AcpRegistrySearchStep";
51 +
52 +const environmentId = EnvironmentId.make("remote-device");
53 +const 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 +
67 +const roots: Root[] = [];
68 +let root: Root;
69 +
70 +function 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 + );
93 +}
94 +
95 +const searchBox = () => page.getByRole("searchbox", { name: "Search ACP Registry" });
96 +const lastQuery = () =>
97 + (state.search.mock.lastCall?.[0] as { input: { query: string } } | undefined)?.input.query;
98 +
99 +function deferred<T>() {
100 + let resolve!: (value: T) => void;
101 + const promise = new Promise<T>((done) => {
102 + resolve = done;
103 + });
104 + return { promise, resolve };
105 +}
106 +
107 +beforeEach(() => {
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 +
124 +afterEach(async () => {
125 + vi.useRealTimers();
126 + for (const mounted of roots.splice(0)) await act(async () => mounted.unmount());
127 + document.body.replaceChildren();
128 +});
129 +
130 +it("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 +
148 +it("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 +
164 +it("submits a typed query at once and refreshes when the same query is submitted again", async () => {
165 + await render();
166 + await userEvent.fill(searchBox(), "Codex");
167 + await userEvent.keyboard("{Enter}");
168 + expect(lastQuery()).toBe("Codex");
169 + expect(state.refresh).not.toHaveBeenCalled();
170 +
171 + state.result = { agents: [gemini] };
172 + await render();
173 + await userEvent.click(searchBox());
174 + await userEvent.keyboard("{Enter}");
175 + expect(state.refresh).toHaveBeenCalledOnce();
176 +
177 + state.isPending = true;
178 + await render();
179 + await expect
180 + .element(page.getByRole("status").filter({ hasText: "Refreshing ACP Registry results." }))
181 + .toBeInTheDocument();
182 + await expect.element(page.getByRole("button", { name: "Add Gemini CLI" })).toBeVisible();
183 +});
184 +
185 +it("prepares a result before handing it back to the wizard", async () => {
186 + state.prepare.mockResolvedValueOnce({
187 + _tag: "Success",
188 + value: { agentId: "gemini", version: "2.0.0", distribution: "binary", prepared: true },
189 + });
190 + state.result = { agents: [gemini] };
191 + const onPrepared = vi.fn();
192 + await render({ onPrepared });
193 +
194 + await page.getByRole("button", { name: "Add Gemini CLI" }).click();
195 +
196 + expect(state.prepare).toHaveBeenCalledWith({ environmentId, input: { agentId: "gemini" } });
197 + await vi.waitFor(() =>
198 + expect(onPrepared).toHaveBeenCalledWith({
199 + ...gemini,
200 + version: "2.0.0",
201 + distribution: "binary",
202 + }),
203 + );
204 +});
205 +
206 +it("shows progress, locks the step while an agent prepares, and reports a failure", async () => {
207 + const pending = deferred<unknown>();
208 + state.prepare.mockReturnValueOnce(pending.promise);
209 + state.result = { agents: [{ ...gemini, distribution: "binary" }] };
210 + await render();
211 +
212 + await page.getByRole("button", { name: "Add Gemini CLI" }).click();
213 + await expect.element(page.getByRole("button", { name: "Downloading Gemini CLI" })).toBeDisabled();
214 + await expect.element(searchBox()).toBeDisabled();
215 +
216 + await act(async () =>
217 + pending.resolve({ _tag: "Failure", cause: Cause.fail(new Error("Registry download failed.")) }),
218 + );
219 + await expect.element(page.getByText("Registry download failed.")).toBeVisible();
220 + await expect.element(page.getByRole("button", { name: "Add Gemini CLI" })).toBeEnabled();
221 +});
222 +
223 +it("rechecks the grant before preparing an agent", async () => {
224 + state.result = { agents: [gemini] };
225 + const onPrepared = vi.fn();
226 + await render({ onPrepared });
227 + state.canManage = false;
228 +
229 + await page.getByRole("button", { name: "Add Gemini CLI" }).click();
230 +
231 + expect(state.prepare).not.toHaveBeenCalled();
232 + expect(onPrepared).not.toHaveBeenCalled();
233 +});
234 +
235 +it("ignores prepare completion after unmount", async () => {
236 + const pending = deferred<unknown>();
237 + state.prepare.mockReturnValueOnce(pending.promise);
238 + state.result = { agents: [gemini] };
239 + const onPrepared = vi.fn();
240 + await render({ onPrepared });
241 +
242 + await page.getByRole("button", { name: "Add Gemini CLI" }).click();
243 + await act(async () => root.unmount());
244 + await act(async () =>
245 + pending.resolve({
246 + _tag: "Success",
247 + value: { agentId: "gemini", version: "1.2.3", distribution: "npx", prepared: true },
248 + }),
249 + );
250 +
251 + expect(onPrepared).not.toHaveBeenCalled();
252 +});
253 +
254 +it("shows an existing registry configuration as already added", async () => {
255 + state.result = { agents: [gemini] };
256 + await render({ configured: true });
257 + await expect
258 + .element(page.getByRole("button", { name: "Already added Gemini CLI" }))
259 + .toBeDisabled();
260 +});
apps/web/src/components/settings/AcpRegistrySearchStep.test.tsx deleted
-359
@@ -1,359 +0,0 @@
1 -import { isValidElement, type ReactElement } from "react";
2 -import { EnvironmentId, ProviderDriverKind, type AcpRegistrySearchAgent } from "@t3tools/contracts";
3 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4 -
5 -import { visitElements } from "../../test/reactElementTree";
6 -import { reactHookHarness as hooks } from "../../test/reactHookHarness";
7 -
8 -const atoms = vi.hoisted(() => ({
9 - search: Symbol("acp-search"),
10 - prepare: Symbol("acp-prepare"),
11 -}));
12 -
13 -const 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(() => atoms.search),
20 - prepare: vi.fn(),
21 -}));
22 -
23 -const lifecycle = vi.hoisted(() => ({
24 - cleanups: [] as Array<() => void>,
25 -}));
26 -
27 -vi.mock("react", async (importOriginal) => {
28 - const actual = await importOriginal<typeof import("react")>();
29 - const { reactHookHarness } = await import("../../test/reactHookHarness");
30 - return {
31 - ...actual,
32 - useEffect: (effect: () => void | (() => void)) => {
33 - const cleanup = effect();
34 - if (cleanup) lifecycle.cleanups.push(cleanup);
35 - },
36 - useRef: reactHookHarness.useRef,
37 - useLayoutEffect: (effect: () => void | (() => void)) => {
38 - const cleanup = effect();
39 - if (cleanup) lifecycle.cleanups.push(cleanup);
40 - },
41 - useState: reactHookHarness.useState,
42 - };
43 -});
44 -
45 -vi.mock("react/compiler-runtime", async () => {
46 - const { reactHookHarness } = await import("../../test/reactHookHarness");
47 - return { c: reactHookHarness.useMemoCache };
48 -});
49 -
50 -vi.mock("../../state/server", () => ({
51 - serverEnvironment: {
52 - searchAcpRegistry: state.search,
53 - prepareAcpRegistryAgent: atoms.prepare,
54 - },
55 -}));
56 -
57 -vi.mock("../../state/session", () => ({
58 - useEnvironmentScope: () => state.canManage,
59 - readEnvironmentScope: () => state.canManage,
60 -}));
61 -
62 -vi.mock("../../state/query", () => ({
63 - useEnvironmentQuery: () => ({
64 - data: state.result,
65 - error: state.error,
66 - isPending: state.isPending,
67 - refresh: state.refresh,
68 - }),
69 -}));
70 -
71 -vi.mock("../../state/use-atom-command", () => ({
72 - useAtomCommand: () => state.prepare,
73 -}));
74 -
75 -vi.mock("@t3tools/client-runtime/state/runtime", () => ({
76 - isAtomCommandInterrupted: () => false,
77 - squashAtomCommandFailure: () => new Error("Prepare failed."),
78 -}));
79 -
80 -import { AcpRegistrySearchStep } from "./AcpRegistrySearchStep";
81 -
82 -const environmentId = EnvironmentId.make("remote-device");
83 -const gemini: AcpRegistrySearchAgent = {
84 - id: "gemini",
85 - name: "Gemini CLI",
86 - version: "1.2.3",
87 - description: "Google's agent",
88 - authors: ["Google <gemini-cli@google.com>", "Contributor"],
89 - license: "Apache-2.0",
90 - website: "https://example.com/docs",
91 - repository: "https://example.com/source",
92 - icon: "https://example.com/icon.png",
93 - distribution: "npx",
94 - integrity: "registry",
95 -};
96 -
97 -function render(options?: {
98 - readonly configured?: boolean;
99 - readonly onPrepared?: (agent: AcpRegistrySearchAgent) => void;
100 -}): ReactElement<Record<string, unknown>> {
101 - hooks.beginRender();
102 - return AcpRegistrySearchStep({
103 - environmentId,
104 - providerInstances: options?.configured
105 - ? {
106 - acpRegistry_gemini: {
107 - driver: ProviderDriverKind.make("acpRegistry"),
108 - config: { agentId: "gemini" },
109 - },
110 - }
111 - : {},
112 - onPrepared: options?.onPrepared ?? vi.fn(),
113 - onManualConfiguration: vi.fn(),
114 - }) as ReactElement<Record<string, unknown>>;
115 -}
116 -
117 -function findByAriaLabel(
118 - tree: ReactElement<Record<string, unknown>>,
119 - label: string,
120 -): ReactElement<Record<string, unknown>> {
121 - const found = visitElements(expandRows(tree), (element) => element.props["aria-label"] === label);
122 - expect(found).not.toBeNull();
123 - return found!;
124 -}
125 -
126 -// The harness calls components as plain functions, so result rows stay
127 -// unexpanded elements until rendered here.
128 -function expandRows(node: unknown): unknown {
129 - if (Array.isArray(node)) return node.map(expandRows);
130 - if (!isValidElement<Record<string, unknown>>(node)) return node;
131 - if (typeof node.type === "function" && node.type.name === "AcpRegistryAgentRow") {
132 - return expandRows((node.type as (props: unknown) => unknown)(node.props));
133 - }
134 - const props = Object.fromEntries(
135 - Object.entries(node.props).map(([key, value]) => [key, expandRows(value)]),
136 - );
137 - return { ...node, props };
138 -}
139 -
140 -describe("AcpRegistrySearchStep", () => {
141 - beforeEach(() => {
142 - state.canManage = true;
143 - vi.useFakeTimers();
144 - hooks.reset();
145 - state.result = null;
146 - state.error = null;
147 - state.isPending = false;
148 - state.refresh.mockReset();
149 - state.search.mockClear();
150 - state.prepare.mockReset().mockResolvedValue({
151 - _tag: "Success",
152 - value: { agentId: "gemini", version: "1.2.3", distribution: "npx", prepared: true },
153 - });
154 - lifecycle.cleanups = [];
155 - vi.stubGlobal(
156 - "fetch",
157 - vi.fn(() => new Promise<Response>(() => {})),
158 - );
159 - });
160 - afterEach(() => {
161 - for (const cleanup of lifecycle.cleanups) cleanup();
162 - vi.useRealTimers();
163 - });
164 -
165 - it("loads the catalog immediately and searches only after typing settles", () => {
166 - const initial = render();
167 - expect(state.search).toHaveBeenLastCalledWith({
168 - environmentId,
169 - input: { query: "" },
170 - });
171 -
172 - const input = findByAriaLabel(initial, "Search ACP Registry");
173 - expect(input.props.size).toBe("sm");
174 - (input.props.onChange as ((event: { currentTarget: { value: string } }) => void) | undefined)?.(
175 - { currentTarget: { value: " Gemini " } },
176 - );
177 - vi.advanceTimersByTime(200);
178 - render();
179 - expect(state.search).toHaveBeenLastCalledWith({ environmentId, input: { query: "" } });
180 - (input.props.onChange as ((event: { currentTarget: { value: string } }) => void) | undefined)?.(
181 - {
182 - currentTarget: { value: " Gemini CLI " },
183 - },
184 - );
185 - vi.advanceTimersByTime(299);
186 - render();
187 - expect(state.search).toHaveBeenLastCalledWith({ environmentId, input: { query: "" } });
188 - vi.advanceTimersByTime(1);
189 - render();
190 - expect(state.search).toHaveBeenLastCalledWith({
191 - environmentId,
192 - input: { query: "Gemini CLI" },
193 - });
194 - (input.props.onChange as ((event: { currentTarget: { value: string } }) => void) | undefined)?.(
195 - {
196 - currentTarget: { value: "" },
197 - },
198 - );
199 - vi.advanceTimersByTime(300);
200 - render();
201 - expect(state.search).toHaveBeenLastCalledWith({ environmentId, input: { query: "" } });
202 - });
203 -
204 - it("renders deterministic loading, error, and empty states", () => {
205 - state.isPending = true;
206 - expect(
207 - visitElements(render(), (element) => element.props.children === "Searching the registry..."),
208 - ).not.toBeNull();
209 -
210 - state.isPending = false;
211 - state.error = "Registry unavailable.";
212 - expect(
213 - visitElements(render(), (element) => element.props.children === "Registry unavailable."),
214 - ).not.toBeNull();
215 -
216 - state.error = null;
217 - state.result = { agents: [] };
218 - expect(
219 - visitElements(render(), (element) => element.props.children === "No compatible agents found"),
220 - ).not.toBeNull();
221 - });
222 -
223 - it("keeps same-query refreshes visible and announced while retaining results", () => {
224 - const first = render();
225 - const input = findByAriaLabel(first, "Search ACP Registry");
226 - (input.props.onChange as ((event: { currentTarget: { value: string } }) => void) | undefined)?.(
227 - {
228 - currentTarget: { value: "Codex" },
229 - },
230 - );
231 - const draft = render();
232 - const searchForm = visitElements(draft, (element) => element.type === "form");
233 - (searchForm?.props.onSubmit as ((event: { preventDefault: () => void }) => void) | undefined)?.(
234 - {
235 - preventDefault: vi.fn(),
236 - },
237 - );
238 -
239 - state.result = { agents: [gemini] };
240 - const resultTree = render();
241 - expect(state.search).toHaveBeenCalledWith({
242 - environmentId,
243 - input: { query: "Codex" },
244 - });
245 - const form = visitElements(resultTree, (element) => element.type === "form");
246 - (form?.props.onSubmit as ((event: { preventDefault: () => void }) => void) | undefined)?.({
247 - preventDefault: vi.fn(),
248 - });
249 - expect(state.refresh).toHaveBeenCalledOnce();
250 -
251 - state.isPending = true;
252 - const refreshingTree = render();
253 - expect(
254 - visitElements(
255 - refreshingTree,
256 - (element) =>
257 - element.props.role === "status" &&
258 - element.props.children === "Refreshing ACP Registry results.",
259 - ),
260 - ).not.toBeNull();
261 - expect(findByAriaLabel(refreshingTree, "Add Gemini CLI")).not.toBeNull();
262 - });
263 -
264 - it("prepares a result before handing it back to the wizard", async () => {
265 - state.prepare.mockResolvedValueOnce({
266 - _tag: "Success",
267 - value: { agentId: "gemini", version: "2.0.0", distribution: "binary", prepared: true },
268 - });
269 - state.result = { agents: [gemini] };
270 - const onPrepared = vi.fn();
271 - const tree = render({ onPrepared });
272 -
273 - const add = findByAriaLabel(tree, "Add Gemini CLI");
274 - (add.props.onClick as (() => void) | undefined)?.();
275 - await Promise.resolve();
276 - await Promise.resolve();
277 -
278 - expect(state.prepare).toHaveBeenCalledWith({
279 - environmentId,
280 - input: { agentId: "gemini" },
281 - });
282 - expect(onPrepared).toHaveBeenCalledWith({
283 - ...gemini,
284 - version: "2.0.0",
285 - distribution: "binary",
286 - });
287 - });
288 -
289 - it("rechecks the grant before preparing an agent", async () => {
290 - state.result = { agents: [gemini] };
291 - const onPrepared = vi.fn();
292 - const add = findByAriaLabel(render({ onPrepared }), "Add Gemini CLI");
293 - state.canManage = false;
294 - await (add.props.onClick as () => void)();
295 - expect(state.prepare).not.toHaveBeenCalled();
296 - expect(onPrepared).not.toHaveBeenCalled();
297 - });
298 -
299 - it("ignores a stale prepare completion", async () => {
300 - let resolveFirst!: (value: { readonly _tag: "Success"; readonly value: unknown }) => void;
301 - let resolveSecond!: (value: { readonly _tag: "Success"; readonly value: unknown }) => void;
302 - state.prepare
303 - .mockImplementationOnce(
304 - () =>
305 - new Promise((resolve) => {
306 - resolveFirst = resolve;
307 - }),
308 - )
309 - .mockImplementationOnce(
310 - () =>
311 - new Promise((resolve) => {
312 - resolveSecond = resolve;
313 - }),
314 - );
315 - state.result = { agents: [gemini] };
316 - const onPrepared = vi.fn();
317 - const tree = render({ onPrepared });
318 - const add = findByAriaLabel(tree, "Add Gemini CLI");
319 -
320 - (add.props.onClick as (() => void) | undefined)?.();
321 - (add.props.onClick as (() => void) | undefined)?.();
322 - resolveFirst({ _tag: "Success", value: {} });
323 - await Promise.resolve();
324 - expect(onPrepared).not.toHaveBeenCalled();
325 -
326 - resolveSecond({ _tag: "Success", value: {} });
327 - await Promise.resolve();
328 - expect(onPrepared).toHaveBeenCalledOnce();
329 - });
330 -
331 - it("ignores prepare completion after unmount", async () => {
332 - let resolvePrepare!: (value: { readonly _tag: "Success"; readonly value: unknown }) => void;
333 - state.prepare.mockImplementationOnce(
334 - () =>
335 - new Promise((resolve) => {
336 - resolvePrepare = resolve;
337 - }),
338 - );
339 - state.result = { agents: [gemini] };
340 - const onPrepared = vi.fn();
341 - const tree = render({ onPrepared });
342 -
343 - const add = findByAriaLabel(tree, "Add Gemini CLI");
344 - (add.props.onClick as (() => void) | undefined)?.();
345 - for (const cleanup of lifecycle.cleanups) cleanup();
346 - resolvePrepare({ _tag: "Success", value: {} });
347 - await Promise.resolve();
348 -
349 - expect(onPrepared).not.toHaveBeenCalled();
350 - });
351 -
352 - it("renders existing registry configuration as already added", () => {
353 - state.result = { agents: [gemini] };
354 - const tree = render({ configured: true });
355 - const added = findByAriaLabel(tree, "Already added Gemini CLI");
356 -
357 - expect(added.props.disabled).toBe(true);
358 - });
359 -});