Skip to content
TypeScript

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

Julius Marmingec20eab44e1d9
diff --git a/apps/web/src/components/diffs/StyledDiffCodeView.test.tsx b/apps/web/src/components/diffs/StyledDiffCodeView.browser.test.tsx
similarity index 61%
rename from apps/web/src/components/diffs/StyledDiffCodeView.test.tsx
rename to apps/web/src/components/diffs/StyledDiffCodeView.browser.test.tsx
index 374f3437a80..6e0eff69bb0 100644
--- a/apps/web/src/components/diffs/StyledDiffCodeView.test.tsx
+++ b/apps/web/src/components/diffs/StyledDiffCodeView.browser.test.tsx
@@ -1,4 +1,3 @@
-import type * as NodeWorkerThreads from "node:worker_threads";
import {
FileRenderer,
getSharedHighlighter,
@@ -15,14 +14,15 @@ import {
useLayoutEffect,
useRef,
useState,
+ type ReactElement,
type Ref,
} from "react";
-import { create, type ReactTestRenderer } from "react-test-renderer";
+import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
const testState = vi.hoisted(() => ({
- workers: [] as NodeWorkerThreads.Worker[],
- terminations: [] as Promise<number>[],
+ workers: [] as Worker[],
+ terminations: 0,
requests: [] as WorkerRequest[],
pools: new Map<WorkerPoolManager, Promise<void>>(),
renderPools: [] as (WorkerPoolManager | undefined)[],
@@ -32,43 +32,32 @@ const testState = vi.hoisted(() => ({
onInitializationHeld: undefined as (() => void) | undefined,
}));
-vi.mock("../../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
-
-vi.mock("@pierre/diffs/worker/worker.js?worker", async () => {
- const { Worker } = await import("node:worker_threads");
- const moduleUrl = import.meta.resolve("@pierre/diffs/worker/worker.js");
+vi.mock(import("../../hooks/useTheme"), async (original) => ({
+ ...(await original()),
+ useTheme: (() => ({ resolvedTheme: "dark" })) as never,
+}));
+// Wraps Pierre's real worker so the suite can count workers, read requests and hold startup.
+// Vite's `?worker` export is a factory that returns a plain Worker, so this patches the instance.
+vi.mock("@pierre/diffs/worker/worker.js?worker", async (original) => {
+ const actual = await original<{ default: new () => Worker }>();
return {
- default: class {
- worker: NodeWorkerThreads.Worker;
-
- constructor() {
- if (testState.failWorkers) throw new Error("Worker creation failed");
- this.worker = new Worker(
- `const { parentPort, workerData } = require("node:worker_threads");
- globalThis.self = {
- addEventListener(type, listener) {
- if (type === "message") parentPort.on("message", data => listener({ data }));
- if (type === "error") process.on("uncaughtException", listener);
- }
- };
- globalThis.postMessage = data => parentPort.postMessage(data);
- import(workerData.moduleUrl);`,
- { eval: true, workerData: { moduleUrl }, execArgv: [] },
- );
- testState.workers.push(this.worker);
- }
-
- addEventListener(
- type: "message" | "error",
- listener: (event: { data: WorkerResponse } | Error) => void,
- ) {
- if (type === "error") {
- this.worker.on("error", listener);
+ ...actual,
+ default: function TestDiffsWorker() {
+ if (testState.failWorkers) throw new Error("Worker creation failed");
+ const worker = new actual.default();
+ testState.workers.push(worker);
+ const addEventListener = worker.addEventListener.bind(worker);
+ const postMessage = worker.postMessage.bind(worker);
+ const terminate = worker.terminate.bind(worker);
+ worker.addEventListener = (type: string, listener: EventListenerOrEventListenerObject) => {
+ if (type !== "message" || typeof listener !== "function") {
+ addEventListener(type, listener);
return;
}
- this.worker.on("message", (data: WorkerResponse) => {
- const deliver = () => listener({ data });
+ addEventListener("message", (event) => {
+ const data = (event as MessageEvent<WorkerResponse>).data;
+ const deliver = () => listener(event);
if (
testState.holdInitialization &&
data.type === "success" &&
@@ -80,27 +69,28 @@ vi.mock("@pierre/diffs/worker/worker.js?worker", async () => {
deliver();
}
});
- }
-
- postMessage(message: WorkerRequest) {
+ };
+ worker.postMessage = (message: WorkerRequest) => {
testState.requests.push(message);
- this.worker.postMessage(message, []);
- }
-
- terminate() {
- testState.terminations.push(this.worker.terminate());
- }
+ postMessage(message);
+ };
+ worker.terminate = () => {
+ testState.terminations += 1;
+ terminate();
+ };
+ return worker;
},
};
});
-vi.mock("@pierre/diffs/react", async (importOriginal) => ({
- ...(await importOriginal<typeof import("@pierre/diffs/react")>()),
- CodeView: (props: CodeViewProps<undefined, undefined>) => {
- return props.items?.map((item) =>
+// Pierre's real viewer virtualizes into a shadow root; this stand-in renders each file through
+// the same worker pool and keeps the highlighted HTML readable.
+vi.mock(import("@pierre/diffs/react"), async (original) => ({
+ ...(await original()),
+ CodeView: ((props: CodeViewProps<undefined, undefined>) =>
+ props.items?.map((item) =>
item.type === "file" ? <FileOutput key={item.id} file={item.file} /> : null,
- );
- },
+ )) as never,
}));
import { StyledDiffCodeView } from "./StyledDiffCodeView";
@@ -152,12 +142,33 @@ function renderViews(count: number) {
);
}
-describe("code-view worker lifecycle", () => {
- let renderer: ReactTestRenderer | undefined;
+const roots: Root[] = [];
+
+function mount(element: ReactElement) {
+ const container = document.createElement("div");
+ document.body.append(container);
+ const root = createRoot(container);
+ roots.push(root);
+ return {
+ root,
+ render: (next: ReactElement) => act(async () => root.render(next)),
+ initial: act(async () => root.render(element)),
+ };
+}
+async function unmountAll() {
+ for (const root of roots.splice(0)) await act(async () => root.unmount());
+ document.body.replaceChildren();
+}
+
+const codeFile = (name: string) =>
+ document.querySelector(`[data-code-file="${name}"]`)?.textContent ?? "";
+const loadingViews = () => document.querySelectorAll('[role="status"]').length;
+
+describe("code-view worker lifecycle", () => {
beforeEach(() => {
testState.workers = [];
- testState.terminations = [];
+ testState.terminations = 0;
testState.requests = [];
testState.pools.clear();
testState.renderPools = [];
@@ -165,14 +176,10 @@ describe("code-view worker lifecycle", () => {
testState.holdInitialization = false;
testState.heldResponses = [];
testState.onInitializationHeld = undefined;
- vi.stubGlobal("window", {});
- vi.stubGlobal("navigator", { hardwareConcurrency: 2 });
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ // Pins the pool at two workers whatever machine runs the suite.
+ Object.defineProperty(navigator, "hardwareConcurrency", { configurable: true, value: 2 });
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
- vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) =>
- setImmediate(() => callback(0)),
- );
- vi.stubGlobal("cancelAnimationFrame", clearImmediate);
const initialize = WorkerPoolManager.prototype.initialize;
vi.spyOn(WorkerPoolManager.prototype, "initialize").mockImplementation(function (
this: WorkerPoolManager,
@@ -185,85 +192,71 @@ describe("code-view worker lifecycle", () => {
});
afterEach(async () => {
- await act(async () => renderer?.unmount());
- renderer = undefined;
+ await unmountAll();
await vi.runOnlyPendingTimersAsync();
- await Promise.all(testState.terminations);
vi.useRealTimers();
vi.restoreAllMocks();
vi.unstubAllGlobals();
+ delete (navigator as { hardwareConcurrency?: number }).hardwareConcurrency;
});
it("starts on demand, keeps quick reopens warm, and expires the last closed pool", async () => {
- await act(async () => {
- renderer = create(renderViews(0));
- });
- const mounted = renderer!;
- const button = mounted.root.findByType("button");
+ const view = mount(renderViews(0));
+ await view.initial;
+ const button = document.querySelector("button")!;
expect(testState.workers).toHaveLength(0);
expect(testState.pools.size).toBe(0);
- await act(async () => {
- (button.props as { onClick(): void }).onClick();
- mounted.update(renderViews(1));
- });
+ await act(async () => button.click());
+ await view.render(renderViews(1));
const pool = [...testState.pools.keys()][0]!;
await act(async () => testState.pools.get(pool));
expect(pool.isInitialized()).toBe(true);
expect(testState.workers).toHaveLength(2);
- expect(mounted.root.findByProps({ "data-code-file": "notes.txt" }).children.join("")).toContain(
- "Plain text is ready.",
- );
+ await vi.waitFor(() => expect(codeFile("notes.txt")).toContain("Plain text is ready."));
expect(testState.requests.filter((request) => request.type === "file")).toHaveLength(0);
- await act(async () => mounted.update(renderViews(2)));
+ await view.render(renderViews(2));
await act(async () => pool.primeFileHighlightCache(files[1]!));
expect(testState.pools.size).toBe(1);
expect(testState.workers).toHaveLength(2);
expect(new Set(testState.renderPools)).toEqual(new Set([pool]));
expect(pool.getFileResultCache(files[1]!)).toBeDefined();
- expect(mounted.root.findByProps({ "data-code-file": "answer.ts" }).children.join("")).toContain(
- "answer",
- );
+ await vi.waitFor(() => expect(codeFile("answer.ts")).toContain("answer"));
- await act(async () => mounted.update(renderViews(1)));
+ await view.render(renderViews(1));
expect(pool.getStats().totalWorkers).toBe(2);
- expect(testState.terminations).toHaveLength(0);
- await act(async () => mounted.update(renderViews(0)));
+ expect(testState.terminations).toBe(0);
+ await view.render(renderViews(0));
await vi.advanceTimersByTimeAsync(29_999);
expect(pool.getStats().totalWorkers).toBe(2);
- expect(testState.terminations).toHaveLength(0);
+ expect(testState.terminations).toBe(0);
- await act(async () => mounted.update(renderViews(1)));
+ await view.render(renderViews(1));
expect(testState.pools.size).toBe(1);
expect(testState.workers).toHaveLength(2);
- expect(mounted.root.findAllByProps({ role: "status" })).toHaveLength(0);
+ expect(loadingViews()).toBe(0);
expect(pool.getFileResultCache(files[1]!)).toBeDefined();
await vi.advanceTimersByTimeAsync(30_000);
expect(pool.getStats().totalWorkers).toBe(2);
- await act(async () => mounted.update(renderViews(0)));
+ await view.render(renderViews(0));
await vi.advanceTimersByTimeAsync(30_000);
- await Promise.all(testState.terminations);
expect(pool.getStats().totalWorkers).toBe(0);
- expect(testState.terminations).toHaveLength(2);
+ expect(testState.terminations).toBe(2);
- await act(async () => mounted.update(renderViews(1)));
+ await view.render(renderViews(1));
const reopenedPool = [...testState.pools.keys()][1]!;
await act(async () => testState.pools.get(reopenedPool));
expect(reopenedPool.isInitialized()).toBe(true);
expect(testState.workers).toHaveLength(4);
- expect(mounted.root.findByType("button")).toBe(button);
- expect(button.children).toEqual(["Edited draft"]);
- expect(mounted.root.findByProps({ "data-code-file": "notes.txt" }).children.join("")).toContain(
- "Plain text is ready.",
- );
+ expect(document.querySelector("button")).toBe(button);
+ expect(button.textContent).toBe("Edited draft");
+ await vi.waitFor(() => expect(codeFile("notes.txt")).toContain("Plain text is ready."));
});
it("renders through Pierre's main-thread fallback when worker creation fails", async () => {
testState.failWorkers = true;
- await act(async () => {
- renderer = create(renderViews(1));
- });
+ await mount(renderViews(1)).initial;
const pool = [...testState.pools.keys()][0]!;
await act(async () => {
await expect(testState.pools.get(pool)).rejects.toMatchObject({ _tag: "DiffWorkerError" });
@@ -275,9 +268,7 @@ describe("code-view worker lifecycle", () => {
});
expect(pool.isWorkingPool()).toBe(false);
expect(testState.workers).toHaveLength(0);
- expect(
- renderer!.root.findByProps({ "data-code-file": "notes.txt" }).children.join(""),
- ).toContain("Plain text is ready.");
+ await vi.waitFor(() => expect(codeFile("notes.txt")).toContain("Plain text is ready."));
});
it("keeps an initializing pool until its last view closes and ignores late responses", async () => {
@@ -285,34 +276,32 @@ describe("code-view worker lifecycle", () => {
const held = new Promise<void>((resolve) => {
testState.onInitializationHeld = resolve;
});
- await act(async () => {
- renderer = create(renderViews(2));
- });
+ const view = mount(renderViews(2));
+ await view.initial;
const pool = [...testState.pools.keys()][0]!;
const pending = testState.pools.get(pool)!;
await held;
expect(pool.isInitialized()).toBe(false);
expect(testState.pools.size).toBe(1);
- expect(renderer!.root.findAllByProps({ role: "status" })).toHaveLength(2);
+ expect(loadingViews()).toBe(2);
expect(testState.renderPools).toHaveLength(0);
- await act(async () => renderer!.update(renderViews(1)));
+ await view.render(renderViews(1));
expect(pool.getStats().totalWorkers).toBe(2);
- expect(testState.terminations).toHaveLength(0);
- await act(async () => renderer!.update(renderViews(0)));
+ expect(testState.terminations).toBe(0);
+ await view.render(renderViews(0));
// Pierre gives up on a held startup after 10 seconds; the idle timer then tears the pool down.
const timedOut = expect(pending).rejects.toThrow("worker initialization timed out");
await vi.advanceTimersByTimeAsync(30_000);
await timedOut;
- await Promise.all(testState.terminations);
await act(async () => {
for (const deliver of testState.heldResponses) deliver();
});
expect(pool.getStats().totalWorkers).toBe(0);
expect(testState.workers).toHaveLength(2);
- expect(testState.terminations).toHaveLength(2);
+ expect(testState.terminations).toBe(2);
expect(testState.renderPools).toHaveLength(0);
- expect(renderer!.root.findAllByType("pre")).toHaveLength(0);
+ expect(document.querySelectorAll("pre")).toHaveLength(0);
});
});
@@ -418,7 +407,8 @@ function RevealViews({
}
describe("code-view file reveals", () => {
- let renderer: ReactTestRenderer | undefined;
+ let view: ReturnType<typeof mount>;
+ const reveal = () => act(async () => document.querySelector("button")!.click());
beforeEach(() => {
revealCalls.length = 0;
@@ -426,64 +416,48 @@ describe("code-view file reveals", () => {
});
afterEach(async () => {
- await act(async () => renderer?.unmount());
- renderer = undefined;
+ await unmountAll();
vi.unstubAllGlobals();
});
it("does not replay a handled tree click or scroll an old handle when a selected file remounts the view", async () => {
- await act(async () => {
- renderer = create(<RevealViews scope="first" visible selectedFile="external-a" />);
- });
- await act(async () => {
- (renderer!.root.findByType("button").props as { onClick(): void }).onClick();
- });
+ view = mount(<RevealViews scope="first" visible selectedFile="external-a" />);
+ await view.initial;
+ await reveal();
expect(revealCalls.at(-1)?.fileKey).toBe("tree-file");
revealCalls.length = 0;
- await act(async () => {
- renderer!.update(
- <RevealViews scope="second" visible selectedFile="external-b" requestId={1} />,
- );
- });
+ await view.render(
+ <RevealViews scope="second" visible selectedFile="external-b" requestId={1} />,
+ );
expect(revealCalls).toEqual([
{ scope: "second", fileKey: "external-b", mounted: true, collapsed: false },
]);
});
it("waits for a live viewer and applies each pending tree click only once", async () => {
- await act(async () => {
- renderer = create(<RevealViews scope="diff" visible={false} selectedFile="external" />);
- });
- await act(async () => {
- (renderer!.root.findByType("button").props as { onClick(): void }).onClick();
- });
+ view = mount(<RevealViews scope="diff" visible={false} selectedFile="external" />);
+ await view.initial;
+ await reveal();
expect(revealCalls).toEqual([]);
- await act(async () => {
- renderer!.update(<RevealViews scope="diff" visible selectedFile="external" />);
- });
+ await view.render(<RevealViews scope="diff" visible selectedFile="external" />);
expect(revealCalls.map((call) => call.fileKey)).toEqual(["external", "tree-file"]);
revealCalls.length = 0;
- await act(async () => {
- renderer!.update(<RevealViews scope="diff" visible={false} selectedFile="external" />);
- });
- await act(async () => {
- renderer!.update(<RevealViews scope="diff" visible selectedFile="external" />);
- });
+ await view.render(<RevealViews scope="diff" visible={false} selectedFile="external" />);
+ await view.render(<RevealViews scope="diff" visible selectedFile="external" />);
expect(revealCalls).toEqual([
{ scope: "diff", fileKey: "external", mounted: true, collapsed: false },
]);
revealCalls.length = 0;
+ // A click that lands in the same update that hides the viewer waits for it to return.
await act(async () => {
- (renderer!.root.findByType("button").props as { onClick(): void }).onClick();
- renderer!.update(<RevealViews scope="diff" visible={false} selectedFile="external" />);
+ document.querySelector("button")!.click();
+ view.root.render(<RevealViews scope="diff" visible={false} selectedFile="external" />);
});
expect(revealCalls).toEqual([]);
- await act(async () => {
- renderer!.update(<RevealViews scope="diff" visible selectedFile="external" />);
- });
+ await view.render(<RevealViews scope="diff" visible selectedFile="external" />);
expect(revealCalls).toEqual([
{ scope: "diff", fileKey: "external", mounted: true, collapsed: false },
{ scope: "diff", fileKey: "tree-file", mounted: true, collapsed: false },
@@ -491,36 +465,27 @@ describe("code-view file reveals", () => {
});
it("cancels pending tree clicks when an external selection or diff scope changes", async () => {
- await act(async () => {
- renderer = create(<RevealViews scope="first" visible={false} selectedFile="external-a" />);
- });
- await act(async () => {
- (renderer!.root.findByType("button").props as { onClick(): void }).onClick();
- });
- await act(async () => {
- renderer!.update(
- <RevealViews scope="first" visible selectedFile="external-b" requestId={1} />,
- );
- });
+ view = mount(<RevealViews scope="first" visible={false} selectedFile="external-a" />);
+ await view.initial;
+ await reveal();
+ await view.render(
+ <RevealViews scope="first" visible selectedFile="external-b" requestId={1} />,
+ );
expect(revealCalls.map((call) => call.fileKey)).toEqual(["external-b"]);
revealCalls.length = 0;
- await act(async () => renderer!.update(<RevealViews scope="first" visible={false} />));
- await act(async () => {
- (renderer!.root.findByType("button").props as { onClick(): void }).onClick();
- });
- await act(async () => renderer!.update(<RevealViews scope="second" visible={false} />));
- await act(async () => renderer!.update(<RevealViews scope="first" visible />));
+ await view.render(<RevealViews scope="first" visible={false} />);
+ await reveal();
+ await view.render(<RevealViews scope="second" visible={false} />);
+ await view.render(<RevealViews scope="first" visible />);
expect(revealCalls).toEqual([]);
});
it("reveals after a collapsed file expands and honors another click on the same file", async () => {
- await act(async () => {
- renderer = create(<RevealViews scope="diff" visible />);
- });
- const reveal = renderer!.root.findByType("button").props as { onClick(): void };
- await act(async () => reveal.onClick());
- await act(async () => reveal.onClick());
+ view = mount(<RevealViews scope="diff" visible />);
+ await view.initial;
+ await reveal();
+ await reveal();
expect(revealCalls).toEqual([
{ scope: "diff", fileKey: "tree-file", mounted: true, collapsed: false },
{ scope: "diff", fileKey: "tree-file", mounted: true, collapsed: false },
diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.browser.test.tsx
new file mode 100644
index 00000000000..5b2460ecb18
--- /dev/null
+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.browser.test.tsx
@@ -0,0 +1,388 @@
+import {
+ EnvironmentId,
+ ProjectId,
+ SourceControlProviderKind,
+ ThreadId,
+ type PullRequestDetailView,
+ type ScopedThreadRef,
+ type ThreadPullRequestLink,
+} from "@t3tools/contracts";
+import { act, type ComponentProps } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+import { page } from "vite-plus/test/browser";
+import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
+
+import "~/index.css";
+
+const { newThread, prepareThread, refresh } = vi.hoisted(() => ({
+ newThread: vi.fn(),
+ prepareThread: vi.fn(),
+ refresh: vi.fn(),
+}));
+
+vi.mock(import("~/state/session"), async (original) => ({
+ ...(await original()),
+ useEnvironmentScope: () => true,
+ readEnvironmentScope: () => true,
+}));
+vi.mock(import("~/hooks/useSettings"), async (original) => ({
+ ...(await original()),
+ useEnvironmentSettings: (() => undefined) as never,
+}));
+vi.mock(import("~/hooks/useHandleNewThread"), async (original) => ({
+ ...(await original()),
+ useNewThreadHandler: (() => newThread) as never,
+}));
+vi.mock(import("~/lib/sourceControlActions"), async (original) => ({
+ ...(await original()),
+ usePreparePullRequestThreadAction: (() => ({
+ run: prepareThread,
+ isAllowed: true,
+ error: null,
+ })) as never,
+}));
+vi.mock(import("~/state/use-atom-command"), async (original) => ({
+ ...(await original()),
+ useAtomCommand: (() => vi.fn()) as never,
+}));
+vi.mock(import("~/state/pullRequests"), async (original) => {
+ const actual = await original();
+ const { Atom } = await import("effect/reactivity");
+ const cannotWriteGuides = Atom.make(false);
+ return {
+ ...actual,
+ pullRequestEnvironment: {
+ ...actual.pullRequestEnvironment,
+ detail: (() => "detail") as never,
+ activity: (() => "activity") as never,
+ reviewGuide: (() => "review-guide") as never,
+ generateReviewGuide: {
+ ...actual.pullRequestEnvironment.generateReviewGuide,
+ permissionAtom: () => cannotWriteGuides,
+ },
+ },
+ };
+});
+vi.mock(import("~/state/query"), async (original) => ({
+ ...(await original()),
+ useEnvironmentQuery: ((query: unknown) => ({
+ data: query === "detail" ? detail : null,
+ dataUpdatedAt: 0,
+ failure: null,
+ isPending: false,
+ isSuccess: true,
+ error: null,
+ refresh,
+ })) as never,
+}));
+vi.mock(import("~/state/usePullRequestStack"), async (original) => ({
+ ...(await original()),
+ usePullRequestStack: (() => ({
+ data: null,
+ isSuccess: true,
+ isPending: false,
+ error: null,
+ refresh,
+ })) as never,
+}));
+// The real tabs load diffs, markdown and checks from the environment; these stand-ins
+// expose the actions they hand back to the panel and a tall scroller.
+vi.mock(import("./PullRequestSummaryTab"), async (original) => ({
+ ...(await original()),
+ PullRequestSummaryTab: (({
+ onFixFinding,
+ scrollerRef,
+ }: ComponentProps<typeof import("./PullRequestSummaryTab").PullRequestSummaryTab>) => (
+ <div ref={scrollerRef} data-testid="summary-scroller" className="h-full overflow-y-auto">
+ <button
+ type="button"
+ onClick={() =>
+ onFixFinding?.({
+ kind: "check",
+ check: { name: "Unit tests", status: "failure", description: "Test failed", url: null },
+ })
+ }
+ >
+ Fix check
+ </button>
+ <div data-testid="nested-scroller" className="h-40 overflow-y-auto">
+ <div className="h-[2000px]" />
+ </div>
+ <div className="h-[3000px]" />
+ </div>
+ )) as never,
+}));
+vi.mock(import("./PullRequestCodeTab"), async (original) => ({
+ ...(await original()),
+ default: (({
+ onAddToAgentSelection,
+ scrollerRef,
+ }: ComponentProps<typeof import("./PullRequestCodeTab").default>) => (
+ <div ref={scrollerRef} data-testid="code-scroller" className="h-full overflow-y-auto">
+ <button
+ type="button"
+ onClick={() =>
+ onAddToAgentSelection?.({
+ request: "Fix this line",
+ comment: {
+ id: "note-1",
+ sectionId: "file:a.ts",
+ sectionTitle: "a.ts",
+ filePath: "a.ts",
+ startIndex: 0,
+ endIndex: 0,
+ rangeLabel: "L1",
+ text: "Please fix",
+ diff: "+broken()",
+ },
+ })
+ }
+ >
+ Add to agent
+ </button>
+ <div className="h-[3000px]" />
+ </div>
+ )) as never,
+}));
+
+import { PullRequestDetailPanel } from "./PullRequestDetailPanel";
+import { pullRequestPanelContext } from "./pullRequestDetail.logic";
+
+const detail: PullRequestDetailView = {
+ provider: SourceControlProviderKind.make("github"),
+ projectId: ProjectId.make("project"),
+ projectTitle: "Project",
+ workspaceRoot: "/workspace",
+ repository: "owner/repo",
+ number: 1,
+ title: "Test pull request",
+ body: "Original description",
+ url: "https://github.com/owner/repo/pull/1",
+ author: { login: "author", name: null, avatarUrl: null },
+ viewer: "author",
+ state: "open",
+ isDraft: false,
+ mergeability: "conflicting",
+ additions: 1,
+ deletions: 0,
+ changedFiles: 1,
+ headBranch: "feature",
+ baseBranch: "main",
+ createdAt: "2026-09-01T00:00:00Z",
+ updatedAt: "2026-09-01T00:00:00Z",
+ mergedAt: null,
+ closedAt: null,
+ reviewers: [],
+ labels: [],
+ checks: [{ name: "Unit tests", status: "success", description: null, url: null }],
+ comments: [],
+ commentCount: 0,
+ commentsTruncated: false,
+ reviewThreads: [],
+ commits: [],
+ mergeCapabilities: { merge: false, squash: false, rebase: false },
+ capabilities: {
+ diff: true,
+ comment: false,
+ search: true,
+ actions: [],
+ mergeMethods: [],
+ review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
+ reviewers: { request: false, listCandidates: false },
+ edit: { changeRequest: true, comment: false },
+ },
+ viewerPermissions: {
+ actions: [],
+ comment: false,
+ resolve: false,
+ verdicts: [],
+ requestReviewers: false,
+ },
+};
+
+const threadRef: ScopedThreadRef = {
+ environmentId: EnvironmentId.make("env-1"),
+ threadId: ThreadId.make("thread-1"),
+};
+const draftId = DraftId.make("draft-1");
+const newDraftId = DraftId.make("new-draft");
+const shortcutContext = () => ({
+ terminalFocus: false,
+ terminalOpen: false,
+ previewFocus: false,
+ previewOpen: false,
+ isWeb: true,
+ isDesktop: false,
+});
+
+const roots: Root[] = [];
+
+function render(props: Partial<ComponentProps<typeof PullRequestDetailPanel>> = {}) {
+ const container = document.createElement("div");
+ container.className = "flex h-[700px] w-[900px]";
+ document.body.append(container);
+ const root = createRoot(container);
+ roots.push(root);
+ return act(async () =>
+ root.render(
+ <PullRequestDetailPanel
+ environmentId={threadRef.environmentId}
+ reference={detail}
+ context="page"
+ shortcutsEnabled={false}
+ getShortcutContext={shortcutContext}
+ {...props}
+ />,
+ ),
+ );
+}
+
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ useComposerDraftStore.setState({ draftsByThreadKey: {} });
+ newThread
+ .mockReset()
+ .mockResolvedValue({ draftId: newDraftId, threadId: ThreadId.make("new-thread") });
+ prepareThread.mockReset().mockResolvedValue({
+ _tag: "Success",
+ value: { branch: "feature", worktreePath: "/workspace/pr" },
+ });
+});
+afterEach(async () => {
+ for (const root of roots.splice(0)) await act(async () => root.unmount());
+ document.body.replaceChildren();
+ vi.unstubAllGlobals();
+});
+
+const surface = { projectId: detail.projectId, repository: detail.repository, number: 1 };
+const link = (number: number, source: ThreadPullRequestLink["source"]): ThreadPullRequestLink => ({
+ host: "github.com",
+ repository: detail.repository,
+ number,
+ url: `https://github.com/${detail.repository}/pull/${number}`,
+ source,
+ linkedAt: "2026-09-01T00:00:00Z",
+ snapshot: null,
+ stack: null,
+});
+const stackThread = {
+ projectId: detail.projectId,
+ pullRequests: [link(3, "manual"), link(2, "stack"), link(1, "stack")],
+ linkedPullRequest: { ...surface, number: 3, url: link(3, "manual").url },
+};
+const unrelatedThread = {
+ projectId: detail.projectId,
+ pullRequests: [link(9, "created")],
+ linkedPullRequest: { ...surface, number: 9, url: link(9, "created").url },
+};
+
+const tab = (name: string) => page.getByRole("button", { name, exact: true });
+
+async function runAction(action: string) {
+ if (action === "Add to agent") {
+ await tab("Code").click();
+ }
+ if (["Ask a question", "Explain this PR"].includes(action) || action.startsWith("Fix findings")) {
+ await page.getByRole("button", { name: "More pull request actions" }).click();
+ // Menu items carry a description under their label.
+ await page.getByRole("menuitem", { name: new RegExp(`^${action}`) }).click();
+ return;
+ }
+ await page.getByRole("button", { name: action, exact: true }).click();
+}
+
+describe.each([
+ ["own PR, a lower layer of the thread's stack", stackThread, threadRef],
+ ["another PR beside the current thread", unrelatedThread, threadRef],
+ ["PR beside an unsent draft", null, draftId],
+ ["standalone PR page", null, undefined],
+] as const)("%s", (_name, thread, target) => {
+ const context = thread ? pullRequestPanelContext(thread, surface) : "page";
+ const renderPanel = () =>
+ render({ context, ...(target ? { composerDraftTarget: target, threadRef } : {}) });
+
+ it(`${thread === stackThread ? "hides" : "offers"} the checkout`, async () => {
+ await renderPanel();
+ await expect.element(page.getByText("Test pull request").first()).toBeVisible();
+ expect(page.getByRole("button", { name: "Check out" }).elements()).toHaveLength(
+ thread === stackThread ? 0 : 1,
+ );
+ });
+
+ it.each([
+ "Resolve conflicts",
+ "Ask a question",
+ "Explain this PR",
+ "Fix findings in this thread",
+ "Fix check",
+ "Add to agent",
+ ])("%s writes to the correct composer", async (action) => {
+ if (target) useComposerDraftStore.getState().setPrompt(target, "Keep my draft");
+ await renderPanel();
+ await runAction(target ? action : action.replace("in this thread", "in a thread"));
+ const draft = () => useComposerDraftStore.getState().getComposerDraft(target ?? newDraftId);
+ await vi.waitFor(() => {
+ if (action === "Resolve conflicts")
+ expect(draft()?.prompt).toContain("resolve every conflict");
+ else if (action === "Fix check") expect(draft()?.prompt).toContain("Fix the failing check");
+ else if (action.startsWith("Fix findings"))
+ expect(draft()?.prompt).toContain("Fix the actionable findings");
+ else expect(draft()?.reviewComments?.length).toBeGreaterThan(0);
+ });
+ if (action === "Add to agent") {
+ expect(draft()?.prompt).toContain("Fix this line");
+ expect(draft()?.reviewComments).toEqual(
+ expect.arrayContaining([expect.objectContaining({ id: "note-1", diff: "+broken()" })]),
+ );
+ }
+ if (target) {
+ expect(draft()?.prompt).toContain("Keep my draft");
+ expect(newThread).not.toHaveBeenCalled();
+ expect(prepareThread).not.toHaveBeenCalled();
+ } else {
+ expect(newThread).toHaveBeenCalled();
+ }
+ });
+});
+
+it("folds the title only for the active tab's own scroller", async () => {
+ await render();
+ const title = page.getByRole("heading", { level: 1, name: "Test pull request" });
+ await expect.element(title).toBeVisible();
+ const titleFold = () => title.element().closest("[inert]") !== null;
+ const scrollTo = async (testId: string, top: number) => {
+ const scroller = page.getByTestId(testId).element() as HTMLElement;
+ await act(async () => {
+ scroller.scrollTop = top;
+ scroller.dispatchEvent(new Event("scroll"));
+ });
+ return scroller;
+ };
+
+ await scrollTo("nested-scroller", 600);
+ expect(titleFold()).toBe(false);
+
+ const summary = await scrollTo("summary-scroller", 600);
+ await vi.waitFor(() => expect(titleFold()).toBe(true));
+ // Folding the header keeps the content under the reader's eye.
+ expect(summary.scrollTop).toBeLessThan(600);
+
+ await scrollTo("summary-scroller", 0);
+ await vi.waitFor(() => expect(titleFold()).toBe(false));
+ await scrollTo("summary-scroller", 600);
+ await vi.waitFor(() => expect(titleFold()).toBe(true));
+
+ await tab("Code").click();
+ await expect.element(page.getByTestId("code-scroller")).toBeInTheDocument();
+ await vi.waitFor(() => expect(titleFold()).toBe(false));
+ await scrollTo("code-scroller", 600);
+ await vi.waitFor(() => expect(titleFold()).toBe(true));
+
+ await tab("Summary").click();
+ await vi.waitFor(() => expect(titleFold()).toBe(true));
+ await scrollTo("summary-scroller", 0);
+ await vi.waitFor(() => expect(titleFold()).toBe(false));
+ await tab("Code").click();
+ await vi.waitFor(() => expect(titleFold()).toBe(true));
+});
diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.test.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.test.tsx
deleted file mode 100644
index 17bff5d4b0e..00000000000
--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.test.tsx
+++ /dev/null
@@ -1,435 +0,0 @@
-import { SourceControlProviderKind } from "@t3tools/contracts";
-import {
- EnvironmentId,
- ProjectId,
- ThreadId,
- type ScopedThreadRef,
- type PullRequestDetailView,
- type ThreadPullRequestLink,
-} from "@t3tools/contracts";
-import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
-import { act, type ReactNode, type ReactElement, type ComponentProps } from "react";
-import { create, type ReactTestRenderer } from "react-test-renderer";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
-import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
-
-const { newThread, prepareThread, refresh, Wrapper, Trigger } = vi.hoisted(() => ({
- newThread: vi.fn(),
- prepareThread: vi.fn(),
- refresh: vi.fn(),
- Wrapper: ({ children }: { children?: ReactNode }) => children,
- Trigger: ({ children, render }: { children?: ReactNode; render?: ReactElement }) => (
- <>
- {render}
- {children}
- </>
- ),
-}));
-vi.mock("~/state/session", async (original) => ({
- ...(await original<typeof import("~/state/session")>()),
- useEnvironmentScope: () => true,
- readEnvironmentScope: () => true,
-}));
-vi.mock("@effect/atom-react", () => ({ useAtomValue: () => [] }));
-vi.mock("~/state/server", () => ({ primaryServerKeybindingsAtom: {} }));
-vi.mock("~/state/entities", () => ({ useProjects: () => [], useServerConfigs: () => new Map() }));
-vi.mock("~/state/environments", () => ({
- useEnvironments: () => ({ environments: [] }),
- usePrimaryEnvironmentId: () => EnvironmentId.make("env-1"),
-}));
-vi.mock("~/hooks/useSettings", () => ({
- useEnvironmentSettings: () => undefined,
- useClientSettings: (select: (settings: typeof DEFAULT_CLIENT_SETTINGS) => unknown) =>
- select(DEFAULT_CLIENT_SETTINGS),
-}));
-vi.mock("~/hooks/useLiveRefresh", () => ({ useLiveRefresh: () => {} }));
-vi.mock("~/hooks/useHandleNewThread", () => ({ useNewThreadHandler: () => newThread }));
-vi.mock("~/lib/sourceControlActions", () => ({
- usePreparePullRequestThreadAction: () => ({ run: prepareThread, isAllowed: true, error: null }),
-}));
-vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
-vi.mock("~/state/pullRequests", async (importOriginal) => ({
- ...(await importOriginal<typeof import("~/state/pullRequests")>()),
- pullRequestEnvironment: {
- detail: () => "detail",
- activity: () => "activity",
-
- reviewGuide: () => "review-guide",
- generateReviewGuide: { permissionAtom: () => "generate-review-guide" },
- },
- usePullRequestTurnRefresh: () => 0,
- useSharedPullRequestSummary: () => null,
-}));
-vi.mock("~/state/vcs", () => ({ vcsEnvironment: { listRefs: () => null } }));
-vi.mock("~/state/query", () => ({
- useEnvironmentQuery: (query: string) => ({
- data: query === "detail" ? detail : null,
- isPending: false,
- isSuccess: true,
- error: null,
- refresh,
- }),
-}));
-vi.mock("~/state/usePullRequestStack", () => ({
- usePullRequestStack: () => ({
- data: null,
- isSuccess: true,
- isPending: false,
- error: null,
- refresh,
- }),
-}));
-vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn(), update: vi.fn() } }));
-vi.mock("../ui/tooltip", () => ({
- TooltipProvider: Wrapper,
- Tooltip: Wrapper,
- TooltipTrigger: Trigger,
- TooltipPopup: () => null,
-}));
-vi.mock("../ui/menu", () => ({
- Menu: Wrapper,
- MenuPopup: Wrapper,
- MenuTrigger: Trigger,
- MenuItem: "button",
- MenuRadioGroup: Wrapper,
- MenuRadioItem: "button",
- MenuSeparator: () => null,
- MenuShortcut: () => null,
-}));
-vi.mock("../ui/alert-dialog", () => ({
- AlertDialog: () => null,
- AlertDialogPopup: Wrapper,
- AlertDialogHeader: Wrapper,
- AlertDialogTitle: Wrapper,
- AlertDialogDescription: Wrapper,
- AlertDialogFooter: Wrapper,
- AlertDialogClose: Wrapper,
-}));
-vi.mock("./PullRequestMarkdown", () => ({
- PullRequestMarkdownContext: Wrapper,
- PullRequestMarkdown: () => null,
-}));
-vi.mock("~/browser/useOpenLink", () => ({ useOpenLink: () => vi.fn() }));
-vi.mock("./PullRequestThreadLinks", () => ({ PullRequestThreadLinks: () => null }));
-vi.mock("./PullRequestSummaryTab", () => ({
- PullRequestSummaryTab: ({
- onFixFinding,
- scrollerRef,
- }: ComponentProps<typeof import("./PullRequestSummaryTab").PullRequestSummaryTab>) => (
- <div ref={scrollerRef} data-test-scroll="summary">
- <button
- onClick={() =>
- onFixFinding?.({
- kind: "check",
- check: { name: "Unit tests", status: "failure", description: "Test failed", url: null },
- })
- }
- >
- Fix check
- </button>
- </div>
- ),
-}));
-
-vi.mock("./PullRequestGuideTab", () => ({ PullRequestGuideTab: () => null }));
-vi.mock("./PullRequestCodeTab", () => ({
- default: ({
- onAddToAgentSelection,
- scrollerRef,
- }: ComponentProps<typeof import("./PullRequestCodeTab").default>) => (
- <div ref={scrollerRef} data-test-scroll="code">
- <button
- onClick={() =>
- onAddToAgentSelection?.({
- request: "Fix this line",
- comment: {
- id: "note-1",
- sectionId: "file:a.ts",
- sectionTitle: "a.ts",
- filePath: "a.ts",
- startIndex: 0,
- endIndex: 0,
- rangeLabel: "L1",
- text: "Please fix",
- diff: "+broken()",
- },
- })
- }
- >
- Add to agent
- </button>
- </div>
- ),
-}));
-
-import { PullRequestDetailPanel } from "./PullRequestDetailPanel";
-import { pullRequestPanelContext } from "./pullRequestDetail.logic";
-
-const detail: PullRequestDetailView = {
- provider: SourceControlProviderKind.make("github"),
- projectId: ProjectId.make("project"),
- projectTitle: "Project",
- workspaceRoot: "/workspace",
- repository: "owner/repo",
- number: 1,
- title: "Test pull request",
- body: "Original description",
- url: "https://github.com/owner/repo/pull/1",
- author: { login: "author", name: null, avatarUrl: null },
- viewer: "author",
- state: "open",
- isDraft: false,
- mergeability: "conflicting",
- additions: 1,
- deletions: 0,
- changedFiles: 1,
- headBranch: "feature",
- baseBranch: "main",
- createdAt: "2026-09-01T00:00:00Z",
- updatedAt: "2026-09-01T00:00:00Z",
- mergedAt: null,
- closedAt: null,
- reviewers: [],
- labels: [],
- checks: [{ name: "Unit tests", status: "success", description: null, url: null }],
- comments: [],
- commentCount: 0,
- commentsTruncated: false,
- reviewThreads: [],
- commits: [],
- mergeCapabilities: { merge: false, squash: false, rebase: false },
- capabilities: {
- diff: true,
- comment: false,
- search: true,
- actions: [],
- mergeMethods: [],
- review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
- reviewers: { request: false, listCandidates: false },
- edit: { changeRequest: true, comment: false },
- },
- viewerPermissions: {
- actions: [],
- comment: false,
- resolve: false,
- verdicts: [],
- requestReviewers: false,
- },
-};
-
-const threadRef: ScopedThreadRef = {
- environmentId: EnvironmentId.make("env-1"),
- threadId: ThreadId.make("thread-1"),
-};
-const draftId = DraftId.make("draft-1");
-const newDraftId = DraftId.make("new-draft");
-let renderer: ReactTestRenderer;
-
-beforeEach(() => {
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- vi.stubGlobal("window", { addEventListener: vi.fn(), removeEventListener: vi.fn() });
- useComposerDraftStore.setState({ draftsByThreadKey: {} });
- newThread
- .mockReset()
- .mockResolvedValue({ draftId: newDraftId, threadId: ThreadId.make("new-thread") });
- prepareThread.mockReset().mockResolvedValue({
- _tag: "Success",
- value: { branch: "feature", worktreePath: "/workspace/pr" },
- });
-});
-afterEach(() => {
- act(() => renderer?.unmount());
- vi.unstubAllGlobals();
-});
-
-async function click(label: string) {
- const button = renderer.root
- .findAllByType("button")
- .find(
- (node) =>
- node.props["aria-label"] === label ||
- node.findAll((child) => child.children.includes(label)).length > 0,
- );
- expect(button, label).toBeDefined();
- await act(async () =>
- button!.props.onClick({
- nativeEvent: new Event("click"),
- preventDefault() {},
- stopPropagation() {},
- }),
- );
-}
-
-const actions = [
- "Resolve conflicts",
- "Ask a question",
- "Explain this PR",
- "Fix findings in this thread",
- "Fix check",
- "Add to agent",
-];
-
-const surface = { projectId: detail.projectId, repository: detail.repository, number: 1 };
-const link = (number: number, source: ThreadPullRequestLink["source"]): ThreadPullRequestLink => ({
- host: "github.com",
- repository: detail.repository,
- number,
- url: `https://github.com/${detail.repository}/pull/${number}`,
- source,
- linkedAt: "2026-09-01T00:00:00Z",
- snapshot: null,
- stack: null,
-});
-const stackThread = {
- projectId: detail.projectId,
- pullRequests: [link(3, "manual"), link(2, "stack"), link(1, "stack")],
-
- linkedPullRequest: { ...surface, number: 3, url: link(3, "manual").url },
-};
-const unrelatedThread = {
- projectId: detail.projectId,
- pullRequests: [link(9, "created")],
- linkedPullRequest: { ...surface, number: 9, url: link(9, "created").url },
-};
-
-describe.each([
- ["own PR, a lower layer of the thread's stack", stackThread, threadRef],
- ["another PR beside the current thread", unrelatedThread, threadRef],
- ["PR beside an unsent draft", null, draftId],
- ["standalone PR page", null, undefined],
-] as const)("%s", (_name, thread, target) => {
- const context = thread ? pullRequestPanelContext(thread, surface) : "page";
-
- function render() {
- renderer = create(
- <PullRequestDetailPanel
- environmentId={threadRef.environmentId}
- reference={detail}
- context={context}
- {...(target ? { composerDraftTarget: target, threadRef } : {})}
- shortcutsEnabled={false}
- getShortcutContext={() => ({
- terminalFocus: false,
- terminalOpen: false,
- previewFocus: false,
- previewOpen: false,
- isWeb: true,
- isDesktop: false,
- })}
- />,
- );
- }
-
- it(`${thread === stackThread ? "hides" : "offers"} the checkout`, async () => {
- await act(async () => render());
- const checkout = renderer.root
- .findAllByType("button")
- .filter((node) => node.props["aria-label"] === "Check out");
- expect(checkout).toHaveLength(thread === stackThread ? 0 : 1);
- });
-
- it.each(actions)("%s writes to the correct composer", async (action) => {
- if (target) useComposerDraftStore.getState().setPrompt(target, "Keep my draft");
- await act(async () => render());
- if (action === "Add to agent") await click("Code");
- await click(target ? action : action.replace("in this thread", "in a thread"));
- const draft = useComposerDraftStore.getState().getComposerDraft(target ?? newDraftId);
- if (action === "Resolve conflicts") expect(draft?.prompt).toContain("resolve every conflict");
- else if (action === "Fix check") expect(draft?.prompt).toContain("Fix the failing check");
- else if (action.startsWith("Fix findings"))
- expect(draft?.prompt).toContain("Fix the actionable findings");
- else expect(draft?.reviewComments?.length).toBeGreaterThan(0);
- if (action === "Add to agent") {
- expect(draft?.prompt).toContain("Fix this line");
- expect(draft?.reviewComments).toEqual(
- expect.arrayContaining([expect.objectContaining({ id: "note-1", diff: "+broken()" })]),
- );
- }
- if (target) {
- expect(draft?.prompt).toContain("Keep my draft");
- expect(newThread).not.toHaveBeenCalled();
- expect(prepareThread).not.toHaveBeenCalled();
- } else {
- expect(newThread).toHaveBeenCalled();
- }
- });
-});
-
-it("changes the title only for the active tab's main scroller", async () => {
- const scrollers = new Map<string, { scrollTop: number; scrollHeight: number }>();
- await act(async () => {
- renderer = create(
- <PullRequestDetailPanel
- environmentId={threadRef.environmentId}
- reference={detail}
- context="page"
- shortcutsEnabled={false}
- getShortcutContext={() => ({
- terminalFocus: false,
- terminalOpen: false,
- previewFocus: false,
- previewOpen: false,
- isWeb: true,
- isDesktop: false,
- })}
- />,
- {
- createNodeMock: (element) => {
- const props = element.props as Record<string, unknown>;
- const name = props["data-test-scroll"] as string | undefined;
- if (name) {
- const scroller = { scrollTop: 0, scrollHeight: 300 };
- scrollers.set(name, scroller);
- return scroller;
- }
- return { scrollHeight: props.inert === false ? 100 : 20 };
- },
- },
- );
- });
-
- const mainScroll = renderer.root.findByProps({
- className: "relative flex min-h-0 flex-1 flex-col overflow-hidden",
- });
- const titleFold = () => {
- let node = renderer.root.findByType("h1");
- while (typeof node.props.inert !== "boolean") node = node.parent!;
- return node;
- };
- const summary = scrollers.get("summary")!;
- const nested = { scrollTop: 200 };
- await act(async () => mainScroll.props.onScrollCapture({ target: nested }));
- expect(titleFold().props.inert).toBe(false);
- summary.scrollTop = 180;
- nested.scrollTop = 0;
- await act(async () => {
- mainScroll.props.onScrollCapture({ target: summary });
- mainScroll.props.onScrollCapture({ target: nested });
- });
- expect(titleFold().props.inert).toBe(true);
- expect(summary.scrollTop).toBe(100);
- expect(nested.scrollTop).toBe(0);
-
- await act(async () => mainScroll.props.onScrollCapture({ target: { scrollTop: 0 } }));
- expect(titleFold().props.inert).toBe(true);
- summary.scrollTop = 0;
- await act(async () => mainScroll.props.onScrollCapture({ target: summary }));
- expect(titleFold().props.inert).toBe(false);
-
- await click("Code");
- const code = scrollers.get("code")!;
- summary.scrollTop = 180;
- await act(async () => mainScroll.props.onScrollCapture({ target: summary }));
- expect(titleFold().props.inert).toBe(false);
- code.scrollTop = 180;
- await act(async () => mainScroll.props.onScrollCapture({ target: code }));
- expect(titleFold().props.inert).toBe(true);
- expect(code.scrollTop).toBe(100);
- await click("Summary");
- expect(titleFold().props.inert).toBe(false);
- await click("Code");
- expect(titleFold().props.inert).toBe(true);
- code.scrollTop = 0;
- await act(async () => mainScroll.props.onScrollCapture({ target: code }));
- expect(titleFold().props.inert).toBe(false);
-});
diff --git a/apps/web/src/components/settings/AcpRegistrySearchStep.browser.test.tsx b/apps/web/src/components/settings/AcpRegistrySearchStep.browser.test.tsx
new file mode 100644
index 00000000000..c4e3acf4a92
--- /dev/null
+++ b/apps/web/src/components/settings/AcpRegistrySearchStep.browser.test.tsx
@@ -0,0 +1,260 @@
+import { EnvironmentId, ProviderDriverKind, type AcpRegistrySearchAgent } from "@t3tools/contracts";
+import * as Cause from "effect/Cause";
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
+import { page, userEvent } from "vite-plus/test/browser";
+
+const state = vi.hoisted(() => ({
+ result: null as { readonly agents: ReadonlyArray<AcpRegistrySearchAgent> } | null,
+ error: null as string | null,
+ isPending: false,
+ canManage: true,
+ refresh: vi.fn(),
+ search: vi.fn(),
+ prepare: vi.fn(),
+}));
+
+vi.mock(import("../../state/server"), async (original) => {
+ const actual = await original();
+ return {
+ ...actual,
+ serverEnvironment: {
+ ...actual.serverEnvironment,
+ searchAcpRegistry: ((input: unknown) => {
+ state.search(input);
+ return "search";
+ }) as never,
+ },
+ };
+});
+vi.mock(import("../../state/session"), async (original) => ({
+ ...(await original()),
+ useEnvironmentScope: () => state.canManage,
+ readEnvironmentScope: () => state.canManage,
+}));
+vi.mock(import("../../state/query"), async (original) => ({
+ ...(await original()),
+ useEnvironmentQuery: (() => ({
+ data: state.result,
+ error: state.error,
+ isPending: state.isPending,
+ refresh: state.refresh,
+ })) as never,
+}));
+vi.mock(import("../../state/use-atom-command"), async (original) => ({
+ ...(await original()),
+ useAtomCommand: (() => state.prepare) as never,
+}));
+
+import { AcpRegistrySearchStep } from "./AcpRegistrySearchStep";
+
+const environmentId = EnvironmentId.make("remote-device");
+const gemini: AcpRegistrySearchAgent = {
+ id: "gemini",
+ name: "Gemini CLI",
+ version: "1.2.3",
+ description: "Google's agent",
+ authors: ["Google <[email protected]>", "Contributor"],
+ license: "Apache-2.0",
+ website: "https://example.com/docs",
+ repository: "https://example.com/source",
+ icon: null,
+ distribution: "npx",
+ integrity: "registry",
+};
+
+const roots: Root[] = [];
+let root: Root;
+
+function render(options?: {
+ readonly configured?: boolean;
+ readonly onPrepared?: (agent: AcpRegistrySearchAgent) => void;
+}) {
+ return act(async () =>
+ root.render(
+ <AcpRegistrySearchStep
+ environmentId={environmentId}
+ providerInstances={
+ options?.configured
+ ? {
+ acpRegistry_gemini: {
+ driver: ProviderDriverKind.make("acpRegistry"),
+ config: { agentId: "gemini" },
+ },
+ }
+ : {}
+ }
+ onPrepared={options?.onPrepared ?? vi.fn()}
+ onManualConfiguration={vi.fn()}
+ />,
+ ),
+ );
+}
+
+const searchBox = () => page.getByRole("searchbox", { name: "Search ACP Registry" });
+const lastQuery = () =>
+ (state.search.mock.lastCall?.[0] as { input: { query: string } } | undefined)?.input.query;
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+
+beforeEach(() => {
+ state.canManage = true;
+ state.result = null;
+ state.error = null;
+ state.isPending = false;
+ state.refresh.mockReset();
+ state.search.mockReset();
+ state.prepare.mockReset().mockResolvedValue({
+ _tag: "Success",
+ value: { agentId: "gemini", version: "1.2.3", distribution: "npx", prepared: true },
+ });
+ const container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ roots.push(root);
+});
+
+afterEach(async () => {
+ vi.useRealTimers();
+ for (const mounted of roots.splice(0)) await act(async () => mounted.unmount());
+ document.body.replaceChildren();
+});
+
+it("loads the catalog immediately and searches only after typing settles", async () => {
+ await render();
+ expect(state.search).toHaveBeenLastCalledWith({ environmentId, input: { query: "" } });
+
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+ await userEvent.fill(searchBox(), " Gemini ");
+ await act(async () => vi.advanceTimersByTime(200));
+ await userEvent.fill(searchBox(), " Gemini CLI ");
+ await act(async () => vi.advanceTimersByTime(299));
+ expect(lastQuery()).toBe("");
+ await act(async () => vi.advanceTimersByTime(1));
+ expect(lastQuery()).toBe("Gemini CLI");
+
+ await userEvent.clear(searchBox());
+ await act(async () => vi.advanceTimersByTime(300));
+ expect(lastQuery()).toBe("");
+});
+
+it("shows the loading, error, and empty states", async () => {
+ state.isPending = true;
+ await render();
+ await expect.element(page.getByText("Searching the registry...")).toBeVisible();
+
+ state.isPending = false;
+ state.error = "Registry unavailable.";
+ await render();
+ await expect.element(page.getByText("Registry unavailable.")).toBeVisible();
+
+ state.error = null;
+ state.result = { agents: [] };
+ await render();
+ await expect.element(page.getByText("No compatible agents found")).toBeVisible();
+});
+
+it("submits a typed query at once and refreshes when the same query is submitted again", async () => {
+ await render();
+ await userEvent.fill(searchBox(), "Codex");
+ await userEvent.keyboard("{Enter}");
+ expect(lastQuery()).toBe("Codex");
+ expect(state.refresh).not.toHaveBeenCalled();
+
+ state.result = { agents: [gemini] };
+ await render();
+ await userEvent.click(searchBox());
+ await userEvent.keyboard("{Enter}");
+ expect(state.refresh).toHaveBeenCalledOnce();
+
+ state.isPending = true;
+ await render();
+ await expect
+ .element(page.getByRole("status").filter({ hasText: "Refreshing ACP Registry results." }))
+ .toBeInTheDocument();
+ await expect.element(page.getByRole("button", { name: "Add Gemini CLI" })).toBeVisible();
+});
+
+it("prepares a result before handing it back to the wizard", async () => {
+ state.prepare.mockResolvedValueOnce({
+ _tag: "Success",
+ value: { agentId: "gemini", version: "2.0.0", distribution: "binary", prepared: true },
+ });
+ state.result = { agents: [gemini] };
+ const onPrepared = vi.fn();
+ await render({ onPrepared });
+
+ await page.getByRole("button", { name: "Add Gemini CLI" }).click();
+
+ expect(state.prepare).toHaveBeenCalledWith({ environmentId, input: { agentId: "gemini" } });
+ await vi.waitFor(() =>
+ expect(onPrepared).toHaveBeenCalledWith({
+ ...gemini,
+ version: "2.0.0",
+ distribution: "binary",
+ }),
+ );
+});
+
+it("shows progress, locks the step while an agent prepares, and reports a failure", async () => {
+ const pending = deferred<unknown>();
+ state.prepare.mockReturnValueOnce(pending.promise);
+ state.result = { agents: [{ ...gemini, distribution: "binary" }] };
+ await render();
+
+ await page.getByRole("button", { name: "Add Gemini CLI" }).click();
+ await expect.element(page.getByRole("button", { name: "Downloading Gemini CLI" })).toBeDisabled();
+ await expect.element(searchBox()).toBeDisabled();
+
+ await act(async () =>
+ pending.resolve({ _tag: "Failure", cause: Cause.fail(new Error("Registry download failed.")) }),
+ );
+ await expect.element(page.getByText("Registry download failed.")).toBeVisible();
+ await expect.element(page.getByRole("button", { name: "Add Gemini CLI" })).toBeEnabled();
+});
+
+it("rechecks the grant before preparing an agent", async () => {
+ state.result = { agents: [gemini] };
+ const onPrepared = vi.fn();
+ await render({ onPrepared });
+ state.canManage = false;
+
+ await page.getByRole("button", { name: "Add Gemini CLI" }).click();
+
+ expect(state.prepare).not.toHaveBeenCalled();
+ expect(onPrepared).not.toHaveBeenCalled();
+});
+
+it("ignores prepare completion after unmount", async () => {
+ const pending = deferred<unknown>();
+ state.prepare.mockReturnValueOnce(pending.promise);
+ state.result = { agents: [gemini] };
+ const onPrepared = vi.fn();
+ await render({ onPrepared });
+
+ await page.getByRole("button", { name: "Add Gemini CLI" }).click();
+ await act(async () => root.unmount());
+ await act(async () =>
+ pending.resolve({
+ _tag: "Success",
+ value: { agentId: "gemini", version: "1.2.3", distribution: "npx", prepared: true },
+ }),
+ );
+
+ expect(onPrepared).not.toHaveBeenCalled();
+});
+
+it("shows an existing registry configuration as already added", async () => {
+ state.result = { agents: [gemini] };
+ await render({ configured: true });
+ await expect
+ .element(page.getByRole("button", { name: "Already added Gemini CLI" }))
+ .toBeDisabled();
+});
diff --git a/apps/web/src/components/settings/AcpRegistrySearchStep.test.tsx b/apps/web/src/components/settings/AcpRegistrySearchStep.test.tsx
deleted file mode 100644
index 3524d784177..00000000000
--- a/apps/web/src/components/settings/AcpRegistrySearchStep.test.tsx
+++ /dev/null
@@ -1,359 +0,0 @@
-import { isValidElement, type ReactElement } from "react";
-import { EnvironmentId, ProviderDriverKind, type AcpRegistrySearchAgent } from "@t3tools/contracts";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
-
-import { visitElements } from "../../test/reactElementTree";
-import { reactHookHarness as hooks } from "../../test/reactHookHarness";
-
-const atoms = vi.hoisted(() => ({
- search: Symbol("acp-search"),
- prepare: Symbol("acp-prepare"),
-}));
-
-const state = vi.hoisted(() => ({
- result: null as { readonly agents: ReadonlyArray<AcpRegistrySearchAgent> } | null,
- error: null as string | null,
- isPending: false,
- canManage: true,
- refresh: vi.fn(),
- search: vi.fn(() => atoms.search),
- prepare: vi.fn(),
-}));
-
-const lifecycle = vi.hoisted(() => ({
- cleanups: [] as Array<() => void>,
-}));
-
-vi.mock("react", async (importOriginal) => {
- const actual = await importOriginal<typeof import("react")>();
- const { reactHookHarness } = await import("../../test/reactHookHarness");
- return {
- ...actual,
- useEffect: (effect: () => void | (() => void)) => {
- const cleanup = effect();
- if (cleanup) lifecycle.cleanups.push(cleanup);
- },
- useRef: reactHookHarness.useRef,
- useLayoutEffect: (effect: () => void | (() => void)) => {
- const cleanup = effect();
- if (cleanup) lifecycle.cleanups.push(cleanup);
- },
- useState: reactHookHarness.useState,
- };
-});
-
-vi.mock("react/compiler-runtime", async () => {
- const { reactHookHarness } = await import("../../test/reactHookHarness");
- return { c: reactHookHarness.useMemoCache };
-});
-
-vi.mock("../../state/server", () => ({
- serverEnvironment: {
- searchAcpRegistry: state.search,
- prepareAcpRegistryAgent: atoms.prepare,
- },
-}));
-
-vi.mock("../../state/session", () => ({
- useEnvironmentScope: () => state.canManage,
- readEnvironmentScope: () => state.canManage,
-}));
-
-vi.mock("../../state/query", () => ({
- useEnvironmentQuery: () => ({
- data: state.result,
- error: state.error,
- isPending: state.isPending,
- refresh: state.refresh,
- }),
-}));
-
-vi.mock("../../state/use-atom-command", () => ({
- useAtomCommand: () => state.prepare,
-}));
-
-vi.mock("@t3tools/client-runtime/state/runtime", () => ({
- isAtomCommandInterrupted: () => false,
- squashAtomCommandFailure: () => new Error("Prepare failed."),
-}));
-
-import { AcpRegistrySearchStep } from "./AcpRegistrySearchStep";
-
-const environmentId = EnvironmentId.make("remote-device");
-const gemini: AcpRegistrySearchAgent = {
- id: "gemini",
- name: "Gemini CLI",
- version: "1.2.3",
- description: "Google's agent",
- authors: ["Google <[email protected]>", "Contributor"],
- license: "Apache-2.0",
- website: "https://example.com/docs",
- repository: "https://example.com/source",
- icon: "https://example.com/icon.png",
- distribution: "npx",
- integrity: "registry",
-};
-
-function render(options?: {
- readonly configured?: boolean;
- readonly onPrepared?: (agent: AcpRegistrySearchAgent) => void;
-}): ReactElement<Record<string, unknown>> {
- hooks.beginRender();
- return AcpRegistrySearchStep({
- environmentId,
- providerInstances: options?.configured
- ? {
- acpRegistry_gemini: {
- driver: ProviderDriverKind.make("acpRegistry"),
- config: { agentId: "gemini" },
- },
- }
- : {},
- onPrepared: options?.onPrepared ?? vi.fn(),
- onManualConfiguration: vi.fn(),
- }) as ReactElement<Record<string, unknown>>;
-}
-
-function findByAriaLabel(
- tree: ReactElement<Record<string, unknown>>,
- label: string,
-): ReactElement<Record<string, unknown>> {
- const found = visitElements(expandRows(tree), (element) => element.props["aria-label"] === label);
- expect(found).not.toBeNull();
- return found!;
-}
-
-// The harness calls components as plain functions, so result rows stay
-// unexpanded elements until rendered here.
-function expandRows(node: unknown): unknown {
- if (Array.isArray(node)) return node.map(expandRows);
- if (!isValidElement<Record<string, unknown>>(node)) return node;
- if (typeof node.type === "function" && node.type.name === "AcpRegistryAgentRow") {
- return expandRows((node.type as (props: unknown) => unknown)(node.props));
- }
- const props = Object.fromEntries(
- Object.entries(node.props).map(([key, value]) => [key, expandRows(value)]),
- );
- return { ...node, props };
-}
-
-describe("AcpRegistrySearchStep", () => {
- beforeEach(() => {
- state.canManage = true;
- vi.useFakeTimers();
- hooks.reset();
- state.result = null;
- state.error = null;
- state.isPending = false;
- state.refresh.mockReset();
- state.search.mockClear();
- state.prepare.mockReset().mockResolvedValue({
- _tag: "Success",
- value: { agentId: "gemini", version: "1.2.3", distribution: "npx", prepared: true },
- });
- lifecycle.cleanups = [];
- vi.stubGlobal(
- "fetch",
- vi.fn(() => new Promise<Response>(() => {})),
- );
- });
- afterEach(() => {
- for (const cleanup of lifecycle.cleanups) cleanup();
- vi.useRealTimers();
- });
-
- it("loads the catalog immediately and searches only after typing settles", () => {
- const initial = render();
- expect(state.search).toHaveBeenLastCalledWith({
- environmentId,
- input: { query: "" },
- });
-
- const input = findByAriaLabel(initial, "Search ACP Registry");
- expect(input.props.size).toBe("sm");
- (input.props.onChange as ((event: { currentTarget: { value: string } }) => void) | undefined)?.(
- { currentTarget: { value: " Gemini " } },
- );
- vi.advanceTimersByTime(200);
- render();
- expect(state.search).toHaveBeenLastCalledWith({ environmentId, input: { query: "" } });
- (input.props.onChange as ((event: { currentTarget: { value: string } }) => void) | undefined)?.(
- {
- currentTarget: { value: " Gemini CLI " },
- },
- );
- vi.advanceTimersByTime(299);
- render();
- expect(state.search).toHaveBeenLastCalledWith({ environmentId, input: { query: "" } });
- vi.advanceTimersByTime(1);
- render();
- expect(state.search).toHaveBeenLastCalledWith({
- environmentId,
- input: { query: "Gemini CLI" },
- });
- (input.props.onChange as ((event: { currentTarget: { value: string } }) => void) | undefined)?.(
- {
- currentTarget: { value: "" },
- },
- );
- vi.advanceTimersByTime(300);
- render();
- expect(state.search).toHaveBeenLastCalledWith({ environmentId, input: { query: "" } });
- });
-
- it("renders deterministic loading, error, and empty states", () => {
- state.isPending = true;
- expect(
- visitElements(render(), (element) => element.props.children === "Searching the registry..."),
- ).not.toBeNull();
-
- state.isPending = false;
- state.error = "Registry unavailable.";
- expect(
- visitElements(render(), (element) => element.props.children === "Registry unavailable."),
- ).not.toBeNull();
-
- state.error = null;
- state.result = { agents: [] };
- expect(
- visitElements(render(), (element) => element.props.children === "No compatible agents found"),
- ).not.toBeNull();
- });
-
- it("keeps same-query refreshes visible and announced while retaining results", () => {
- const first = render();
- const input = findByAriaLabel(first, "Search ACP Registry");
- (input.props.onChange as ((event: { currentTarget: { value: string } }) => void) | undefined)?.(
- {
- currentTarget: { value: "Codex" },
- },
- );
- const draft = render();
- const searchForm = visitElements(draft, (element) => element.type === "form");
- (searchForm?.props.onSubmit as ((event: { preventDefault: () => void }) => void) | undefined)?.(
- {
- preventDefault: vi.fn(),
- },
- );
-
- state.result = { agents: [gemini] };
- const resultTree = render();
- expect(state.search).toHaveBeenCalledWith({
- environmentId,
- input: { query: "Codex" },
- });
- const form = visitElements(resultTree, (element) => element.type === "form");
- (form?.props.onSubmit as ((event: { preventDefault: () => void }) => void) | undefined)?.({
- preventDefault: vi.fn(),
- });
- expect(state.refresh).toHaveBeenCalledOnce();
-
- state.isPending = true;
- const refreshingTree = render();
- expect(
- visitElements(
- refreshingTree,
- (element) =>
- element.props.role === "status" &&
- element.props.children === "Refreshing ACP Registry results.",
- ),
- ).not.toBeNull();
- expect(findByAriaLabel(refreshingTree, "Add Gemini CLI")).not.toBeNull();
- });
-
- it("prepares a result before handing it back to the wizard", async () => {
- state.prepare.mockResolvedValueOnce({
- _tag: "Success",
- value: { agentId: "gemini", version: "2.0.0", distribution: "binary", prepared: true },
- });
- state.result = { agents: [gemini] };
- const onPrepared = vi.fn();
- const tree = render({ onPrepared });
-
- const add = findByAriaLabel(tree, "Add Gemini CLI");
- (add.props.onClick as (() => void) | undefined)?.();
- await Promise.resolve();
- await Promise.resolve();
-
- expect(state.prepare).toHaveBeenCalledWith({
- environmentId,
- input: { agentId: "gemini" },
- });
- expect(onPrepared).toHaveBeenCalledWith({
- ...gemini,
- version: "2.0.0",
- distribution: "binary",
- });
- });
-
- it("rechecks the grant before preparing an agent", async () => {
- state.result = { agents: [gemini] };
- const onPrepared = vi.fn();
- const add = findByAriaLabel(render({ onPrepared }), "Add Gemini CLI");
- state.canManage = false;
- await (add.props.onClick as () => void)();
- expect(state.prepare).not.toHaveBeenCalled();
- expect(onPrepared).not.toHaveBeenCalled();
- });
-
- it("ignores a stale prepare completion", async () => {
- let resolveFirst!: (value: { readonly _tag: "Success"; readonly value: unknown }) => void;
- let resolveSecond!: (value: { readonly _tag: "Success"; readonly value: unknown }) => void;
- state.prepare
- .mockImplementationOnce(
- () =>
- new Promise((resolve) => {
- resolveFirst = resolve;
- }),
- )
- .mockImplementationOnce(
- () =>
- new Promise((resolve) => {
- resolveSecond = resolve;
- }),
- );
- state.result = { agents: [gemini] };
- const onPrepared = vi.fn();
- const tree = render({ onPrepared });
- const add = findByAriaLabel(tree, "Add Gemini CLI");
-
- (add.props.onClick as (() => void) | undefined)?.();
- (add.props.onClick as (() => void) | undefined)?.();
- resolveFirst({ _tag: "Success", value: {} });
- await Promise.resolve();
- expect(onPrepared).not.toHaveBeenCalled();
-
- resolveSecond({ _tag: "Success", value: {} });
- await Promise.resolve();
- expect(onPrepared).toHaveBeenCalledOnce();
- });
-
- it("ignores prepare completion after unmount", async () => {
- let resolvePrepare!: (value: { readonly _tag: "Success"; readonly value: unknown }) => void;
- state.prepare.mockImplementationOnce(
- () =>
- new Promise((resolve) => {
- resolvePrepare = resolve;
- }),
- );
- state.result = { agents: [gemini] };
- const onPrepared = vi.fn();
- const tree = render({ onPrepared });
-
- const add = findByAriaLabel(tree, "Add Gemini CLI");
- (add.props.onClick as (() => void) | undefined)?.();
- for (const cleanup of lifecycle.cleanups) cleanup();
- resolvePrepare({ _tag: "Success", value: {} });
- await Promise.resolve();
-
- expect(onPrepared).not.toHaveBeenCalled();
- });
-
- it("renders existing registry configuration as already added", () => {
- state.result = { agents: [gemini] };
- const tree = render({ configured: true });
- const added = findByAriaLabel(tree, "Already added Gemini CLI");
-
- expect(added.props.disabled).toBe(true);
- });
-});