Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PullRequestDetailPanel.browser.test.tsx

821 lines28.8 KB

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";
18import { selectActiveRightPanelSurface, useRightPanelStore } from "~/rightPanelStore";
19import { RightPanelSurfaceContent } from "../chat/RightPanelSurfaceContent";
20​
21import "~/index.css";
22​
23const {
24 newThread,
25 prepareThread,
26 refresh,
27 update,
28 addToast,
29 updateToast,
30 checkoutState,
31 hostCommand,
32 queries,
33} = vi.hoisted(() => ({
34 hostCommand: vi.fn(),
35 queries: { diff: undefined as unknown },
36 newThread: vi.fn(),
37 prepareThread: vi.fn(),
38 refresh: vi.fn(),
39 update: vi.fn(),
40 addToast: vi.fn(),
41 updateToast: vi.fn(),
42 checkoutState: { error: null as Error | null },
43}));
44​
45vi.mock(import("~/state/session"), async (original) => ({
46 ...(await original()),
47 useEnvironmentScope: () => true,
48 readEnvironmentScope: () => true,
49}));
50vi.mock(import("~/hooks/useSettings"), async (original) => ({
51 ...(await original()),
52 useEnvironmentSettings: (() => undefined) as never,
53}));
54vi.mock(import("~/hooks/useHandleNewThread"), async (original) => ({
55 ...(await original()),
56 useNewThreadHandler: (() => newThread) as never,
57}));
58vi.mock(import("~/lib/sourceControlActions"), async (original) => ({
59 ...(await original()),
60 usePreparePullRequestThreadAction: (() => ({
61 run: prepareThread,
62 isAllowed: true,
63 error: checkoutState.error,
64 })) as never,
65}));
66vi.mock(import("~/state/use-atom-command"), async (original) => ({
67 ...(await original()),
68 useAtomCommand: ((command: unknown) => (command === "update" ? update : hostCommand)) as never,
69}));
70vi.mock(import("~/state/pullRequests"), async (original) => {
71 const actual = await original();
72 const { Atom } = await import("effect/reactivity");
73 const cannotWriteGuides = Atom.make(false);
74 const diff = Atom.make(null);
75 queries.diff = diff;
76 return {
77 ...actual,
78 pullRequestEnvironment: {
79 ...actual.pullRequestEnvironment,
80 detail: (() => "detail") as never,
81 diff: (() => diff) as never,
82 activity: (() => "activity") as never,
83 update: "update" as never,
84 reviewGuide: (() => "review-guide") as never,
85 generateReviewGuide: {
86 ...actual.pullRequestEnvironment.generateReviewGuide,
87 permissionAtom: () => cannotWriteGuides,
88 },
89 },
90 };
91});
92vi.mock(import("~/state/query"), async (original) => ({
93 ...(await original()),
94 useEnvironmentQuery: ((query: unknown) => ({
95 data:
96 query === "detail"
97 ? (activityDetail ?? currentDetail)
98 : query === "activity"
99 ? activityDetail
100 : query === queries.diff
101 ? diff
102 : null,
103 dataUpdatedAt: 0,
104 failure: null,
105 isPending: false,
106 isSuccess: true,
107 error: null,
108 refresh,
109 })) as never,
110}));
111vi.mock(import("~/state/usePullRequestStack"), async (original) => ({
112 ...(await original()),
113 usePullRequestStack: (() => ({
114 data: null,
115 isSuccess: true,
116 isPending: false,
117 error: null,
118 refresh,
119 })) as never,
120}));
121// Action and scroll tests use stand-ins; activity tests render the real Summary.
122vi.mock(import("./PullRequestSummaryTab"), async (original) => {
123 const actual = await original();
124 return {
125 ...actual,
126 PullRequestSummaryTab: ((props: ComponentProps<typeof actual.PullRequestSummaryTab>) => {
127 if (activityDetail !== null) return <actual.PullRequestSummaryTab {...props} />;
128 const { onFixFinding, scrollerRef } = props;
129 return (
130 <div ref={scrollerRef} data-testid="summary-scroller" className="h-full overflow-y-auto">
131 <button
132 type="button"
133 onClick={() =>
134 onFixFinding?.({
135 kind: "check",
136 check: {
137 name: "Unit tests",
138 status: "failure",
139 description: "Test failed",
140 url: null,
141 },
142 })
143 }
144 >
145 Fix check
146 </button>
147 <div data-testid="nested-scroller" className="h-40 overflow-y-auto">
148 <div className="h-[2000px]" />
149 </div>
150 <div className="h-[3000px]" />
151 </div>
152 );
153 }) as never,
154 };
155});
156vi.mock(import("../ui/toast"), async (original) => {
157 const actual = await original();
158 return {
159 ...actual,
160 toastManager: { ...actual.toastManager, add: addToast, update: updateToast } as never,
161 };
162});
163​
164import { PullRequestDetailPanel } from "./PullRequestDetailPanel";
165import { pullRequestPanelContext } from "./pullRequestDetail.logic";
166import { usePullRequestReviewStore } from "./pullRequestReviewStore";
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​
220let currentDetail = detail;
221let activityDetail: PullRequestDetailView | null = null;
222​
223// Enough lines to exercise the panel's title folding with the real virtualized Code tab.
224const diff = {
225 patch: [
226 "diff --git a/a.ts b/a.ts",
227 "new file mode 100644",
228 "--- /dev/null",
229 "+++ b/a.ts",
230 "@@ -0,0 +1,100 @@",
231 "+broken()",
232 ...Array.from({ length: 99 }, (_, index) => `+// line ${index + 2}`),
233 "",
234 ].join("\n"),
235 truncated: false,
236 nextCursor: null,
237};
238​
239const threadRef: ScopedThreadRef = {
240 environmentId: EnvironmentId.make("env-1"),
241 threadId: ThreadId.make("thread-1"),
242};
243const draftId = DraftId.make("draft-1");
244const newDraftId = DraftId.make("new-draft");
245const shortcutContext = () => ({
246 terminalFocus: false,
247 terminalOpen: false,
248 previewFocus: false,
249 previewOpen: false,
250 isWeb: true,
251 isDesktop: false,
252});
253​
254const roots: Root[] = [];
255​
256function render(props: Partial<ComponentProps<typeof PullRequestDetailPanel>> = {}) {
257 const container = document.createElement("div");
258 container.className = "flex h-[700px] w-[900px]";
259 document.body.append(container);
260 const root = createRoot(container);
261 roots.push(root);
262 return act(async () =>
263 root.render(
264 <PullRequestDetailPanel
265 environmentId={threadRef.environmentId}
266 reference={detail}
267 context="page"
268 shortcutsEnabled={false}
269 getShortcutContext={shortcutContext}
270 {...props}
271 />,
272 ),
273 );
275​
276beforeEach(() => {
277 activityDetail = null;
278 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
279 currentDetail = detail;
280 useComposerDraftStore.setState({ draftsByThreadKey: {} });
281 useRightPanelStore.setState({ byThreadKey: {} });
282 usePullRequestReviewStore.setState({ drafts: {}, summaries: {} });
283 hostCommand.mockReset();
284 newThread
285 .mockReset()
286 .mockResolvedValue({ draftId: newDraftId, threadId: ThreadId.make("new-thread") });
287 addToast.mockReset().mockReturnValue("checkout-toast");
288 updateToast.mockReset();
289 checkoutState.error = null;
290 prepareThread.mockReset().mockResolvedValue({
291 _tag: "Success",
292 value: { branch: "feature", worktreePath: "/workspace/pr" },
293 });
294 update.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
295});
296afterEach(async () => {
297 for (const root of roots.splice(0)) await act(async () => root.unmount());
298 document.body.replaceChildren();
299 vi.unstubAllGlobals();
300});
301​
302const surface = { projectId: detail.projectId, repository: detail.repository, number: 1 };
303const link = (number: number, source: ThreadPullRequestLink["source"]): ThreadPullRequestLink => ({
304 host: "github.com",
305 repository: detail.repository,
306 number,
307 url: `https://github.com/${detail.repository}/pull/${number}`,
308 source,
309 linkedAt: "2026-09-01T00:00:00Z",
310 snapshot: null,
311 stack: null,
312});
313const stackThread = {
314 projectId: detail.projectId,
315 pullRequests: [link(3, "manual"), link(2, "stack"), link(1, "stack")],
316 linkedPullRequest: { ...surface, number: 3, url: link(3, "manual").url },
317};
318const unrelatedThread = {
319 projectId: detail.projectId,
320 pullRequests: [link(9, "created")],
321 linkedPullRequest: { ...surface, number: 9, url: link(9, "created").url },
322};
323​
324const tab = (name: string) => page.getByRole("button", { name, exact: true });
325​
326const selectionDraft = () => page.getByRole("textbox", { name: "Comment on lines a.ts:1" });
327​
328async function selectFirstLine() {
329 const line = page.getByText("broken()", { exact: true });
330 await expect.element(line).toBeVisible();
331 const host = line.element().getRootNode() as ShadowRoot;
332 const gutter = host.querySelector<HTMLElement>('[data-column-number="1"]')!;
333 await userEvent.click(gutter);
335​
336it.each([
337 { isComposing: true, keyCode: 13 },
338 { isComposing: false, keyCode: 229 },
339])("does not save the PR title during IME composition (%j)", async ({ isComposing, keyCode }) => {
340 await render();
341 await page.getByRole("button", { name: "Edit title" }).click();
342 const titleInput = page.getByRole("textbox", { name: "Pull request title" });
343 const title = "日本語のタイトル";
344 await titleInput.fill(title);
345 const pressEnter = (init: KeyboardEventInit) =>
346 act(async () => {
347 titleInput
348 .element()
349 .dispatchEvent(
350 new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true, ...init }),
351 );
352 });
353​
354 await pressEnter({ isComposing, keyCode });
355 expect(update).not.toHaveBeenCalled();
356 await expect.element(titleInput).toHaveValue(title);
357​
358 await pressEnter({ keyCode: 13 });
359 expect(update).toHaveBeenCalledExactlyOnceWith({
360 environmentId: threadRef.environmentId,
361 input: { ...surface, title },
362 });
363 await expect.element(titleInput).not.toBeInTheDocument();
364});
365​
366async function runAction(action: string) {
367 if (action === "Add to agent") {
368 await tab("Code").click();
369 await page.getByRole("button", { name: "Expand all files", exact: true }).click();
370 await selectFirstLine();
371 const draft = page.getByRole("textbox", { name: "Comment on lines a.ts:1" });
372 await expect.element(draft).toBeVisible();
373 expect(
374 page.getByRole("button", { name: "Add to review", exact: true }).elements(),
375 ).toHaveLength(0);
376 await draft.fill("Fix this line");
377 }
378 if (["Ask a question", "Explain this PR"].includes(action) || action.startsWith("Fix findings")) {
379 await page.getByRole("button", { name: "More pull request actions" }).click();
380 // Menu items carry a description under their label.
381 await page.getByRole("menuitem", { name: new RegExp(`^${action}`) }).click();
382 return;
383 }
384 await page.getByRole("button", { name: action, exact: true }).click();
386​
387describe.each([
388 ["own PR, a lower layer of the thread's stack", stackThread, threadRef],
389 ["another PR beside the current thread", unrelatedThread, threadRef],
390 ["PR beside an unsent draft", null, draftId],
391 ["standalone PR page", null, undefined],
392] as const)("%s", (_name, thread, target) => {
393 const context = thread ? pullRequestPanelContext(thread, surface) : "page";
394 const renderPanel = () =>
395 render({ context, ...(target ? { composerDraftTarget: target, threadRef } : {}) });
396​
397 it(`${thread === stackThread ? "hides" : "offers"} the checkout`, async () => {
398 await renderPanel();
399 await expect.element(page.getByText("Test pull request").first()).toBeVisible();
400 expect(page.getByRole("button", { name: "Check out" }).elements()).toHaveLength(
401 thread === stackThread ? 0 : 1,
402 );
403 });
404​
405 it.each([
406 "Resolve conflicts",
407 "Ask a question",
408 "Explain this PR",
409 "Fix findings in this thread",
410 "Fix check",
411 "Add to agent",
412 ])("%s writes to the correct composer", async (action) => {
413 // Cover both a host without inline comments and an account that cannot write them.
414 currentDetail =
415 thread === stackThread
416 ? {
417 ...detail,
418 capabilities: {
419 ...detail.capabilities,
420 review: { ...detail.capabilities.review, inlineComment: true },
421 },
422 }
423 : { ...detail, viewerPermissions: { ...detail.viewerPermissions, comment: true } };
424 if (target) useComposerDraftStore.getState().setPrompt(target, "Keep my draft");
425 await renderPanel();
426 await runAction(target ? action : action.replace("in this thread", "in a thread"));
427 const draft = () => useComposerDraftStore.getState().getComposerDraft(target ?? newDraftId);
428 await vi.waitFor(() => {
429 if (action === "Resolve conflicts")
430 expect(draft()?.prompt).toContain("resolve every conflict");
431 else if (action === "Fix check") expect(draft()?.prompt).toContain("Fix the failing check");
432 else if (action.startsWith("Fix findings"))
433 expect(draft()?.prompt).toContain("Fix the actionable findings");
434 else expect(draft()?.reviewComments?.length).toBeGreaterThan(0);
435 });
436 if (action === "Add to agent") {
437 expect(draft()?.prompt).toContain("Fix this line");
438 expect(draft()?.reviewComments).toEqual(
439 expect.arrayContaining([
440 expect.objectContaining({
441 filePath: "a.ts",
442 diff: expect.stringContaining("+broken()"),
443 startIndex: 0,
444 endIndex: 0,
445 }),
446 ]),
447 );
448 expect(usePullRequestReviewStore.getState().drafts).toEqual({});
449 expect(hostCommand).not.toHaveBeenCalled();
450 await expect
451 .element(page.getByRole("textbox", { name: "Comment on lines a.ts:1" }))
452 .not.toBeInTheDocument();
453 }
454 if (target) {
455 expect(draft()?.prompt).toContain("Keep my draft");
456 expect(newThread).not.toHaveBeenCalled();
457 expect(prepareThread).not.toHaveBeenCalled();
458 } else {
459 expect(newThread).toHaveBeenCalled();
460 }
461 });
462});
463​
464it("offers both selection actions and queues a permitted host review locally", async () => {
465 currentDetail = {
466 ...detail,
467 capabilities: {
468 ...detail.capabilities,
469 review: { ...detail.capabilities.review, inlineComment: true },
470 },
471 viewerPermissions: { ...detail.viewerPermissions, comment: true },
472 };
473 await render({ composerDraftTarget: draftId, threadRef });
474 await tab("Code").click();
475 await page.getByRole("button", { name: "Expand all files", exact: true }).click();
476 await selectFirstLine();
477 const addToReview = page.getByRole("button", { name: "Add to review", exact: true });
478 await expect.element(addToReview).toBeVisible();
479 await expect
480 .element(page.getByRole("button", { name: "Add to agent", exact: true }))
481 .toBeVisible();
482 await selectionDraft().fill("Fix this line before merging");
483 await addToReview.click();
484 await expect.element(selectionDraft()).not.toBeInTheDocument();
485 expect(Object.values(usePullRequestReviewStore.getState().drafts).flat()).toEqual([
486 expect.objectContaining({ path: "a.ts", body: "Fix this line before merging" }),
487 ]);
488 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.reviewComments ?? []).toEqual(
489 [],
490 );
491 expect(hostCommand).not.toHaveBeenCalled();
492});
493​
494it("cancels an agent-only selection and submits a fresh one with the keyboard without a host review", async () => {
495 await render({ composerDraftTarget: draftId, threadRef });
496 await tab("Code").click();
497 await page.getByRole("button", { name: "Expand all files", exact: true }).click();
498 await selectFirstLine();
499 await selectionDraft().fill("Discard this request");
500 await page.getByRole("button", { name: "Cancel", exact: true }).click();
501 await expect.element(selectionDraft()).not.toBeInTheDocument();
502 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.reviewComments ?? []).toEqual(
503 [],
504 );
505 expect(usePullRequestReviewStore.getState().drafts).toEqual({});
506 expect(hostCommand).not.toHaveBeenCalled();
507​
508 await selectFirstLine();
509 await expect.element(selectionDraft()).toHaveValue("");
510 await selectionDraft().fill("Fix this line");
511 await userEvent.keyboard("{Control>}{Enter}{/Control}");
512 await expect.element(selectionDraft()).not.toBeInTheDocument();
513 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.prompt).toContain(
514 "Fix this line",
515 );
516 expect(usePullRequestReviewStore.getState().drafts).toEqual({});
517 expect(hostCommand).not.toHaveBeenCalled();
518});
519​
520it("folds the title only for the active tab's own scroller", async () => {
521 await render();
522 const title = page.getByRole("heading", { level: 1, name: "Test pull request" });
523 await expect.element(title).toBeVisible();
524 const titleFold = () => title.element().closest("[inert]") !== null;
525 const scrollTo = async (testId: string, top: number) => {
526 const scroller =
527 testId === "code-scroller"
528 ? document.querySelector<HTMLElement>(".\\@container.overflow-auto")!
529 : (page.getByTestId(testId).element() as HTMLElement);
530 await act(async () => {
531 scroller.scrollTop = top;
532 scroller.dispatchEvent(new Event("scroll"));
533 });
534 return scroller;
535 };
536​
537 await scrollTo("nested-scroller", 600);
538 expect(titleFold()).toBe(false);
539​
540 const summary = await scrollTo("summary-scroller", 600);
541 await vi.waitFor(() => expect(titleFold()).toBe(true));
542 // Folding the header keeps the content under the reader's eye.
543 expect(summary.scrollTop).toBeLessThan(600);
544​
545 await scrollTo("summary-scroller", 0);
546 await vi.waitFor(() => expect(titleFold()).toBe(false));
547 await scrollTo("summary-scroller", 600);
548 await vi.waitFor(() => expect(titleFold()).toBe(true));
549​
550 await tab("Code").click();
551 await page.getByRole("button", { name: "Expand all files", exact: true }).click();
552 await expect.element(page.getByText("broken()", { exact: true })).toBeVisible();
553 await vi.waitFor(() => expect(titleFold()).toBe(false));
554 await scrollTo("code-scroller", 600);
555 await vi.waitFor(() => expect(titleFold()).toBe(true));
556​
557 await tab("Summary").click();
558 await vi.waitFor(() => expect(titleFold()).toBe(true));
559 await scrollTo("summary-scroller", 0);
560 await vi.waitFor(() => expect(titleFold()).toBe(false));
561 await tab("Code").click();
562 await vi.waitFor(() => expect(titleFold()).toBe(true));
563});
564​
565it("restores the selected PR tab when switching threads and remounting the right panel", async () => {
566 const otherThread = { ...threadRef, threadId: ThreadId.make("thread-2") };
567 useRightPanelStore.getState().openPullRequest(threadRef, surface);
568 useRightPanelStore.getState().openPullRequest(otherThread, surface);
569 const codeTab = () => page.getByRole("button", { name: "Expand all files", exact: true });
570 const container = document.createElement("div");
571 container.className = "flex h-[700px] w-[900px]";
572 document.body.append(container);
573 const root = createRoot(container);
574 roots.push(root);
575 const show = (ref: ScopedThreadRef) => {
576 const selected = selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, ref);
577 return act(async () => {
578 root.render(
579 <RightPanelSurfaceContent
580 surface={selected}
581 activeSurfaceId={selected?.id ?? null}
582 threadRef={ref}
583 environmentId={ref.environmentId}
584 visible
585 composerDraftTarget={ref}
586 keybindings={[]}
587 configuredPreviewUrls={[]}
588 workspaceMutationId={null}
589 getShortcutContext={shortcutContext}
590 onSendAnnotation={() => {}}
591 onCloseSurface={() => {}}
592 terminal={{
593 launchContext: null,
594 focusRequestId: 0,
595 keybindings: [],
596 onAddTerminalContext: () => {},
597 onSplitTerminal: () => {},
598 onSplitTerminalVertical: () => {},
599 onNewTerminal: () => {},
600 onActiveTerminalChange: () => {},
601 onCloseTerminal: () => {},
602 }}
603 pullRequest={{
604 capabilityKnown: true,
605 supported: true,
606 projectId: detail.projectId,
607 pullRequests: [],
608 linkedPullRequest: null,
609 branchPullRequest: null,
610 onBack: undefined,
611 }}
612 files={{
613 projectName: null,
614 workspaceRoot: undefined,
615 availableEditors: [],
616 pendingSurfaceIds: new Set(),
617 onOpenFile: () => {},
618 onPendingChange: () => {},
619 }}
620 />,
621 );
622 });
623 };
624​
625 await show(threadRef);
626 await expect.element(page.getByTestId("summary-scroller")).toBeVisible();
627 await tab("Code").click();
628 await expect.element(codeTab()).toBeVisible();
629 await show(otherThread);
630 await expect.element(page.getByTestId("summary-scroller")).toBeVisible();
631 await show(threadRef);
632 await expect.element(codeTab()).toBeVisible();
633​
634 useRightPanelStore
635 .getState()
636 .openPullRequest(threadRef, { ...surface, projectId: "other-project" });
637 await show(threadRef);
638 await expect.element(page.getByTestId("summary-scroller")).toBeVisible();
639 useRightPanelStore.getState().openPullRequest(threadRef, surface);
640 await show(threadRef);
641 await expect.element(codeTab()).toBeVisible();
642​
643 await act(async () => root.render(null));
644 useRightPanelStore.getState().openPullRequest(threadRef, { ...surface, url: detail.url });
645 await show(threadRef);
646 await expect.element(codeTab()).toBeVisible();
647 await tab("Summary").click();
648 await show(otherThread);
649 await show(threadRef);
650 await expect.element(page.getByTestId("summary-scroller")).toBeVisible();
651});
652​
653it("stays collapsed at the bottom after native scroll clamping and reopens at the top", async () => {
654 await render();
655 const title = page.getByRole("heading", { level: 1, name: "Test pull request" });
656 await expect.element(title).toBeVisible();
657 const scroller = page.getByTestId("summary-scroller").element() as HTMLElement;
658 const content = scroller.lastElementChild as HTMLElement;
659 // Leave only a short scroll range so folding the header makes the browser clamp it.
660 content.style.height = `${scroller.clientHeight - 24}px`;
661 const expandedHeight = scroller.clientHeight;
662 const expandedBottom = scroller.scrollHeight - scroller.clientHeight;
663​
664 await act(async () => {
665 const scrolled = new Promise<void>((resolve) =>
666 scroller.addEventListener("scroll", () => resolve(), { once: true }),
667 );
668 scroller.scrollTop = scroller.scrollHeight;
669 await scrolled;
670 });
671​
672 await vi.waitFor(() => {
673 expect(title.element().closest("[inert]")).not.toBeNull();
674 expect(scroller.clientHeight).toBeGreaterThan(expandedHeight);
675 expect(scroller.scrollTop).toBeGreaterThan(0);
676 expect(scroller.scrollTop).toBeLessThan(expandedBottom);
677 expect(scroller.scrollTop).toBe(scroller.scrollHeight - scroller.clientHeight);
678 });
679​
680 await act(async () => {
681 const scrolled = new Promise<void>((resolve) =>
682 scroller.addEventListener("scroll", () => resolve(), { once: true }),
683 );
684 scroller.scrollTop = 0;
685 await scrolled;
686 });
687 await vi.waitFor(() => expect(title.element().closest("[inert]")).toBeNull());
688});
689​
690it("shows the current checkout recovery detail on the first failure and on retry", async () => {
691 const first = new GitManagerError({
692 cwd: "/workspace",
693 operation: "preparePullRequestThread",
694 detail: "This PR branch is already checked out in the main repo. Use Local.",
695 });
696 const second = new GitCommandError({
697 cwd: "/workspace",
698 operation: "GitVcsDriver.createWorktree",
699 command: "git worktree add",
700 detail: "The worktree directory already exists. Choose another directory.",
701 });
702 await render();
703​
704 for (const [index, error] of [first, second].entries()) {
705 prepareThread.mockImplementationOnce(async () => {
706 checkoutState.error = error;
707 return { _tag: "Failure", cause: Cause.fail(error) };
708 });
709 await page.getByRole("button", { name: "Check out", exact: true }).click();
710 await page.getByRole("menuitem", { name: /In a separate worktree/ }).click();
711 await vi.waitFor(() => expect(updateToast).toHaveBeenCalledTimes(index + 1));
712 }
713 expect(updateToast.mock.calls.map(([, toast]) => toast.description)).toEqual([
714 expect.stringContaining(first.detail),
715 second.detail,
716 ]);
717});
718​
719it("keeps discussion counts and Timeline expansion in sync with activity refreshes", async () => {
720 activityDetail = {
721 ...detail,
722 provider: SourceControlProviderKind.make("gitlab"),
723 url: "https://gitlab.com/owner/repo/-/merge_requests/1",
724 comments: [],
725 commentCount: 0,
726 commentsTruncated: true,
727 reviewThreads: [
728 {
729 id: "discussion-1",
730 path: "src/index.ts",
731 line: 1,
732 side: "right",
733 isResolved: false,
734 isOutdated: false,
735 comments: [
736 {
737 id: "note-1",
738 author: detail.author,
739 body: "Discussion finding",
740 createdAt: "2026-09-01T00:01:00Z",
741 url: "https://gitlab.com/owner/repo/-/merge_requests/1#note_1",
742 },
743 {
744 id: "note-2",
745 author: detail.author,
746 body: "Discussion reply",
747 createdAt: "2026-09-01T00:02:00Z",
748 url: "https://gitlab.com/owner/repo/-/merge_requests/1#note_2",
749 },
750 ],
751 },
752 ],
753 };
754 await render({ reference: activityDetail });
755 await expect.element(page.getByText("Discussion finding", { exact: true })).toBeVisible();
756 await expect.element(page.getByText("Discussion reply", { exact: true })).toBeVisible();
757 expect
758 .soft(page.getByRole("button", { name: /^Comments \(/ }).element().textContent)
759 .toBe("Comments (2)");
760 const warning = page.getByText(/open it on the host to read the rest/).element().textContent;
761 expect.soft(warning).toMatch(/\b2\b/);
762 expect.soft(warning).not.toMatch(/most recent/i);
763​
764 await tab("Timeline").click();
765 await expect.element(page.getByText("Discussion finding", { exact: true }).last()).toBeVisible();
766 await expect.element(page.getByText("Discussion reply", { exact: true }).last()).toBeVisible();
767 expect.soft(page.getByLabelText(/^[0-9]+ comments?$/).element().textContent).toBe("2");
768​
769 const threadToggle = page.getByRole("button", { name: /^src\/index\.ts:1/ });
770 const expectThread = (expanded: boolean, status: string | null) => {
771 const toggle = threadToggle.element();
772 if (status) expect(toggle.textContent).toContain(status);
773 else expect(toggle.textContent).not.toMatch(/Resolved|Review dismissed/);
774 const visibleBody = (toggle.parentElement as HTMLElement).innerText;
775 expect({
776 expanded: toggle.getAttribute("aria-expanded"),
777 findingVisible: visibleBody.includes("Discussion finding"),
778 replyVisible: visibleBody.includes("Discussion reply"),
779 }).toEqual({
780 expanded: String(expanded),
781 findingVisible: expanded,
782 replyVisible: expanded,
783 });
784 };
785 const refreshActivity = async (isResolved: boolean, reviewState: string | null = null) => {
786 await tab("Code").click();
787 await expect
788 .element(page.getByRole("button", { name: "Expand all files", exact: true }))
789 .toBeVisible();
790 const current = activityDetail!;
791 activityDetail = {
792 ...current,
793 comments: current.reviewThreads.flatMap((thread) =>
794 thread.comments.map((comment) => ({
795 ...comment,
796 kind: "review-comment" as const,
797 path: thread.path,
798 reviewState,
799 })),
800 ),
801 reviewThreads: current.reviewThreads.map((thread) => ({ ...thread, isResolved })),
802 };
803 await tab("Timeline").click();
804 };
805​
806 expectThread(true, null);
807 await refreshActivity(true);
808 expectThread(false, "Resolved");
809 await threadToggle.click();
810 expectThread(true, "Resolved");
811 await refreshActivity(true);
812 expectThread(true, "Resolved");
813 await threadToggle.click();
814 expectThread(false, "Resolved");
815 await refreshActivity(false);
816 expectThread(true, null);
817 await refreshActivity(false, "DISMISSED");
818 expectThread(false, "Review dismissed");
819 await refreshActivity(false);
820 expectThread(true, null);
821});