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

PullRequestSummaryTab.browser.test.tsx

579 lines20.1 KB

1import {
2 DEFAULT_CLIENT_SETTINGS,
3 SourceControlProviderKind,
4 type ClientSettings,
5} from "@t3tools/contracts";
6import { EnvironmentId, ProjectId, type PullRequestDetailView } from "@t3tools/contracts";
7import { expect, it, vi } from "vite-plus/test";
8import { userEvent } from "vite-plus/test/browser";
9​
10const state = vi.hoisted(() => ({
11 update: vi.fn(),
12 canUpdate: true,
13 timestampFormat: "locale" as "locale" | "12-hour" | "24-hour",
14 openLink: vi.fn(async () => {}),
15}));
16​
17vi.mock(import("~/browser/useOpenLink"), () => ({ useOpenLink: () => state.openLink }));
18​
19vi.mock(import("~/state/use-atom-command"), async (original) => ({
20 ...(await original()),
21 useAtomCommand: (() => state.update) as never,
22}));
23vi.mock(import("~/state/session"), async (original) => ({
24 ...(await original()),
25 readEnvironmentScope: () => true,
26 useEnvironmentScope: () => true,
27}));
28vi.mock(import("~/hooks/useSettings"), async (original) => ({
29 ...(await original()),
30 useClientSettings: ((select?: (settings: ClientSettings) => unknown) => {
31 const settings = { ...DEFAULT_CLIENT_SETTINGS, timestampFormat: state.timestampFormat };
32 return select ? select(settings) : settings;
33 }) as never,
34}));
35vi.mock(import("~/state/pullRequests"), async (original) => {
36 const actual = await original();
37 const { Atom } = await import("effect/reactivity");
38 const allowed = Atom.make(true);
39 const denied = Atom.make(false);
40 return {
41 ...actual,
42 pullRequestEnvironment: {
43 ...actual.pullRequestEnvironment,
44 update: {
45 ...actual.pullRequestEnvironment.update,
46 permissionAtom: () => (state.canUpdate ? allowed : denied),
47 },
48 },
49 };
50});
51​
52function setup() {
53 state.update.mockReset();
54 state.update.mockResolvedValue({ _tag: "Success", value: undefined });
55 state.canUpdate = true;
56 state.timestampFormat = "locale";
57 state.openLink.mockClear();
59​
60import "~/index.css";
61import { workspaceAreaProps } from "~/lib/workspaceFocus";
62import { act, render as renderUi } from "../../../test/render";
63import { PullRequestSummaryTab } from "./PullRequestSummaryTab";
64​
65const detail: PullRequestDetailView = {
66 provider: SourceControlProviderKind.make("github"),
67 projectId: ProjectId.make("project"),
68 projectTitle: "Project",
69 workspaceRoot: "/workspace",
70 repository: "owner/repo",
71 number: 1,
72 title: "Test pull request",
73 body: "Original description",
74 url: "https://github.com/owner/repo/pull/1",
75 author: { login: "author", name: null, avatarUrl: null },
76 viewer: "author",
77 state: "open",
78 isDraft: false,
79 mergeability: "mergeable",
80 additions: 1,
81 deletions: 0,
82 changedFiles: 1,
83 headBranch: "feature",
84 baseBranch: "main",
85 createdAt: "2026-09-01T00:00:00Z",
86 updatedAt: "2026-09-01T00:00:00Z",
87 mergedAt: null,
88 closedAt: null,
89 reviewers: [],
90 labels: [],
91 checks: [{ name: "Unit tests", status: "success", description: null, url: null }],
92 comments: [],
93 commentCount: 0,
94 commentsTruncated: false,
95 reviewThreads: [],
96 commits: [],
97 mergeCapabilities: { merge: false, squash: false, rebase: false },
98 capabilities: {
99 diff: true,
100 comment: true,
101 search: true,
102 actions: [],
103 mergeMethods: [],
104 review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
105 reviewers: { request: false, listCandidates: false },
106 edit: { changeRequest: true, comment: true },
107 },
108 viewerPermissions: {
109 actions: [],
110 comment: true,
111 resolve: false,
112 verdicts: [],
113 requestReviewers: false,
114 },
115};
116​
117// The comment filter persists to localStorage, so tests that touch it start and end empty.
118​
119const tab = (value = detail, revealUrl?: string) => (
120 <PullRequestSummaryTab
121 scrollerRef={() => {}}
122 revealUrl={revealUrl}
123 environmentId={EnvironmentId.make("environment")}
124 threadRef={null}
125 reference={value}
126 detail={value}
127 observedAt={value.observedAt}
128 activityPending={false}
129 activityError={null}
130 onRefresh={() => {}}
131 />
132);
133​
134async function render(value = detail) {
135 const screen = await renderUi(tab(value));
136 const { container } = screen;
137 const heading = (title: string) => {
138 const section = container.querySelector(`section[aria-label="${title}"]`);
139 expect(section, `section ${title}`).not.toBeNull();
140 return [...section!.querySelectorAll("button")].find(
141 (button) => button.querySelector("span")?.textContent === title,
142 )!;
143 };
144 return Object.assign(screen, {
145 click: (title: string) => act(async () => heading(title).click()),
146 expanded: (title: string) => heading(title).getAttribute("aria-expanded"),
147 visibleText: () => container.innerText,
148 });
150​
151it("keeps an unsaved description when collapsed and reopened, and after a failed save", async () => {
152 setup();
153 state.update.mockResolvedValue({ _tag: "Failure", cause: new Error("offline") });
154 await using screen = await render();
155 await act(async () =>
156 screen.container.querySelector<HTMLButtonElement>('[aria-label="Edit description"]')!.click(),
157 );
158 const textarea = screen.container.querySelector("textarea")!;
159 await userEvent.clear(textarea);
160 await userEvent.type(textarea, "Unsaved description");
161 await screen.click("Description");
162 expect(screen.expanded("Description")).toBe("false");
163 await screen.click("Description");
164 expect(screen.container.querySelector("textarea")!.value).toBe("Unsaved description");
165​
166 await userEvent.click(screen.getByRole("button", { name: "Save" }));
167 expect(state.update).toHaveBeenCalledTimes(1);
168 await expect.element(screen.getByRole("button", { name: "Save" })).toBeEnabled();
169 expect(screen.container.querySelector("textarea")!.value).toBe("Unsaved description");
170});
171​
172it("ticks a description checkbox placed after an attachment and edits from the ticked body", async () => {
173 setup();
174 let finishSave = (_result: unknown) => {};
175 state.update.mockReturnValueOnce(new Promise((resolve) => (finishSave = resolve)));
176 const body = "Intro\n\nhttps://example.com/shot.png\n\n## Test plan\n- [ ] First\n- [ ] Second";
177 const ticked = body.replace("- [ ] Second", "- [x] Second");
178 await using screen = await render({ ...detail, body, observedAt: 1 });
179 const boxes = () => screen.container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]');
180 expect([...boxes()].map((box) => box.disabled)).toEqual([false, false]);
181​
182 await userEvent.click(boxes()[1]!);
183 expect(state.update).toHaveBeenCalledWith({
184 environmentId: "environment",
185 input: expect.objectContaining({ number: 1, body: ticked }),
186 });
187 expect([...boxes()].map((box) => box.checked)).toEqual([false, true]);
188 await act(async () => finishSave({ _tag: "Success", value: undefined }));
189​
190 // The host has not been read since the save, so the editor starts from the ticked body.
191 await act(async () =>
192 screen.container.querySelector<HTMLButtonElement>('[aria-label="Edit description"]')!.click(),
193 );
194 expect(screen.container.querySelector("textarea")!.value).toBe(ticked);
195});
196​
197it("leaves description checkboxes read-only without the right to edit it", async () => {
198 setup();
199 const body = "- [ ] First";
200 {
201 await using screen = await render({ ...detail, body, viewer: "someone-else" });
202 expect(
203 screen.container.querySelector<HTMLInputElement>('input[type="checkbox"]')!.disabled,
204 ).toBe(true);
205 }
206 state.canUpdate = false;
207 await using screen = await render({ ...detail, body });
208 expect(screen.container.querySelector<HTMLInputElement>('input[type="checkbox"]')!.disabled).toBe(
209 true,
210 );
211});
212​
213it("fixes an overview thread as its opening remark, since it has no line to attach", async () => {
214 setup();
215 const author = { login: "reviewer", name: null, avatarUrl: null };
216 const note = { author, createdAt: "2026-09-01T00:00:00Z", url: null };
217 const remark = {
218 ...note,
219 id: "10",
220 kind: "review-comment" as const,
221 body: "Mention the flag in the README",
222 path: null,
223 reviewState: null,
224 };
225 const onFixFinding = vi.fn();
226 const value: PullRequestDetailView = {
227 ...detail,
228 comments: [remark],
229 overviewThreads: [
230 {
231 id: "overview",
232 path: null,
233 line: null,
234 side: "right",
235 isResolved: false,
236 isOutdated: false,
237 comments: [{ ...note, id: "10", body: remark.body }],
238 },
239 ],
240 };
241 await using screen = await renderUi(
242 <PullRequestSummaryTab
243 scrollerRef={() => {}}
244 environmentId={EnvironmentId.make("environment")}
245 threadRef={null}
246 reference={value}
247 detail={value}
248 observedAt={value.observedAt}
249 activityPending={false}
250 activityError={null}
251 onRefresh={() => {}}
252 onFixFinding={onFixFinding}
253 />,
254 );
255​
256 await userEvent.click(screen.getByRole("button", { name: "Fix in a thread" }));
257 expect(onFixFinding).toHaveBeenCalledWith({ kind: "comment", comment: remark });
258});
259​
260it("shows a comment's exact time in the chosen 24-hour clock", async () => {
261 setup();
262 state.timestampFormat = "24-hour";
263 const createdAt = "2026-09-01T17:30:00Z";
264 const comment = {
265 id: "10",
266 kind: "review-comment" as const,
267 body: "A remark",
268 author: { login: "reviewer", name: null, avatarUrl: null },
269 createdAt,
270 url: null,
271 path: null,
272 reviewState: null,
273 };
274 await using screen = await render({ ...detail, comments: [comment], commentCount: 1 });
275​
276 await userEvent.hover(screen.container.querySelector(`time[datetime="${createdAt}"]`)!);
277 const expected = new Date(createdAt).toLocaleString(undefined, { hour12: false });
278 await vi.waitFor(() =>
279 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toBe(expected),
280 );
281});
282​
283it("keeps the chosen comment order when the right panel remounts the tab", async () => {
284 setup();
285 const comment = (id: string, createdAt: string) => ({
286 id,
287 kind: "review-comment" as const,
288 body: `Remark ${id}`,
289 author: { login: "reviewer", name: null, avatarUrl: null },
290 createdAt,
291 url: null,
292 path: null,
293 reviewState: null,
294 });
295 const value = {
296 ...detail,
297 comments: [comment("10", "2026-09-01T10:00:00Z"), comment("11", "2026-09-02T10:00:00Z")],
298 commentCount: 2,
299 };
300 {
301 await using screen = await render(value);
302 await userEvent.click(screen.getByRole("button", { name: "Show oldest comments first" }));
303 await expect
304 .element(screen.getByRole("button", { name: "Show newest comments first" }))
305 .toBeVisible();
306 }
307 // Switching to another right-panel tab unmounts the pull request surface.
308 await using screen = await render(value);
309 await expect
310 .element(screen.getByRole("button", { name: "Show newest comments first" }))
311 .toBeVisible();
312});
313​
314let resolvedConversationAttempt = 0;
315​
316it("keeps an opened resolved conversation open when the right panel remounts the tab", async () => {
317 setup();
318 // A fresh pull request per attempt, so a retry does not inherit the remembered open card.
319 resolvedConversationAttempt += 1;
320 const value: PullRequestDetailView = {
321 ...detail,
322 url: `https://github.com/owner/repo/pull/resolved-${resolvedConversationAttempt}`,
323 reviewThreads: [
324 {
325 id: "resolved-review",
326 path: "README.md",
327 line: 1,
328 side: "right",
329 isResolved: true,
330 isOutdated: false,
331 comments: [
332 {
333 id: "review-remark",
334 author: { login: "reviewer", name: null, avatarUrl: null },
335 body: Array.from({ length: 20 }, (_, index) => `Review paragraph ${index}`).join(
336 "\n\n",
337 ),
338 createdAt: "2026-09-01T00:00:00Z",
339 url: null,
340 },
341 ],
342 },
343 ],
344 };
345 localStorage.setItem(
346 "t3code:pull-request-comment-filter:v1",
347 JSON.stringify({ bots: false, resolved: true }),
348 );
349 try {
350 {
351 await using screen = await render(value);
352 await userEvent.click(screen.getByRole("button", { name: "Resolved", exact: true }));
353 await userEvent.click(screen.getByRole("button", { name: "Show full comment" }));
354 await expect.element(screen.getByRole("button", { name: "Show less" })).toBeVisible();
355 }
356 {
357 // Switching to another right-panel tab unmounts the pull request surface.
358 await using screen = await render(value);
359 const resolved = screen.getByRole("button", { name: "Resolved", exact: true });
360 await expect.element(resolved).toBeVisible();
361 expect(resolved.element().getAttribute("aria-expanded")).toBe("true");
362 await expect.element(screen.getByRole("button", { name: "Show less" })).toBeVisible();
363 await userEvent.click(resolved);
364 }
365 await using screen = await render(value);
366 const resolved = screen.getByRole("button", { name: "Resolved", exact: true });
367 await expect.element(resolved).toBeVisible();
368 expect(resolved.element().getAttribute("aria-expanded")).toBe("false");
369 } finally {
370 localStorage.removeItem("t3code:pull-request-comment-filter:v1");
371 }
372});
373​
374it("keeps a collapsed section closed when the right panel remounts the tab", async () => {
375 setup();
376 const value: PullRequestDetailView = {
377 ...detail,
378 url: "https://github.com/owner/repo/pull/section-open-state",
379 };
380 {
381 await using screen = await render(value);
382 const description = screen.getByRole("button", { name: "Description", exact: true });
383 await userEvent.click(description);
384 await expect.element(description).toHaveAttribute("aria-expanded", "false");
385 }
386 await using screen = await render(value);
387 await expect
388 .element(screen.getByRole("button", { name: "Description", exact: true }))
389 .toHaveAttribute("aria-expanded", "false");
390});
391​
392it("does not replay another pull request's Checks reveal onto a collapsed Checks section", async () => {
393 setup();
394 const prA: PullRequestDetailView = {
395 ...detail,
396 number: 1001,
397 url: "https://github.com/owner/repo/pull/1001",
398 };
399 const prB: PullRequestDetailView = {
400 ...detail,
401 number: 1002,
402 url: "https://github.com/owner/repo/pull/1002",
403 };
404 await using screen = await render(prA);
405 const checksButton = () => screen.getByRole("button", { name: "Checks", exact: true });
406​
407 await userEvent.click(checksButton());
408 await expect.element(checksButton()).toHaveAttribute("aria-expanded", "true");
409 await userEvent.click(checksButton());
410 await expect.element(checksButton()).toHaveAttribute("aria-expanded", "false");
411​
412 await screen.rerender(tab(prB, `${prB.url}/checks`));
413 await expect.element(checksButton()).toHaveAttribute("aria-expanded", "true");
414​
415 await screen.rerender(tab(prA));
416 await expect.element(checksButton()).toHaveAttribute("aria-expanded", "false");
417});
418​
419it("comes back at the scroll position it left when the right panel remounts the tab", async () => {
420 setup();
421 const body = Array.from({ length: 80 }, (_, index) => `Paragraph ${index}`).join("\n\n");
422 const value = { ...detail, body, url: "https://github.com/owner/repo/pull/2" };
423 const mount = async (shown = value) => {
424 const container = document.createElement("div");
425 container.className = "flex h-[300px]";
426 const screen = await renderUi(tab(shown), { container });
427 const scroller = container.querySelector<HTMLElement>("[data-pull-request-summary-scroll]")!;
428 return Object.assign(screen, { scroller });
429 };
430 {
431 await using screen = await mount();
432 screen.scroller.scrollTop = 500;
433 await vi.waitFor(() => expect(screen.scroller.scrollTop).toBe(500));
434 await act(async () => screen.scroller.dispatchEvent(new Event("scroll")));
435 }
436 // The tab can come back before the content that reached that position has loaded.
437 await using screen = await mount({ ...value, body: "Paragraph 0" });
438 await screen.rerender(tab(value));
439 await vi.waitFor(() => expect(screen.scroller.scrollTop).toBe(500));
440 await screen.unmount();
441 await using again = await mount();
442 expect(again.scroller.scrollTop).toBe(500);
443});
444​
445it("scrolls from the keyboard after a click inside it", async () => {
446 setup();
447 const body = Array.from({ length: 80 }, (_, index) => `Paragraph ${index}`).join("\n\n");
448 const container = document.createElement("div");
449 container.className = "flex h-[300px]";
450 await using screen = await renderUi(
451 // The panel area takes focus itself, so a click on plain text lands on it unless the tab can.
452 <div {...workspaceAreaProps("panel", 4, "Workspace panel")} className="flex min-w-0 flex-1">
453 {tab({ ...detail, body })}
454 </div>,
455 { container },
456 );
457 const scroller = container.querySelector<HTMLElement>("[data-pull-request-summary-scroll]")!;
458 await userEvent.click(screen.getByText("Paragraph 0", { exact: true }));
459 await userEvent.keyboard("{PageDown}");
460 await vi.waitFor(() => expect(scroller.scrollTop).toBeGreaterThan(0));
461});
462​
463it("opens comment timestamps through the link-target setting, not a popup", async () => {
464 setup();
465 const author = { login: "reviewer", name: null, avatarUrl: null };
466 const comment = (id: string, reviewState: string | null) => ({
467 id,
468 kind: "review" as const,
469 body: `Remark ${id}`,
470 author,
471 createdAt: `2026-09-0${id}T00:00:00Z`,
472 url: `${detail.url}#review-${id}`,
473 path: null,
474 reviewState,
475 });
476 // The dismissed review renders as a collapsed card; show it with the resolved filter on.
477 localStorage.setItem(
478 "t3code:pull-request-comment-filter:v1",
479 JSON.stringify({ bots: false, resolved: true }),
480 );
481 try {
482 await using screen = await render({
483 ...detail,
484 comments: [comment("1", null), comment("2", "DISMISSED")],
485 commentCount: 2,
486 });
487 for (const id of ["1", "2"]) {
488 const href = `${detail.url}#review-${id}`;
489 const link = screen.container.querySelector(`a[href="${href}"]`);
490 expect(link, href).not.toBeNull();
491 state.openLink.mockClear();
492 const click = new MouseEvent("click", { bubbles: true, cancelable: true });
493 link!.dispatchEvent(click);
494​
495 expect(click.defaultPrevented).toBe(true);
496 expect(state.openLink).toHaveBeenCalledOnce();
497 expect(state.openLink).toHaveBeenCalledWith(href, { event: expect.anything() });
498 }
499 } finally {
500 localStorage.removeItem("t3code:pull-request-comment-filter:v1");
501 }
502});
503​
504it("opens a comment author's profile through the link-target setting, not a popup", async () => {
505 setup();
506 await using screen = await render({
507 ...detail,
508 comments: [
509 {
510 id: "1",
511 kind: "issue-comment" as const,
512 body: "Looks good",
513 author: { login: "reviewer", name: null, avatarUrl: null },
514 createdAt: "2026-09-01T00:00:00Z",
515 url: null,
516 path: null,
517 reviewState: null,
518 },
519 ],
520 commentCount: 1,
521 });
522 const link = await vi.waitFor(() => {
523 const found = screen.container.querySelector('a[aria-label="Open reviewer\'s profile"]');
524 expect(found).not.toBeNull();
525 return found!;
526 });
527 const href = link.getAttribute("href")!;
528 const click = new MouseEvent("click", { bubbles: true, cancelable: true });
529 link.dispatchEvent(click);
530​
531 expect(click.defaultPrevented).toBe(true);
532 expect(state.openLink).toHaveBeenCalledOnce();
533 expect(state.openLink).toHaveBeenCalledWith(href, { event: expect.anything() });
534});
535​
536it("opens a thread's remaining replies through the link-target setting, not a popup", async () => {
537 setup();
538 await using screen = await render({
539 ...detail,
540 reviewThreads: [
541 {
542 id: "thread",
543 path: "a.ts",
544 line: 3,
545 side: "right",
546 isResolved: false,
547 isOutdated: false,
548 commentCount: 3,
549 comments: [
550 {
551 id: "comment",
552 body: "Please rename this",
553 author: { login: "reviewer", name: null, avatarUrl: null },
554 createdAt: "2026-09-01T00:00:00Z",
555 url: "https://github.com/owner/repo/pull/1#discussion_r1",
556 },
557 ],
558 },
559 ],
560 });
561 const link = await vi.waitFor(() => {
562 const found = [...screen.container.querySelectorAll("a")].find(
563 (anchor) => anchor.textContent === "View on host",
564 );
565 expect(found).toBeDefined();
566 return found!;
567 });
568 const click = new MouseEvent("click", { bubbles: true, cancelable: true });
569 link.dispatchEvent(click);
570​
571 expect(click.defaultPrevented).toBe(true);
572 expect(state.openLink).toHaveBeenCalledOnce();
573 expect(state.openLink).toHaveBeenCalledWith(
574 "https://github.com/owner/repo/pull/1#discussion_r1",
575 {
576 event: expect.anything(),
577 },
578 );
579});