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

PullRequestCodeTab.browser.test.tsx

562 lines19.7 KB

1import { sha256 } from "@noble/hashes/sha2";
2import { bytesToHex } from "@noble/hashes/utils";
3import {
4 EnvironmentId,
5 ProjectId,
6 SourceControlProviderKind,
7 type PullRequestDetailView,
8 type PullRequestDiffResult,
9} from "@t3tools/contracts";
10import { expect, it, vi } from "vite-plus/test";
11import { userEvent } from "vite-plus/test/browser";
12​
13import "~/index.css";
14import { __setClientSettingsForTests } from "../../hooks/useSettings";
15import { setAppearanceMode } from "../../hooks/useTheme";
16import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
17​
18const { diffAtom, pagedDiffAtom } = await vi.hoisted(async () => {
19 const { AsyncResult, Atom } = await import("effect/reactivity");
20 const filePatch = (path: string) =>
21 [
22 `diff --git a/${path} b/${path}`,
23 "index 1111111..2222222 100644",
24 `--- a/${path}`,
25 `+++ b/${path}`,
26 "@@ -1,6 +1,6 @@",
27 "-before()",
28 "+after()",
29 " one()",
30 " two()",
31 " three()",
32 " four()",
33 " five()",
34 "",
35 ].join("\n");
36 const firstPage: PullRequestDiffResult = {
37 patch: filePatch("a.ts"),
38 truncated: false,
39 nextCursor: null,
40 };
41 const pages: Record<string, PullRequestDiffResult> = {
42 first: {
43 patch: Array.from({ length: 40 }, (_, index) =>
44 filePatch(index === 1 ? "early-1.test.ts" : `early-${index}.ts`),
45 ).join(""),
46 truncated: true,
47 nextCursor: "page-2",
48 },
49 "page-2": { patch: filePatch("late.test.ts"), truncated: false, nextCursor: null },
50 };
51 return {
52 // An environment query whose refetch returns equal content hands back the previous value
53 // itself, so a refresh publishes a new result around the very same page.
54 diffAtom: Atom.make(() => AsyncResult.success(firstPage)),
55 pagedDiffAtom: Atom.family((cursor: string) =>
56 Atom.make(() => AsyncResult.success(pages[cursor]!)),
57 ),
58 };
59});
60​
61const mocks = vi.hoisted(() => ({
62 paged: false,
63 diffCommits: [] as Array<string | undefined>,
64 viewedPaths: null as ReadonlySet<string> | null,
65 viewedListeners: new Set<() => void>(),
66}));
67​
68function deliverViewedPaths(paths: ReadonlySet<string> | null) {
69 mocks.viewedPaths = paths;
70 for (const listener of mocks.viewedListeners) listener();
72​
73vi.mock(import("~/state/use-atom-command"), async (original) => ({
74 ...(await original()),
75 useAtomCommand: (() => vi.fn()) as never,
76}));
77vi.mock(import("./usePullRequestFilesViewed"), async () => {
78 const { useSyncExternalStore } = await import("react");
79 const subscribe = (listener: () => void) => {
80 mocks.viewedListeners.add(listener);
81 return () => mocks.viewedListeners.delete(listener);
82 };
83 return {
84 usePullRequestFilesViewed: () => {
85 const viewedPaths = useSyncExternalStore(subscribe, () => mocks.viewedPaths);
86 return {
87 enabled: viewedPaths !== null,
88 isViewed: (path: string) => viewedPaths?.has(path) === true,
89 isStale: () => false,
90 setViewed: (path: string, viewed: boolean) => {
91 const next = new Set(mocks.viewedPaths);
92 if (viewed) next.add(path);
93 else next.delete(path);
94 deliverViewedPaths(next);
95 },
96 truncated: false,
97 error: null,
98 refresh: () => {},
99 };
100 },
101 };
102});
103vi.mock(import("~/state/pullRequests"), async (original) => {
104 const actual = await original();
105 return {
106 ...actual,
107 pullRequestEnvironment: {
108 ...actual.pullRequestEnvironment,
109 diff: (({ input }: { input: { cursor?: string; commit?: string } }) => {
110 mocks.diffCommits.push(input.commit);
111 return mocks.paged ? pagedDiffAtom(input.cursor ?? "first") : diffAtom;
112 }) as never,
113 },
114 };
115});
116​
117import { render } from "../../../test/render";
118import PullRequestCodeTab from "./PullRequestCodeTab";
119​
120const detail: PullRequestDetailView = {
121 provider: SourceControlProviderKind.make("github"),
122 projectId: ProjectId.make("project"),
123 projectTitle: "Project",
124 workspaceRoot: "/workspace",
125 repository: "owner/repo",
126 number: 1,
127 title: "Test pull request",
128 body: "",
129 url: "https://github.com/owner/repo/pull/1",
130 author: { login: "author", name: null, avatarUrl: null },
131 viewer: "author",
132 state: "open",
133 isDraft: false,
134 mergeability: "mergeable",
135 additions: 1,
136 deletions: 1,
137 changedFiles: 1,
138 headBranch: "feature",
139 baseBranch: "main",
140 createdAt: "2026-09-01T00:00:00Z",
141 updatedAt: "2026-09-01T00:00:00Z",
142 mergedAt: null,
143 closedAt: null,
144 reviewers: [],
145 labels: [],
146 checks: [],
147 comments: [],
148 commentCount: 0,
149 commentsTruncated: false,
150 reviewThreads: [],
151 commits: [],
152 mergeCapabilities: { merge: false, squash: false, rebase: false },
153 capabilities: {
154 diff: true,
155 comment: false,
156 search: true,
157 actions: [],
158 mergeMethods: [],
159 review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
160 reviewers: { request: false, listCandidates: false },
161 edit: { changeRequest: false, comment: false },
162 },
163 viewerPermissions: {
164 actions: [],
165 comment: false,
166 resolve: false,
167 verdicts: [],
168 requestReviewers: false,
169 },
170};
171​
172function setup({ paged }: { paged: boolean }) {
173 window.localStorage.removeItem("t3code.diffHideTestFiles");
174 __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
175 mocks.paged = paged;
176 mocks.diffCommits = [];
177 mocks.viewedPaths = null;
178 mocks.viewedListeners.clear();
180​
181const tab = (
182 refreshToken: number,
183 revealRequest: { readonly path: string; readonly nonce: number } | null = null,
184 revealUrl?: string,
185 onRevealSettled?: (url: string) => void,
186) => (
187 <PullRequestCodeTab
188 scrollerRef={() => {}}
189 environmentId={EnvironmentId.make("environment")}
190 reference={detail}
191 detail={detail}
192 selectedCommitOid={null}
193 onSelectedCommitChange={() => {}}
194 onRefresh={() => {}}
195 refreshToken={refreshToken}
196 revealRequest={revealRequest}
197 revealUrl={revealUrl}
198 onRevealSettled={onRevealSettled}
199 />
200);
201​
202it("keeps the diff after a refresh that brings back the same page", async () => {
203 setup({ paged: false });
204 const container = document.createElement("div");
205 container.className = "flex h-[700px] w-[900px]";
206 await using screen = await render(tab(0), { container });
207 await expect.element(screen.getByText("1 file", { exact: true })).toBeVisible();
208​
209 await screen.rerender(tab(1));
210​
211 await expect
212 .element(screen.getByText("This pull request has no file changes."))
213 .not.toBeInTheDocument();
214 await expect.element(screen.getByText("1 file", { exact: true })).toBeVisible();
215});
216​
217it("restores saved Viewed folds, follows cleared marks, and allows explicit expansion", async () => {
218 setup({ paged: false });
219 __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: false });
220 using _preferences = {
221 [Symbol.dispose]() {
222 __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
223 },
224 };
225 mocks.viewedPaths = new Set(["a.ts"]);
226 const container = document.createElement("div");
227 container.className = "flex h-[700px] w-[900px]";
228 await using screen = await render(tab(0), { container });
229 await expect.element(screen.getByRole("checkbox", { name: "Viewed" })).toBeChecked();
230 await expect
231 .element(screen.getByRole("button", { name: "Expand diff", exact: true }))
232 .toHaveAttribute("aria-expanded", "false");
233​
234 await screen.getByRole("button", { name: "Expand diff", exact: true }).click();
235 await expect.element(screen.getByText("three()", { exact: true })).toBeVisible();
236 screen.getByRole("checkbox", { name: "Viewed" }).element().focus();
237 await userEvent.keyboard(" ");
238 await expect.element(screen.getByRole("checkbox", { name: "Viewed" })).not.toBeChecked();
239 await expect.element(screen.getByText("three()", { exact: true })).toBeVisible();
240 screen.getByRole("checkbox", { name: "Viewed" }).element().focus();
241 await userEvent.keyboard(" ");
242 await expect
243 .element(screen.getByRole("button", { name: "Expand diff", exact: true }))
244 .toHaveAttribute("aria-expanded", "false");
245​
246 deliverViewedPaths(new Set());
247 await expect.element(screen.getByRole("checkbox", { name: "Viewed" })).not.toBeChecked();
248 await expect.element(screen.getByText("three()", { exact: true })).toBeVisible();
249 deliverViewedPaths(new Set(["a.ts"]));
250 await expect
251 .element(screen.getByRole("button", { name: "Expand diff", exact: true }))
252 .toHaveAttribute("aria-expanded", "false");
253 await screen.getByRole("button", { name: "Expand all files", exact: true }).click();
254 await expect.element(screen.getByText("three()", { exact: true })).toBeVisible();
255​
256 await screen.rerender(<div />);
257 await screen.rerender(tab(1));
258 await expect
259 .element(screen.getByRole("button", { name: "Expand diff", exact: true }))
260 .toHaveAttribute("aria-expanded", "false");
261});
262​
263// regression: #13279 a Viewed answer that lands after a link reveals a file must not fold it
264it("keeps a revealed file open when its Viewed mark loads afterwards", async () => {
265 setup({ paged: false });
266 __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: false });
267 using _preferences = {
268 [Symbol.dispose]() {
269 __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
270 },
271 };
272 mocks.viewedPaths = new Set();
273 const container = document.createElement("div");
274 container.className = "flex h-[700px] w-[900px]";
275 await using screen = await render(tab(0, { path: "a.ts", nonce: 1 }), { container });
276 await expect.element(screen.getByText("three()", { exact: true })).toBeVisible();
277​
278 deliverViewedPaths(new Set(["a.ts"]));
279 await expect.element(screen.getByRole("checkbox", { name: "Viewed" })).toBeChecked();
280​
281 await expect
282 .element(screen.getByRole("button", { name: "Collapse diff" }))
283 .toHaveAttribute("aria-expanded", "true");
284 await expect.element(screen.getByText("three()", { exact: true })).toBeVisible();
285});
286​
287function pagedContainer() {
288 const container = document.createElement("div");
289 container.className = "flex h-[500px] w-[900px]";
290 return container;
292​
293async function expectFileHeaderShown(
294 screen: Awaited<ReturnType<typeof render>>,
295 container: HTMLElement,
296 path: string,
297) {
298 const header = screen.getByText(path, { exact: true }).first();
299 await expect.element(header).toBeInTheDocument();
300 await vi.waitFor(() => {
301 const bounds = container.querySelector(".diff-render-surface")!.getBoundingClientRect();
302 const { top, bottom } = header.element().getBoundingClientRect();
303 expect(top).toBeGreaterThanOrEqual(bounds.top);
304 expect(bottom).toBeLessThanOrEqual(bounds.bottom);
305 });
307​
308it("scrolls to a file asked for as the tab opens", async () => {
309 setup({ paged: true });
310 const container = pagedContainer();
311 await using screen = await render(tab(0, { path: "early-39.ts", nonce: 1 }), { container });
312​
313 await expectFileHeaderShown(screen, container, "early-39.ts");
314});
315​
316it("pages forward to a file asked for that is not loaded yet, then scrolls to it", async () => {
317 setup({ paged: true });
318 __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: true });
319 using _preferences = {
320 [Symbol.dispose]() {
321 window.localStorage.removeItem("t3code.diffHideTestFiles");
322 __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
323 },
324 };
325 const container = pagedContainer();
326 await using screen = await render(tab(0), { container });
327 await expect.element(screen.getByText("early-0.ts", { exact: true }).first()).toBeVisible();
328 await screen.getByRole("button", { name: "Hide test files" }).click();
329​
330 const url = `${detail.url}/files#diff-${bytesToHex(sha256(new TextEncoder().encode("late.test.ts")))}R4-R5`;
331 const settled = vi.fn();
332 await screen.rerender(tab(0, null, url, settled));
333​
334 await expectFileHeaderShown(screen, container, "late.test.ts");
335 await expect.element(screen.getByText("three()", { exact: true })).toBeVisible();
336 await vi.waitFor(() => expect(settled).toHaveBeenCalledWith(url));
337 // A settled link keeps its test file past the filter, and a later click reveals it again.
338 await screen.rerender(tab(0, { path: "early-0.ts", nonce: 1 }));
339 await expectFileHeaderShown(screen, container, "early-0.ts");
340 await screen.rerender(tab(0, { path: "early-0.ts", nonce: 1 }, url, settled));
341 await expectFileHeaderShown(screen, container, "late.test.ts");
342});
343​
344it("never requests the diff of a selected commit the pull request no longer has", async () => {
345 setup({ paged: false });
346 const container = document.createElement("div");
347 container.className = "flex h-[700px] w-[900px]";
348 // The timeline can open a commit that a force-push removed from the pull request.
349 await using screen = await render(
350 <PullRequestCodeTab
351 scrollerRef={() => {}}
352 environmentId={EnvironmentId.make("environment")}
353 reference={detail}
354 detail={{
355 ...detail,
356 commits: [
357 {
358 oid: "kept",
359 messageHeadline: "Kept commit",
360 committedDate: "2026-09-01T00:00:00Z",
361 },
362 ],
363 }}
364 selectedCommitOid="gone"
365 onSelectedCommitChange={() => {}}
366 onRefresh={() => {}}
367 />,
368 { container },
369 );
370​
371 await expect.element(screen.getByText("1 file", { exact: true })).toBeVisible();
372 await expect
373 .element(screen.getByRole("button", { name: "Diff scope: All commits" }))
374 .toBeVisible();
375 expect(mocks.diffCommits).not.toContain("gone");
376});
377​
378it("answers a commit's diff link only once that commit's diff is shown", async () => {
379 setup({ paged: false });
380 const container = document.createElement("div");
381 container.className = "flex h-[700px] w-[900px]";
382 const oid = "c".repeat(40);
383 const withCommit = {
384 ...detail,
385 commits: [{ oid, messageHeadline: "Linked commit", committedDate: "2026-09-01T00:00:00Z" }],
386 };
387 const url = `${detail.url}/commits/${oid}#diff-${bytesToHex(sha256(new TextEncoder().encode("a.ts")))}R2`;
388 const settled = vi.fn();
389 const scoped = (selectedCommitOid: string | null, revealUrl?: string) => (
390 <PullRequestCodeTab
391 scrollerRef={() => {}}
392 environmentId={EnvironmentId.make("environment")}
393 reference={detail}
394 detail={withCommit}
395 selectedCommitOid={selectedCommitOid}
396 onSelectedCommitChange={() => {}}
397 onRefresh={() => {}}
398 revealUrl={revealUrl}
399 onRevealSettled={settled}
400 />
401 );
402 await using screen = await render(scoped(null), { container });
403 await expect.element(screen.getByText("1 file", { exact: true })).toBeVisible();
404​
405 // The panel selects the link's commit after this tab has already seen the link.
406 await screen.rerender(scoped(null, url));
407 expect(settled).not.toHaveBeenCalled();
408 await screen.rerender(scoped(oid, url));
409 await vi.waitFor(() => expect(settled).toHaveBeenCalledWith(url));
410});
411​
412it("hides a resolved conversation behind avatars on its line until they are clicked", async () => {
413 setup({ paged: false });
414 __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: false });
415 using _preferences = {
416 [Symbol.dispose]() {
417 __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
418 },
419 };
420 const container = document.createElement("div");
421 container.className = "flex h-[700px] w-[900px]";
422 const comment = {
423 author: { login: "reviewer", name: null, avatarUrl: null },
424 body: "Rename this.",
425 createdAt: "2026-09-01T00:00:00Z",
426 url: null,
427 };
428 const withThread = (isResolved: boolean, oldSideToo = false) => (
429 <PullRequestCodeTab
430 scrollerRef={() => {}}
431 environmentId={EnvironmentId.make("environment")}
432 reference={detail}
433 detail={{
434 ...detail,
435 capabilities: {
436 ...detail.capabilities,
437 review: { ...detail.capabilities.review, reply: true },
438 },
439 viewerPermissions: { ...detail.viewerPermissions, comment: true },
440 reviewThreads: [
441 {
442 id: "thread",
443 path: "a.ts",
444 line: 3,
445 side: "right",
446 isResolved,
447 isOutdated: false,
448 comments: [{ id: "comment", ...comment }],
449 },
450 ...(oldSideToo
451 ? [
452 {
453 id: "old-side",
454 path: "a.ts",
455 line: 3,
456 side: "left" as const,
457 isResolved: true,
458 isOutdated: false,
459 comments: [{ id: "old-side-comment", ...comment }],
460 },
461 ]
462 : []),
463 ],
464 }}
465 selectedCommitOid={null}
466 onSelectedCommitChange={() => {}}
467 onRefresh={() => {}}
468 />
469 );
470 await using screen = await render(withThread(true), { container });
471 const marker = screen.getByRole("button", { name: "Resolved conversation", exact: true });
472 const card = (state: string) => screen.getByRole("button", { name: `${state} · 1 comment` });
473 const reply = () => screen.getByRole("textbox", { name: "Reply to this conversation" });
474​
475 await expect.element(marker).toHaveAttribute("aria-expanded", "false");
476 await expect.element(card("Resolved")).not.toBeInTheDocument();
477​
478 await marker.click();
479 await expect.element(marker).toHaveAttribute("aria-expanded", "true");
480 await expect.element(card("Resolved")).toHaveAttribute("aria-expanded", "true");
481 await screen.getByRole("button", { name: "Reply", exact: true }).click();
482 await reply().fill("Unsent");
483​
484 // Hidden conversations stay mounted, so the unsent reply is still there.
485 await marker.click();
486 await expect.element(card("Resolved")).not.toBeInTheDocument();
487 await marker.click();
488 await expect.element(reply()).toHaveValue("Unsent");
489 await marker.click();
490​
491 // Seen open and then resolved, it stays until the avatars are clicked.
492 await screen.rerender(withThread(false));
493 await expect.element(card("Open")).toBeVisible();
494 await screen.rerender(withThread(true));
495 await expect.element(card("Resolved")).toBeVisible();
496​
497 // Stacked view draws a context row once, so both sides' conversations share the avatars.
498 await screen.rerender(withThread(true, true));
499 await expect
500 .element(screen.getByRole("button", { name: "2 resolved conversations" }))
501 .toBeVisible();
502});
503​
504// regression: #37996
505it("keeps an unsent reply when the appearance switches between light and dark", async () => {
506 setup({ paged: false });
507 __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: false });
508 setAppearanceMode("dark");
509 using _preferences = {
510 [Symbol.dispose]() {
511 __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
512 setAppearanceMode("system");
513 },
514 };
515 const container = document.createElement("div");
516 container.className = "flex h-[700px] w-[900px]";
517 await using screen = await render(
518 <PullRequestCodeTab
519 scrollerRef={() => {}}
520 environmentId={EnvironmentId.make("environment")}
521 reference={detail}
522 detail={{
523 ...detail,
524 capabilities: {
525 ...detail.capabilities,
526 review: { ...detail.capabilities.review, reply: true },
527 },
528 viewerPermissions: { ...detail.viewerPermissions, comment: true },
529 reviewThreads: [
530 {
531 id: "thread",
532 path: "a.ts",
533 line: 3,
534 side: "right",
535 isResolved: false,
536 isOutdated: false,
537 comments: [
538 {
539 id: "comment",
540 author: { login: "reviewer", name: null, avatarUrl: null },
541 body: "Rename this.",
542 createdAt: "2026-09-01T00:00:00Z",
543 url: null,
544 },
545 ],
546 },
547 ],
548 }}
549 selectedCommitOid={null}
550 onSelectedCommitChange={() => {}}
551 onRefresh={() => {}}
552 />,
553 { container },
554 );
555 const reply = () => screen.getByRole("textbox", { name: "Reply to this conversation" });
556 await screen.getByRole("button", { name: "Reply", exact: true }).click();
557 await reply().fill("Unsent");
558​
559 setAppearanceMode("light");
560​
561 await expect.element(reply()).toHaveValue("Unsent");
562});