Open History to see the last commit
1import {
2 EnvironmentId,
3 GitCommandError,
4 GitManagerError,
5 ProjectId,
6 SourceControlProviderKind,
7 ThreadId,
8 type PullRequestDetailView,
9 type ScopedThreadRef,
10 type ThreadPullRequestLink,
11} from "@t3tools/contracts";
12import * as Cause from "effect/Cause";
13import { act, type ComponentProps } from "react";
14import { createRoot, type Root } from "react-dom/client";
15import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
16import { page } from "vite-plus/test/browser";
17import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
18
19import "~/index.css";
20
21const { newThread, prepareThread, refresh, addToast, updateToast, checkoutState } = vi.hoisted(
22 () => ({
23 newThread: vi.fn(),
24 prepareThread: vi.fn(),
25 refresh: vi.fn(),
26 addToast: vi.fn(),
27 updateToast: vi.fn(),
28 checkoutState: { error: null as Error | null },
29 }),
30);
31
32vi.mock(import("~/state/session"), async (original) => ({
33 ...(await original()),
34 useEnvironmentScope: () => true,
35 readEnvironmentScope: () => true,
36}));
37vi.mock(import("~/hooks/useSettings"), async (original) => ({
38 ...(await original()),
39 useEnvironmentSettings: (() => undefined) as never,
40}));
41vi.mock(import("~/hooks/useHandleNewThread"), async (original) => ({
42 ...(await original()),
43 useNewThreadHandler: (() => newThread) as never,
44}));
45vi.mock(import("~/lib/sourceControlActions"), async (original) => ({
46 ...(await original()),
47 usePreparePullRequestThreadAction: (() => ({
48 run: prepareThread,
49 isAllowed: true,
50 error: checkoutState.error,
51 })) as never,
52}));
53vi.mock(import("~/state/use-atom-command"), async (original) => ({
54 ...(await original()),
55 useAtomCommand: (() => vi.fn()) as never,
56}));
57vi.mock(import("~/state/pullRequests"), async (original) => {
58 const actual = await original();
59 const { Atom } = await import("effect/reactivity");
60 const cannotWriteGuides = Atom.make(false);
61 return {
62 ...actual,
63 pullRequestEnvironment: {
64 ...actual.pullRequestEnvironment,
65 detail: (() => "detail") as never,
66 activity: (() => "activity") as never,
67 reviewGuide: (() => "review-guide") as never,
68 generateReviewGuide: {
69 ...actual.pullRequestEnvironment.generateReviewGuide,
70 permissionAtom: () => cannotWriteGuides,
71 },
72 },
73 };
74});
75vi.mock(import("~/state/query"), async (original) => ({
76 ...(await original()),
77 useEnvironmentQuery: ((query: unknown) => ({
78 data: query === "detail" ? detail : null,
79 dataUpdatedAt: 0,
80 failure: null,
81 isPending: false,
82 isSuccess: true,
83 error: null,
84 refresh,
85 })) as never,
86}));
87vi.mock(import("~/state/usePullRequestStack"), async (original) => ({
88 ...(await original()),
89 usePullRequestStack: (() => ({
90 data: null,
91 isSuccess: true,
92 isPending: false,
93 error: null,
94 refresh,
95 })) as never,
96}));
97// The real tabs load diffs, markdown and checks from the environment; these stand-ins
98// expose the actions they hand back to the panel and a tall scroller.
99vi.mock(import("./PullRequestSummaryTab"), async (original) => ({
100 ...(await original()),
101 PullRequestSummaryTab: (({
102 onFixFinding,
103 scrollerRef,
104 }: ComponentProps<typeof import("./PullRequestSummaryTab").PullRequestSummaryTab>) => (
105 <div ref={scrollerRef} data-testid="summary-scroller" className="h-full overflow-y-auto">
106 <button
107 type="button"
108 onClick={() =>
109 onFixFinding?.({
110 kind: "check",
111 check: { name: "Unit tests", status: "failure", description: "Test failed", url: null },
112 })
113 }
114 >
115 Fix check
116 </button>
117 <div data-testid="nested-scroller" className="h-40 overflow-y-auto">
118 <div className="h-[2000px]" />
119 </div>
120 <div className="h-[3000px]" />
121 </div>
122 )) as never,
123}));
124vi.mock(import("./PullRequestCodeTab"), async (original) => ({
125 ...(await original()),
126 default: (({
127 onAddToAgentSelection,
128 scrollerRef,
129 }: ComponentProps<typeof import("./PullRequestCodeTab").default>) => (
130 <div ref={scrollerRef} data-testid="code-scroller" className="h-full overflow-y-auto">
131 <button
132 type="button"
133 onClick={() =>
134 onAddToAgentSelection?.({
135 request: "Fix this line",
136 comment: {
137 id: "note-1",
138 sectionId: "file:a.ts",
139 sectionTitle: "a.ts",
140 filePath: "a.ts",
141 startIndex: 0,
142 endIndex: 0,
143 rangeLabel: "L1",
144 text: "Please fix",
145 diff: "+broken()",
146 },
147 })
148 }
149 >
150 Add to agent
151 </button>
152 <div className="h-[3000px]" />
153 </div>
154 )) as never,
155}));
156
157vi.mock(import("../ui/toast"), async (original) => {
158 const actual = await original();
159 return {
160 ...actual,
161 toastManager: { ...actual.toastManager, add: addToast, update: updateToast } as never,
162 };
163});
164
165import { PullRequestDetailPanel } from "./PullRequestDetailPanel";
166import { pullRequestPanelContext } from "./pullRequestDetail.logic";
167
168const 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
220const threadRef: ScopedThreadRef = {
221 environmentId: EnvironmentId.make("env-1"),
222 threadId: ThreadId.make("thread-1"),
223};
224const draftId = DraftId.make("draft-1");
225const newDraftId = DraftId.make("new-draft");
226const shortcutContext = () => ({
227 terminalFocus: false,
228 terminalOpen: false,
229 previewFocus: false,
230 previewOpen: false,
231 isWeb: true,
232 isDesktop: false,
233});
234
235const roots: Root[] = [];
236
237function render(props: Partial<ComponentProps<typeof PullRequestDetailPanel>> = {}) {
238 const container = document.createElement("div");
239 container.className = "flex h-[700px] w-[900px]";
240 document.body.append(container);
241 const root = createRoot(container);
242 roots.push(root);
243 return act(async () =>
244 root.render(
245 <PullRequestDetailPanel
246 environmentId={threadRef.environmentId}
247 reference={detail}
248 context="page"
249 shortcutsEnabled={false}
250 getShortcutContext={shortcutContext}
251 {...props}
252 />,
253 ),
254 );
255}
256
257beforeEach(() => {
258 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
259 useComposerDraftStore.setState({ draftsByThreadKey: {} });
260 newThread
261 .mockReset()
262 .mockResolvedValue({ draftId: newDraftId, threadId: ThreadId.make("new-thread") });
263 addToast.mockReset().mockReturnValue("checkout-toast");
264 updateToast.mockReset();
265 checkoutState.error = null;
266 prepareThread.mockReset().mockResolvedValue({
267 _tag: "Success",
268 value: { branch: "feature", worktreePath: "/workspace/pr" },
269 });
270});
271afterEach(async () => {
272 for (const root of roots.splice(0)) await act(async () => root.unmount());
273 document.body.replaceChildren();
274 vi.unstubAllGlobals();
275});
276
277const surface = { projectId: detail.projectId, repository: detail.repository, number: 1 };
278const link = (number: number, source: ThreadPullRequestLink["source"]): ThreadPullRequestLink => ({
279 host: "github.com",
280 repository: detail.repository,
281 number,
282 url: `https://github.com/${detail.repository}/pull/${number}`,
283 source,
284 linkedAt: "2026-09-01T00:00:00Z",
285 snapshot: null,
286 stack: null,
287});
288const stackThread = {
289 projectId: detail.projectId,
290 pullRequests: [link(3, "manual"), link(2, "stack"), link(1, "stack")],
291 linkedPullRequest: { ...surface, number: 3, url: link(3, "manual").url },
292};
293const unrelatedThread = {
294 projectId: detail.projectId,
295 pullRequests: [link(9, "created")],
296 linkedPullRequest: { ...surface, number: 9, url: link(9, "created").url },
297};
298
299const tab = (name: string) => page.getByRole("button", { name, exact: true });
300
301async function runAction(action: string) {
302 if (action === "Add to agent") {
303 await tab("Code").click();
304 }
305 if (["Ask a question", "Explain this PR"].includes(action) || action.startsWith("Fix findings")) {
306 await page.getByRole("button", { name: "More pull request actions" }).click();
307 // Menu items carry a description under their label.
308 await page.getByRole("menuitem", { name: new RegExp(`^${action}`) }).click();
309 return;
310 }
311 await page.getByRole("button", { name: action, exact: true }).click();
312}
313
314describe.each([
315 ["own PR, a lower layer of the thread's stack", stackThread, threadRef],
316 ["another PR beside the current thread", unrelatedThread, threadRef],
317 ["PR beside an unsent draft", null, draftId],
318 ["standalone PR page", null, undefined],
319] as const)("%s", (_name, thread, target) => {
320 const context = thread ? pullRequestPanelContext(thread, surface) : "page";
321 const renderPanel = () =>
322 render({ context, ...(target ? { composerDraftTarget: target, threadRef } : {}) });
323
324 it(`${thread === stackThread ? "hides" : "offers"} the checkout`, async () => {
325 await renderPanel();
326 await expect.element(page.getByText("Test pull request").first()).toBeVisible();
327 expect(page.getByRole("button", { name: "Check out" }).elements()).toHaveLength(
328 thread === stackThread ? 0 : 1,
329 );
330 });
331
332 it.each([
333 "Resolve conflicts",
334 "Ask a question",
335 "Explain this PR",
336 "Fix findings in this thread",
337 "Fix check",
338 "Add to agent",
339 ])("%s writes to the correct composer", async (action) => {
340 if (target) useComposerDraftStore.getState().setPrompt(target, "Keep my draft");
341 await renderPanel();
342 await runAction(target ? action : action.replace("in this thread", "in a thread"));
343 const draft = () => useComposerDraftStore.getState().getComposerDraft(target ?? newDraftId);
344 await vi.waitFor(() => {
345 if (action === "Resolve conflicts")
346 expect(draft()?.prompt).toContain("resolve every conflict");
347 else if (action === "Fix check") expect(draft()?.prompt).toContain("Fix the failing check");
348 else if (action.startsWith("Fix findings"))
349 expect(draft()?.prompt).toContain("Fix the actionable findings");
350 else expect(draft()?.reviewComments?.length).toBeGreaterThan(0);
351 });
352 if (action === "Add to agent") {
353 expect(draft()?.prompt).toContain("Fix this line");
354 expect(draft()?.reviewComments).toEqual(
355 expect.arrayContaining([expect.objectContaining({ id: "note-1", diff: "+broken()" })]),
356 );
357 }
358 if (target) {
359 expect(draft()?.prompt).toContain("Keep my draft");
360 expect(newThread).not.toHaveBeenCalled();
361 expect(prepareThread).not.toHaveBeenCalled();
362 } else {
363 expect(newThread).toHaveBeenCalled();
364 }
365 });
366});
367
368it("folds the title only for the active tab's own scroller", async () => {
369 await render();
370 const title = page.getByRole("heading", { level: 1, name: "Test pull request" });
371 await expect.element(title).toBeVisible();
372 const titleFold = () => title.element().closest("[inert]") !== null;
373 const scrollTo = async (testId: string, top: number) => {
374 const scroller = page.getByTestId(testId).element() as HTMLElement;
375 await act(async () => {
376 scroller.scrollTop = top;
377 scroller.dispatchEvent(new Event("scroll"));
378 });
379 return scroller;
380 };
381
382 await scrollTo("nested-scroller", 600);
383 expect(titleFold()).toBe(false);
384
385 const summary = await scrollTo("summary-scroller", 600);
386 await vi.waitFor(() => expect(titleFold()).toBe(true));
387 // Folding the header keeps the content under the reader's eye.
388 expect(summary.scrollTop).toBeLessThan(600);
389
390 await scrollTo("summary-scroller", 0);
391 await vi.waitFor(() => expect(titleFold()).toBe(false));
392 await scrollTo("summary-scroller", 600);
393 await vi.waitFor(() => expect(titleFold()).toBe(true));
394
395 await tab("Code").click();
396 await expect.element(page.getByTestId("code-scroller")).toBeInTheDocument();
397 await vi.waitFor(() => expect(titleFold()).toBe(false));
398 await scrollTo("code-scroller", 600);
399 await vi.waitFor(() => expect(titleFold()).toBe(true));
400
401 await tab("Summary").click();
402 await vi.waitFor(() => expect(titleFold()).toBe(true));
403 await scrollTo("summary-scroller", 0);
404 await vi.waitFor(() => expect(titleFold()).toBe(false));
405 await tab("Code").click();
406 await vi.waitFor(() => expect(titleFold()).toBe(true));
407});
408
409it("shows the current checkout recovery detail on the first failure and on retry", async () => {
410 const first = new GitManagerError({
411 cwd: "/workspace",
412 operation: "preparePullRequestThread",
413 detail: "This PR branch is already checked out in the main repo. Use Local.",
414 });
415 const second = new GitCommandError({
416 cwd: "/workspace",
417 operation: "GitVcsDriver.createWorktree",
418 command: "git worktree add",
419 detail: "The worktree directory already exists. Choose another directory.",
420 });
421 await render();
422
423 for (const [index, error] of [first, second].entries()) {
424 prepareThread.mockImplementationOnce(async () => {
425 checkoutState.error = error;
426 return { _tag: "Failure", cause: Cause.fail(error) };
427 });
428 await page.getByRole("button", { name: "Check out", exact: true }).click();
429 await page.getByRole("menuitem", { name: /In a separate worktree/ }).click();
430 await vi.waitFor(() => expect(updateToast).toHaveBeenCalledTimes(index + 1));
431 }
432 expect(updateToast.mock.calls.map(([, toast]) => toast.description)).toEqual([
433 expect.stringContaining(first.detail),
434 second.detail,
435 ]);
436});