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, userEvent } from "vite-plus/test/browser";
17import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
18
19import "~/index.css";
20
21const {
22 newThread,
23 prepareThread,
24 refresh,
25 update,
26 addToast,
27 updateToast,
28 checkoutState,
29 hostCommand,
30 queries,
31} = vi.hoisted(() => ({
32 hostCommand: vi.fn(),
33 queries: { diff: undefined as unknown },
34 newThread: vi.fn(),
35 prepareThread: vi.fn(),
36 refresh: vi.fn(),
37 update: vi.fn(),
38 addToast: vi.fn(),
39 updateToast: vi.fn(),
40 checkoutState: { error: null as Error | null },
41}));
42
43vi.mock(import("~/state/session"), async (original) => ({
44 ...(await original()),
45 useEnvironmentScope: () => true,
46 readEnvironmentScope: () => true,
47}));
48vi.mock(import("~/hooks/useSettings"), async (original) => ({
49 ...(await original()),
50 useEnvironmentSettings: (() => undefined) as never,
51}));
52vi.mock(import("~/hooks/useHandleNewThread"), async (original) => ({
53 ...(await original()),
54 useNewThreadHandler: (() => newThread) as never,
55}));
56vi.mock(import("~/lib/sourceControlActions"), async (original) => ({
57 ...(await original()),
58 usePreparePullRequestThreadAction: (() => ({
59 run: prepareThread,
60 isAllowed: true,
61 error: checkoutState.error,
62 })) as never,
63}));
64vi.mock(import("~/state/use-atom-command"), async (original) => ({
65 ...(await original()),
66 useAtomCommand: ((command: unknown) => (command === "update" ? update : hostCommand)) as never,
67}));
68vi.mock(import("~/state/pullRequests"), async (original) => {
69 const actual = await original();
70 const { Atom } = await import("effect/reactivity");
71 const cannotWriteGuides = Atom.make(false);
72 const diff = Atom.make(null);
73 queries.diff = diff;
74 return {
75 ...actual,
76 pullRequestEnvironment: {
77 ...actual.pullRequestEnvironment,
78 detail: (() => "detail") as never,
79 diff: (() => diff) as never,
80 activity: (() => "activity") as never,
81 update: "update" as never,
82 reviewGuide: (() => "review-guide") as never,
83 generateReviewGuide: {
84 ...actual.pullRequestEnvironment.generateReviewGuide,
85 permissionAtom: () => cannotWriteGuides,
86 },
87 },
88 };
89});
90vi.mock(import("~/state/query"), async (original) => ({
91 ...(await original()),
92 useEnvironmentQuery: ((query: unknown) => ({
93 data: query === "detail" ? currentDetail : query === queries.diff ? diff : null,
94 dataUpdatedAt: 0,
95 failure: null,
96 isPending: false,
97 isSuccess: true,
98 error: null,
99 refresh,
100 })) as never,
101}));
102vi.mock(import("~/state/usePullRequestStack"), async (original) => ({
103 ...(await original()),
104 usePullRequestStack: (() => ({
105 data: null,
106 isSuccess: true,
107 isPending: false,
108 error: null,
109 refresh,
110 })) as never,
111}));
112// The summary stand-in exposes its panel actions and nested scrolling.
113vi.mock(import("./PullRequestSummaryTab"), async (original) => ({
114 ...(await original()),
115 PullRequestSummaryTab: (({
116 onFixFinding,
117 scrollerRef,
118 }: ComponentProps<typeof import("./PullRequestSummaryTab").PullRequestSummaryTab>) => (
119 <div ref={scrollerRef} data-testid="summary-scroller" className="h-full overflow-y-auto">
120 <button
121 type="button"
122 onClick={() =>
123 onFixFinding?.({
124 kind: "check",
125 check: { name: "Unit tests", status: "failure", description: "Test failed", url: null },
126 })
127 }
128 >
129 Fix check
130 </button>
131 <div data-testid="nested-scroller" className="h-40 overflow-y-auto">
132 <div className="h-[2000px]" />
133 </div>
134 <div className="h-[3000px]" />
135 </div>
136 )) as never,
137}));
138
139vi.mock(import("../ui/toast"), async (original) => {
140 const actual = await original();
141 return {
142 ...actual,
143 toastManager: { ...actual.toastManager, add: addToast, update: updateToast } as never,
144 };
145});
146
147import { PullRequestDetailPanel } from "./PullRequestDetailPanel";
148import { pullRequestPanelContext } from "./pullRequestDetail.logic";
149import { usePullRequestReviewStore } from "./pullRequestReviewStore";
150
151const detail: PullRequestDetailView = {
152 provider: SourceControlProviderKind.make("github"),
153 projectId: ProjectId.make("project"),
154 projectTitle: "Project",
155 workspaceRoot: "/workspace",
156 repository: "owner/repo",
157 number: 1,
158 title: "Test pull request",
159 body: "Original description",
160 url: "https://github.com/owner/repo/pull/1",
161 author: { login: "author", name: null, avatarUrl: null },
162 viewer: "author",
163 state: "open",
164 isDraft: false,
165 mergeability: "conflicting",
166 additions: 1,
167 deletions: 0,
168 changedFiles: 1,
169 headBranch: "feature",
170 baseBranch: "main",
171 createdAt: "2026-09-01T00:00:00Z",
172 updatedAt: "2026-09-01T00:00:00Z",
173 mergedAt: null,
174 closedAt: null,
175 reviewers: [],
176 labels: [],
177 checks: [{ name: "Unit tests", status: "success", description: null, url: null }],
178 comments: [],
179 commentCount: 0,
180 commentsTruncated: false,
181 reviewThreads: [],
182 commits: [],
183 mergeCapabilities: { merge: false, squash: false, rebase: false },
184 capabilities: {
185 diff: true,
186 comment: false,
187 search: true,
188 actions: [],
189 mergeMethods: [],
190 review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
191 reviewers: { request: false, listCandidates: false },
192 edit: { changeRequest: true, comment: false },
193 },
194 viewerPermissions: {
195 actions: [],
196 comment: false,
197 resolve: false,
198 verdicts: [],
199 requestReviewers: false,
200 },
201};
202
203let currentDetail = detail;
204
205// Enough lines to exercise the panel's title folding with the real virtualized Code tab.
206const diff = {
207 patch: [
208 "diff --git a/a.ts b/a.ts",
209 "new file mode 100644",
210 "--- /dev/null",
211 "+++ b/a.ts",
212 "@@ -0,0 +1,100 @@",
213 "+broken()",
214 ...Array.from({ length: 99 }, (_, index) => `+// line ${index + 2}`),
215 "",
216 ].join("\n"),
217 truncated: false,
218 nextCursor: null,
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 currentDetail = detail;
261 useComposerDraftStore.setState({ draftsByThreadKey: {} });
262 usePullRequestReviewStore.setState({ drafts: {}, summaries: {} });
263 hostCommand.mockReset();
264 newThread
265 .mockReset()
266 .mockResolvedValue({ draftId: newDraftId, threadId: ThreadId.make("new-thread") });
267 addToast.mockReset().mockReturnValue("checkout-toast");
268 updateToast.mockReset();
269 checkoutState.error = null;
270 prepareThread.mockReset().mockResolvedValue({
271 _tag: "Success",
272 value: { branch: "feature", worktreePath: "/workspace/pr" },
273 });
274 update.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
275});
276afterEach(async () => {
277 for (const root of roots.splice(0)) await act(async () => root.unmount());
278 document.body.replaceChildren();
279 vi.unstubAllGlobals();
280});
281
282const surface = { projectId: detail.projectId, repository: detail.repository, number: 1 };
283const link = (number: number, source: ThreadPullRequestLink["source"]): ThreadPullRequestLink => ({
284 host: "github.com",
285 repository: detail.repository,
286 number,
287 url: `https://github.com/${detail.repository}/pull/${number}`,
288 source,
289 linkedAt: "2026-09-01T00:00:00Z",
290 snapshot: null,
291 stack: null,
292});
293const stackThread = {
294 projectId: detail.projectId,
295 pullRequests: [link(3, "manual"), link(2, "stack"), link(1, "stack")],
296 linkedPullRequest: { ...surface, number: 3, url: link(3, "manual").url },
297};
298const unrelatedThread = {
299 projectId: detail.projectId,
300 pullRequests: [link(9, "created")],
301 linkedPullRequest: { ...surface, number: 9, url: link(9, "created").url },
302};
303
304const tab = (name: string) => page.getByRole("button", { name, exact: true });
305
306const selectionDraft = () => page.getByRole("textbox", { name: "Comment on lines a.ts:1" });
307
308async function selectFirstLine() {
309 const line = page.getByText("broken()", { exact: true });
310 await expect.element(line).toBeVisible();
311 const host = line.element().getRootNode() as ShadowRoot;
312 const gutter = host.querySelector<HTMLElement>('[data-column-number="1"]')!;
313 await userEvent.click(gutter);
314}
315
316it.each([
317 { isComposing: true, keyCode: 13 },
318 { isComposing: false, keyCode: 229 },
319])("does not save the PR title during IME composition (%j)", async ({ isComposing, keyCode }) => {
320 await render();
321 await page.getByRole("button", { name: "Edit title" }).click();
322 const titleInput = page.getByRole("textbox", { name: "Pull request title" });
323 const title = "日本語のタイトル";
324 await titleInput.fill(title);
325 const pressEnter = (init: KeyboardEventInit) =>
326 act(async () => {
327 titleInput
328 .element()
329 .dispatchEvent(
330 new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true, ...init }),
331 );
332 });
333
334 await pressEnter({ isComposing, keyCode });
335 expect(update).not.toHaveBeenCalled();
336 await expect.element(titleInput).toHaveValue(title);
337
338 await pressEnter({ keyCode: 13 });
339 expect(update).toHaveBeenCalledExactlyOnceWith({
340 environmentId: threadRef.environmentId,
341 input: { ...surface, title },
342 });
343 await expect.element(titleInput).not.toBeInTheDocument();
344});
345
346async function runAction(action: string) {
347 if (action === "Add to agent") {
348 await tab("Code").click();
349 await page.getByRole("button", { name: "Expand all files", exact: true }).click();
350 await selectFirstLine();
351 const draft = page.getByRole("textbox", { name: "Comment on lines a.ts:1" });
352 await expect.element(draft).toBeVisible();
353 expect(
354 page.getByRole("button", { name: "Add to review", exact: true }).elements(),
355 ).toHaveLength(0);
356 await draft.fill("Fix this line");
357 }
358 if (["Ask a question", "Explain this PR"].includes(action) || action.startsWith("Fix findings")) {
359 await page.getByRole("button", { name: "More pull request actions" }).click();
360 // Menu items carry a description under their label.
361 await page.getByRole("menuitem", { name: new RegExp(`^${action}`) }).click();
362 return;
363 }
364 await page.getByRole("button", { name: action, exact: true }).click();
365}
366
367describe.each([
368 ["own PR, a lower layer of the thread's stack", stackThread, threadRef],
369 ["another PR beside the current thread", unrelatedThread, threadRef],
370 ["PR beside an unsent draft", null, draftId],
371 ["standalone PR page", null, undefined],
372] as const)("%s", (_name, thread, target) => {
373 const context = thread ? pullRequestPanelContext(thread, surface) : "page";
374 const renderPanel = () =>
375 render({ context, ...(target ? { composerDraftTarget: target, threadRef } : {}) });
376
377 it(`${thread === stackThread ? "hides" : "offers"} the checkout`, async () => {
378 await renderPanel();
379 await expect.element(page.getByText("Test pull request").first()).toBeVisible();
380 expect(page.getByRole("button", { name: "Check out" }).elements()).toHaveLength(
381 thread === stackThread ? 0 : 1,
382 );
383 });
384
385 it.each([
386 "Resolve conflicts",
387 "Ask a question",
388 "Explain this PR",
389 "Fix findings in this thread",
390 "Fix check",
391 "Add to agent",
392 ])("%s writes to the correct composer", async (action) => {
393 // Cover both a host without inline comments and an account that cannot write them.
394 currentDetail =
395 thread === stackThread
396 ? {
397 ...detail,
398 capabilities: {
399 ...detail.capabilities,
400 review: { ...detail.capabilities.review, inlineComment: true },
401 },
402 }
403 : { ...detail, viewerPermissions: { ...detail.viewerPermissions, comment: true } };
404 if (target) useComposerDraftStore.getState().setPrompt(target, "Keep my draft");
405 await renderPanel();
406 await runAction(target ? action : action.replace("in this thread", "in a thread"));
407 const draft = () => useComposerDraftStore.getState().getComposerDraft(target ?? newDraftId);
408 await vi.waitFor(() => {
409 if (action === "Resolve conflicts")
410 expect(draft()?.prompt).toContain("resolve every conflict");
411 else if (action === "Fix check") expect(draft()?.prompt).toContain("Fix the failing check");
412 else if (action.startsWith("Fix findings"))
413 expect(draft()?.prompt).toContain("Fix the actionable findings");
414 else expect(draft()?.reviewComments?.length).toBeGreaterThan(0);
415 });
416 if (action === "Add to agent") {
417 expect(draft()?.prompt).toContain("Fix this line");
418 expect(draft()?.reviewComments).toEqual(
419 expect.arrayContaining([
420 expect.objectContaining({
421 filePath: "a.ts",
422 diff: expect.stringContaining("+broken()"),
423 startIndex: 0,
424 endIndex: 0,
425 }),
426 ]),
427 );
428 expect(usePullRequestReviewStore.getState().drafts).toEqual({});
429 expect(hostCommand).not.toHaveBeenCalled();
430 await expect
431 .element(page.getByRole("textbox", { name: "Comment on lines a.ts:1" }))
432 .not.toBeInTheDocument();
433 }
434 if (target) {
435 expect(draft()?.prompt).toContain("Keep my draft");
436 expect(newThread).not.toHaveBeenCalled();
437 expect(prepareThread).not.toHaveBeenCalled();
438 } else {
439 expect(newThread).toHaveBeenCalled();
440 }
441 });
442});
443
444it("offers both selection actions and queues a permitted host review locally", async () => {
445 currentDetail = {
446 ...detail,
447 capabilities: {
448 ...detail.capabilities,
449 review: { ...detail.capabilities.review, inlineComment: true },
450 },
451 viewerPermissions: { ...detail.viewerPermissions, comment: true },
452 };
453 await render({ composerDraftTarget: draftId, threadRef });
454 await tab("Code").click();
455 await page.getByRole("button", { name: "Expand all files", exact: true }).click();
456 await selectFirstLine();
457 const addToReview = page.getByRole("button", { name: "Add to review", exact: true });
458 await expect.element(addToReview).toBeVisible();
459 await expect
460 .element(page.getByRole("button", { name: "Add to agent", exact: true }))
461 .toBeVisible();
462 await selectionDraft().fill("Fix this line before merging");
463 await addToReview.click();
464 await expect.element(selectionDraft()).not.toBeInTheDocument();
465 expect(Object.values(usePullRequestReviewStore.getState().drafts).flat()).toEqual([
466 expect.objectContaining({ path: "a.ts", body: "Fix this line before merging" }),
467 ]);
468 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.reviewComments ?? []).toEqual(
469 [],
470 );
471 expect(hostCommand).not.toHaveBeenCalled();
472});
473
474it("cancels an agent-only selection and submits a fresh one with the keyboard without a host review", async () => {
475 await render({ composerDraftTarget: draftId, threadRef });
476 await tab("Code").click();
477 await page.getByRole("button", { name: "Expand all files", exact: true }).click();
478 await selectFirstLine();
479 await selectionDraft().fill("Discard this request");
480 await page.getByRole("button", { name: "Cancel", exact: true }).click();
481 await expect.element(selectionDraft()).not.toBeInTheDocument();
482 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.reviewComments ?? []).toEqual(
483 [],
484 );
485 expect(usePullRequestReviewStore.getState().drafts).toEqual({});
486 expect(hostCommand).not.toHaveBeenCalled();
487
488 await selectFirstLine();
489 await expect.element(selectionDraft()).toHaveValue("");
490 await selectionDraft().fill("Fix this line");
491 await userEvent.keyboard("{Control>}{Enter}{/Control}");
492 await expect.element(selectionDraft()).not.toBeInTheDocument();
493 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.prompt).toContain(
494 "Fix this line",
495 );
496 expect(usePullRequestReviewStore.getState().drafts).toEqual({});
497 expect(hostCommand).not.toHaveBeenCalled();
498});
499
500it("folds the title only for the active tab's own scroller", async () => {
501 await render();
502 const title = page.getByRole("heading", { level: 1, name: "Test pull request" });
503 await expect.element(title).toBeVisible();
504 const titleFold = () => title.element().closest("[inert]") !== null;
505 const scrollTo = async (testId: string, top: number) => {
506 const scroller =
507 testId === "code-scroller"
508 ? document.querySelector<HTMLElement>(".\\@container.overflow-auto")!
509 : (page.getByTestId(testId).element() as HTMLElement);
510 await act(async () => {
511 scroller.scrollTop = top;
512 scroller.dispatchEvent(new Event("scroll"));
513 });
514 return scroller;
515 };
516
517 await scrollTo("nested-scroller", 600);
518 expect(titleFold()).toBe(false);
519
520 const summary = await scrollTo("summary-scroller", 600);
521 await vi.waitFor(() => expect(titleFold()).toBe(true));
522 // Folding the header keeps the content under the reader's eye.
523 expect(summary.scrollTop).toBeLessThan(600);
524
525 await scrollTo("summary-scroller", 0);
526 await vi.waitFor(() => expect(titleFold()).toBe(false));
527 await scrollTo("summary-scroller", 600);
528 await vi.waitFor(() => expect(titleFold()).toBe(true));
529
530 await tab("Code").click();
531 await page.getByRole("button", { name: "Expand all files", exact: true }).click();
532 await expect.element(page.getByText("broken()", { exact: true })).toBeVisible();
533 await vi.waitFor(() => expect(titleFold()).toBe(false));
534 await scrollTo("code-scroller", 600);
535 await vi.waitFor(() => expect(titleFold()).toBe(true));
536
537 await tab("Summary").click();
538 await vi.waitFor(() => expect(titleFold()).toBe(true));
539 await scrollTo("summary-scroller", 0);
540 await vi.waitFor(() => expect(titleFold()).toBe(false));
541 await tab("Code").click();
542 await vi.waitFor(() => expect(titleFold()).toBe(true));
543});
544
545it("stays collapsed at the bottom after native scroll clamping and reopens at the top", async () => {
546 await render();
547 const title = page.getByRole("heading", { level: 1, name: "Test pull request" });
548 await expect.element(title).toBeVisible();
549 const scroller = page.getByTestId("summary-scroller").element() as HTMLElement;
550 const content = scroller.lastElementChild as HTMLElement;
551 // Leave only a short scroll range so folding the header makes the browser clamp it.
552 content.style.height = `${scroller.clientHeight - 24}px`;
553 const expandedHeight = scroller.clientHeight;
554 const expandedBottom = scroller.scrollHeight - scroller.clientHeight;
555
556 await act(async () => {
557 const scrolled = new Promise<void>((resolve) =>
558 scroller.addEventListener("scroll", () => resolve(), { once: true }),
559 );
560 scroller.scrollTop = scroller.scrollHeight;
561 await scrolled;
562 });
563
564 await vi.waitFor(() => {
565 expect(title.element().closest("[inert]")).not.toBeNull();
566 expect(scroller.clientHeight).toBeGreaterThan(expandedHeight);
567 expect(scroller.scrollTop).toBeGreaterThan(0);
568 expect(scroller.scrollTop).toBeLessThan(expandedBottom);
569 expect(scroller.scrollTop).toBe(scroller.scrollHeight - scroller.clientHeight);
570 });
571
572 await act(async () => {
573 const scrolled = new Promise<void>((resolve) =>
574 scroller.addEventListener("scroll", () => resolve(), { once: true }),
575 );
576 scroller.scrollTop = 0;
577 await scrolled;
578 });
579 await vi.waitFor(() => expect(title.element().closest("[inert]")).toBeNull());
580});
581
582it("shows the current checkout recovery detail on the first failure and on retry", async () => {
583 const first = new GitManagerError({
584 cwd: "/workspace",
585 operation: "preparePullRequestThread",
586 detail: "This PR branch is already checked out in the main repo. Use Local.",
587 });
588 const second = new GitCommandError({
589 cwd: "/workspace",
590 operation: "GitVcsDriver.createWorktree",
591 command: "git worktree add",
592 detail: "The worktree directory already exists. Choose another directory.",
593 });
594 await render();
595
596 for (const [index, error] of [first, second].entries()) {
597 prepareThread.mockImplementationOnce(async () => {
598 checkoutState.error = error;
599 return { _tag: "Failure", cause: Cause.fail(error) };
600 });
601 await page.getByRole("button", { name: "Check out", exact: true }).click();
602 await page.getByRole("menuitem", { name: /In a separate worktree/ }).click();
603 await vi.waitFor(() => expect(updateToast).toHaveBeenCalledTimes(index + 1));
604 }
605 expect(updateToast.mock.calls.map(([, toast]) => toast.description)).toEqual([
606 expect.stringContaining(first.detail),
607 second.detail,
608 ]);
609});