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, update, addToast, updateToast, checkoutState } =
22 vi.hoisted(() => ({
23 newThread: vi.fn(),
24 prepareThread: vi.fn(),
25 refresh: vi.fn(),
26 update: vi.fn(),
27 addToast: vi.fn(),
28 updateToast: vi.fn(),
29 checkoutState: { error: null as Error | null },
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: ((command: unknown) => (command === "update" ? update : 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 update: "update" as never,
68 reviewGuide: (() => "review-guide") as never,
69 generateReviewGuide: {
70 ...actual.pullRequestEnvironment.generateReviewGuide,
71 permissionAtom: () => cannotWriteGuides,
72 },
73 },
74 };
75});
76vi.mock(import("~/state/query"), async (original) => ({
77 ...(await original()),
78 useEnvironmentQuery: ((query: unknown) => ({
79 data: query === "detail" ? detail : null,
80 dataUpdatedAt: 0,
81 failure: null,
82 isPending: false,
83 isSuccess: true,
84 error: null,
85 refresh,
86 })) as never,
87}));
88vi.mock(import("~/state/usePullRequestStack"), async (original) => ({
89 ...(await original()),
90 usePullRequestStack: (() => ({
91 data: null,
92 isSuccess: true,
93 isPending: false,
94 error: null,
95 refresh,
96 })) as never,
97}));
98// The real tabs load diffs, markdown and checks from the environment; these stand-ins
99// expose the actions they hand back to the panel and a tall scroller.
100vi.mock(import("./PullRequestSummaryTab"), async (original) => ({
101 ...(await original()),
102 PullRequestSummaryTab: (({
103 onFixFinding,
104 scrollerRef,
105 }: ComponentProps<typeof import("./PullRequestSummaryTab").PullRequestSummaryTab>) => (
106 <div ref={scrollerRef} data-testid="summary-scroller" className="h-full overflow-y-auto">
107 <button
108 type="button"
109 onClick={() =>
110 onFixFinding?.({
111 kind: "check",
112 check: { name: "Unit tests", status: "failure", description: "Test failed", url: null },
113 })
114 }
115 >
116 Fix check
117 </button>
118 <div data-testid="nested-scroller" className="h-40 overflow-y-auto">
119 <div className="h-[2000px]" />
120 </div>
121 <div className="h-[3000px]" />
122 </div>
123 )) as never,
124}));
125vi.mock(import("./PullRequestCodeTab"), async (original) => ({
126 ...(await original()),
127 default: (({
128 onAddToAgentSelection,
129 scrollerRef,
130 }: ComponentProps<typeof import("./PullRequestCodeTab").default>) => (
131 <div ref={scrollerRef} data-testid="code-scroller" className="h-full overflow-y-auto">
132 <button
133 type="button"
134 onClick={() =>
135 onAddToAgentSelection?.({
136 request: "Fix this line",
137 comment: {
138 id: "note-1",
139 sectionId: "file:a.ts",
140 sectionTitle: "a.ts",
141 filePath: "a.ts",
142 startIndex: 0,
143 endIndex: 0,
144 rangeLabel: "L1",
145 text: "Please fix",
146 diff: "+broken()",
147 },
148 })
149 }
150 >
151 Add to agent
152 </button>
153 <div className="h-[3000px]" />
154 </div>
155 )) as never,
156}));
157
158vi.mock(import("../ui/toast"), async (original) => {
159 const actual = await original();
160 return {
161 ...actual,
162 toastManager: { ...actual.toastManager, add: addToast, update: updateToast } as never,
163 };
164});
165
166import { PullRequestDetailPanel } from "./PullRequestDetailPanel";
167import { pullRequestPanelContext } from "./pullRequestDetail.logic";
168
169const detail: PullRequestDetailView = {
170 provider: SourceControlProviderKind.make("github"),
171 projectId: ProjectId.make("project"),
172 projectTitle: "Project",
173 workspaceRoot: "/workspace",
174 repository: "owner/repo",
175 number: 1,
176 title: "Test pull request",
177 body: "Original description",
178 url: "https://github.com/owner/repo/pull/1",
179 author: { login: "author", name: null, avatarUrl: null },
180 viewer: "author",
181 state: "open",
182 isDraft: false,
183 mergeability: "conflicting",
184 additions: 1,
185 deletions: 0,
186 changedFiles: 1,
187 headBranch: "feature",
188 baseBranch: "main",
189 createdAt: "2026-09-01T00:00:00Z",
190 updatedAt: "2026-09-01T00:00:00Z",
191 mergedAt: null,
192 closedAt: null,
193 reviewers: [],
194 labels: [],
195 checks: [{ name: "Unit tests", status: "success", description: null, url: null }],
196 comments: [],
197 commentCount: 0,
198 commentsTruncated: false,
199 reviewThreads: [],
200 commits: [],
201 mergeCapabilities: { merge: false, squash: false, rebase: false },
202 capabilities: {
203 diff: true,
204 comment: false,
205 search: true,
206 actions: [],
207 mergeMethods: [],
208 review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
209 reviewers: { request: false, listCandidates: false },
210 edit: { changeRequest: true, comment: false },
211 },
212 viewerPermissions: {
213 actions: [],
214 comment: false,
215 resolve: false,
216 verdicts: [],
217 requestReviewers: false,
218 },
219};
220
221const threadRef: ScopedThreadRef = {
222 environmentId: EnvironmentId.make("env-1"),
223 threadId: ThreadId.make("thread-1"),
224};
225const draftId = DraftId.make("draft-1");
226const newDraftId = DraftId.make("new-draft");
227const shortcutContext = () => ({
228 terminalFocus: false,
229 terminalOpen: false,
230 previewFocus: false,
231 previewOpen: false,
232 isWeb: true,
233 isDesktop: false,
234});
235
236const roots: Root[] = [];
237
238function render(props: Partial<ComponentProps<typeof PullRequestDetailPanel>> = {}) {
239 const container = document.createElement("div");
240 container.className = "flex h-[700px] w-[900px]";
241 document.body.append(container);
242 const root = createRoot(container);
243 roots.push(root);
244 return act(async () =>
245 root.render(
246 <PullRequestDetailPanel
247 environmentId={threadRef.environmentId}
248 reference={detail}
249 context="page"
250 shortcutsEnabled={false}
251 getShortcutContext={shortcutContext}
252 {...props}
253 />,
254 ),
255 );
256}
257
258beforeEach(() => {
259 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
260 useComposerDraftStore.setState({ draftsByThreadKey: {} });
261 newThread
262 .mockReset()
263 .mockResolvedValue({ draftId: newDraftId, threadId: ThreadId.make("new-thread") });
264 addToast.mockReset().mockReturnValue("checkout-toast");
265 updateToast.mockReset();
266 checkoutState.error = null;
267 prepareThread.mockReset().mockResolvedValue({
268 _tag: "Success",
269 value: { branch: "feature", worktreePath: "/workspace/pr" },
270 });
271 update.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
272});
273afterEach(async () => {
274 for (const root of roots.splice(0)) await act(async () => root.unmount());
275 document.body.replaceChildren();
276 vi.unstubAllGlobals();
277});
278
279const surface = { projectId: detail.projectId, repository: detail.repository, number: 1 };
280const link = (number: number, source: ThreadPullRequestLink["source"]): ThreadPullRequestLink => ({
281 host: "github.com",
282 repository: detail.repository,
283 number,
284 url: `https://github.com/${detail.repository}/pull/${number}`,
285 source,
286 linkedAt: "2026-09-01T00:00:00Z",
287 snapshot: null,
288 stack: null,
289});
290const stackThread = {
291 projectId: detail.projectId,
292 pullRequests: [link(3, "manual"), link(2, "stack"), link(1, "stack")],
293 linkedPullRequest: { ...surface, number: 3, url: link(3, "manual").url },
294};
295const unrelatedThread = {
296 projectId: detail.projectId,
297 pullRequests: [link(9, "created")],
298 linkedPullRequest: { ...surface, number: 9, url: link(9, "created").url },
299};
300
301const tab = (name: string) => page.getByRole("button", { name, exact: true });
302
303it.each([
304 { isComposing: true, keyCode: 13 },
305 { isComposing: false, keyCode: 229 },
306])("does not save the PR title during IME composition (%j)", async ({ isComposing, keyCode }) => {
307 await render();
308 await page.getByRole("button", { name: "Edit title" }).click();
309 const titleInput = page.getByRole("textbox", { name: "Pull request title" });
310 const title = "日本語のタイトル";
311 await titleInput.fill(title);
312 const pressEnter = (init: KeyboardEventInit) =>
313 act(async () => {
314 titleInput
315 .element()
316 .dispatchEvent(
317 new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true, ...init }),
318 );
319 });
320
321 await pressEnter({ isComposing, keyCode });
322 expect(update).not.toHaveBeenCalled();
323 await expect.element(titleInput).toHaveValue(title);
324
325 await pressEnter({ keyCode: 13 });
326 expect(update).toHaveBeenCalledExactlyOnceWith({
327 environmentId: threadRef.environmentId,
328 input: { ...surface, title },
329 });
330 await expect.element(titleInput).not.toBeInTheDocument();
331});
332
333async function runAction(action: string) {
334 if (action === "Add to agent") {
335 await tab("Code").click();
336 }
337 if (["Ask a question", "Explain this PR"].includes(action) || action.startsWith("Fix findings")) {
338 await page.getByRole("button", { name: "More pull request actions" }).click();
339 // Menu items carry a description under their label.
340 await page.getByRole("menuitem", { name: new RegExp(`^${action}`) }).click();
341 return;
342 }
343 await page.getByRole("button", { name: action, exact: true }).click();
344}
345
346describe.each([
347 ["own PR, a lower layer of the thread's stack", stackThread, threadRef],
348 ["another PR beside the current thread", unrelatedThread, threadRef],
349 ["PR beside an unsent draft", null, draftId],
350 ["standalone PR page", null, undefined],
351] as const)("%s", (_name, thread, target) => {
352 const context = thread ? pullRequestPanelContext(thread, surface) : "page";
353 const renderPanel = () =>
354 render({ context, ...(target ? { composerDraftTarget: target, threadRef } : {}) });
355
356 it(`${thread === stackThread ? "hides" : "offers"} the checkout`, async () => {
357 await renderPanel();
358 await expect.element(page.getByText("Test pull request").first()).toBeVisible();
359 expect(page.getByRole("button", { name: "Check out" }).elements()).toHaveLength(
360 thread === stackThread ? 0 : 1,
361 );
362 });
363
364 it.each([
365 "Resolve conflicts",
366 "Ask a question",
367 "Explain this PR",
368 "Fix findings in this thread",
369 "Fix check",
370 "Add to agent",
371 ])("%s writes to the correct composer", async (action) => {
372 if (target) useComposerDraftStore.getState().setPrompt(target, "Keep my draft");
373 await renderPanel();
374 await runAction(target ? action : action.replace("in this thread", "in a thread"));
375 const draft = () => useComposerDraftStore.getState().getComposerDraft(target ?? newDraftId);
376 await vi.waitFor(() => {
377 if (action === "Resolve conflicts")
378 expect(draft()?.prompt).toContain("resolve every conflict");
379 else if (action === "Fix check") expect(draft()?.prompt).toContain("Fix the failing check");
380 else if (action.startsWith("Fix findings"))
381 expect(draft()?.prompt).toContain("Fix the actionable findings");
382 else expect(draft()?.reviewComments?.length).toBeGreaterThan(0);
383 });
384 if (action === "Add to agent") {
385 expect(draft()?.prompt).toContain("Fix this line");
386 expect(draft()?.reviewComments).toEqual(
387 expect.arrayContaining([expect.objectContaining({ id: "note-1", diff: "+broken()" })]),
388 );
389 }
390 if (target) {
391 expect(draft()?.prompt).toContain("Keep my draft");
392 expect(newThread).not.toHaveBeenCalled();
393 expect(prepareThread).not.toHaveBeenCalled();
394 } else {
395 expect(newThread).toHaveBeenCalled();
396 }
397 });
398});
399
400it("folds the title only for the active tab's own scroller", async () => {
401 await render();
402 const title = page.getByRole("heading", { level: 1, name: "Test pull request" });
403 await expect.element(title).toBeVisible();
404 const titleFold = () => title.element().closest("[inert]") !== null;
405 const scrollTo = async (testId: string, top: number) => {
406 const scroller = page.getByTestId(testId).element() as HTMLElement;
407 await act(async () => {
408 scroller.scrollTop = top;
409 scroller.dispatchEvent(new Event("scroll"));
410 });
411 return scroller;
412 };
413
414 await scrollTo("nested-scroller", 600);
415 expect(titleFold()).toBe(false);
416
417 const summary = await scrollTo("summary-scroller", 600);
418 await vi.waitFor(() => expect(titleFold()).toBe(true));
419 // Folding the header keeps the content under the reader's eye.
420 expect(summary.scrollTop).toBeLessThan(600);
421
422 await scrollTo("summary-scroller", 0);
423 await vi.waitFor(() => expect(titleFold()).toBe(false));
424 await scrollTo("summary-scroller", 600);
425 await vi.waitFor(() => expect(titleFold()).toBe(true));
426
427 await tab("Code").click();
428 await expect.element(page.getByTestId("code-scroller")).toBeInTheDocument();
429 await vi.waitFor(() => expect(titleFold()).toBe(false));
430 await scrollTo("code-scroller", 600);
431 await vi.waitFor(() => expect(titleFold()).toBe(true));
432
433 await tab("Summary").click();
434 await vi.waitFor(() => expect(titleFold()).toBe(true));
435 await scrollTo("summary-scroller", 0);
436 await vi.waitFor(() => expect(titleFold()).toBe(false));
437 await tab("Code").click();
438 await vi.waitFor(() => expect(titleFold()).toBe(true));
439});
440
441it("stays collapsed at the bottom after native scroll clamping and reopens at the top", async () => {
442 await render();
443 const title = page.getByRole("heading", { level: 1, name: "Test pull request" });
444 await expect.element(title).toBeVisible();
445 const scroller = page.getByTestId("summary-scroller").element() as HTMLElement;
446 const content = scroller.lastElementChild as HTMLElement;
447 // Leave only a short scroll range so folding the header makes the browser clamp it.
448 content.style.height = `${scroller.clientHeight - 24}px`;
449 const expandedHeight = scroller.clientHeight;
450 const expandedBottom = scroller.scrollHeight - scroller.clientHeight;
451
452 await act(async () => {
453 const scrolled = new Promise<void>((resolve) =>
454 scroller.addEventListener("scroll", () => resolve(), { once: true }),
455 );
456 scroller.scrollTop = scroller.scrollHeight;
457 await scrolled;
458 });
459
460 await vi.waitFor(() => {
461 expect(title.element().closest("[inert]")).not.toBeNull();
462 expect(scroller.clientHeight).toBeGreaterThan(expandedHeight);
463 expect(scroller.scrollTop).toBeGreaterThan(0);
464 expect(scroller.scrollTop).toBeLessThan(expandedBottom);
465 expect(scroller.scrollTop).toBe(scroller.scrollHeight - scroller.clientHeight);
466 });
467
468 await act(async () => {
469 const scrolled = new Promise<void>((resolve) =>
470 scroller.addEventListener("scroll", () => resolve(), { once: true }),
471 );
472 scroller.scrollTop = 0;
473 await scrolled;
474 });
475 await vi.waitFor(() => expect(title.element().closest("[inert]")).toBeNull());
476});
477
478it("shows the current checkout recovery detail on the first failure and on retry", async () => {
479 const first = new GitManagerError({
480 cwd: "/workspace",
481 operation: "preparePullRequestThread",
482 detail: "This PR branch is already checked out in the main repo. Use Local.",
483 });
484 const second = new GitCommandError({
485 cwd: "/workspace",
486 operation: "GitVcsDriver.createWorktree",
487 command: "git worktree add",
488 detail: "The worktree directory already exists. Choose another directory.",
489 });
490 await render();
491
492 for (const [index, error] of [first, second].entries()) {
493 prepareThread.mockImplementationOnce(async () => {
494 checkoutState.error = error;
495 return { _tag: "Failure", cause: Cause.fail(error) };
496 });
497 await page.getByRole("button", { name: "Check out", exact: true }).click();
498 await page.getByRole("menuitem", { name: /In a separate worktree/ }).click();
499 await vi.waitFor(() => expect(updateToast).toHaveBeenCalledTimes(index + 1));
500 }
501 expect(updateToast.mock.calls.map(([, toast]) => toast.description)).toEqual([
502 expect.stringContaining(first.detail),
503 second.detail,
504 ]);
505});