Open History to see the last commit
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}));
15
16vi.mock(import("~/state/use-atom-command"), async (original) => ({
17 ...(await original()),
18 useAtomCommand: (() => state.update) as never,
19}));
20vi.mock(import("~/state/session"), async (original) => ({
21 ...(await original()),
22 readEnvironmentScope: () => true,
23 useEnvironmentScope: () => true,
24}));
25vi.mock(import("~/hooks/useSettings"), async (original) => ({
26 ...(await original()),
27 useClientSettings: ((select?: (settings: ClientSettings) => unknown) => {
28 const settings = { ...DEFAULT_CLIENT_SETTINGS, timestampFormat: state.timestampFormat };
29 return select ? select(settings) : settings;
30 }) as never,
31}));
32vi.mock(import("~/state/pullRequests"), async (original) => {
33 const actual = await original();
34 const { Atom } = await import("effect/reactivity");
35 const allowed = Atom.make(true);
36 const denied = Atom.make(false);
37 return {
38 ...actual,
39 pullRequestEnvironment: {
40 ...actual.pullRequestEnvironment,
41 update: {
42 ...actual.pullRequestEnvironment.update,
43 permissionAtom: () => (state.canUpdate ? allowed : denied),
44 },
45 },
46 };
47});
48
49function setup() {
50 state.update.mockReset();
51 state.update.mockResolvedValue({ _tag: "Success", value: undefined });
52 state.canUpdate = true;
53 state.timestampFormat = "locale";
54}
55
56import "~/index.css";
57import { workspaceAreaProps } from "~/lib/workspaceFocus";
58import { act, render as renderUi } from "../../../test/render";
59import { PullRequestSummaryTab } from "./PullRequestSummaryTab";
60
61const detail: PullRequestDetailView = {
62 provider: SourceControlProviderKind.make("github"),
63 projectId: ProjectId.make("project"),
64 projectTitle: "Project",
65 workspaceRoot: "/workspace",
66 repository: "owner/repo",
67 number: 1,
68 title: "Test pull request",
69 body: "Original description",
70 url: "https://github.com/owner/repo/pull/1",
71 author: { login: "author", name: null, avatarUrl: null },
72 viewer: "author",
73 state: "open",
74 isDraft: false,
75 mergeability: "mergeable",
76 additions: 1,
77 deletions: 0,
78 changedFiles: 1,
79 headBranch: "feature",
80 baseBranch: "main",
81 createdAt: "2026-09-01T00:00:00Z",
82 updatedAt: "2026-09-01T00:00:00Z",
83 mergedAt: null,
84 closedAt: null,
85 reviewers: [],
86 labels: [],
87 checks: [{ name: "Unit tests", status: "success", description: null, url: null }],
88 comments: [],
89 commentCount: 0,
90 commentsTruncated: false,
91 reviewThreads: [],
92 commits: [],
93 mergeCapabilities: { merge: false, squash: false, rebase: false },
94 capabilities: {
95 diff: true,
96 comment: true,
97 search: true,
98 actions: [],
99 mergeMethods: [],
100 review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
101 reviewers: { request: false, listCandidates: false },
102 edit: { changeRequest: true, comment: true },
103 },
104 viewerPermissions: {
105 actions: [],
106 comment: true,
107 resolve: false,
108 verdicts: [],
109 requestReviewers: false,
110 },
111};
112
113// The comment filter persists to localStorage, so tests that touch it start and end empty.
114
115const tab = (value = detail) => (
116 <PullRequestSummaryTab
117 scrollerRef={() => {}}
118 environmentId={EnvironmentId.make("environment")}
119 threadRef={null}
120 reference={value}
121 detail={value}
122 activityPending={false}
123 activityError={null}
124 onRefresh={() => {}}
125 />
126);
127
128async function render(value = detail) {
129 const screen = await renderUi(tab(value));
130 const { container } = screen;
131 const heading = (title: string) => {
132 const section = container.querySelector(`section[aria-label="${title}"]`);
133 expect(section, `section ${title}`).not.toBeNull();
134 return [...section!.querySelectorAll("button")].find(
135 (button) => button.querySelector("span")?.textContent === title,
136 )!;
137 };
138 return Object.assign(screen, {
139 click: (title: string) => act(async () => heading(title).click()),
140 expanded: (title: string) => heading(title).getAttribute("aria-expanded"),
141 visibleText: () => container.innerText,
142 });
143}
144
145it("keeps an unsaved description when collapsed and reopened, and after a failed save", async () => {
146 setup();
147 state.update.mockResolvedValue({ _tag: "Failure", cause: new Error("offline") });
148 await using screen = await render();
149 await act(async () =>
150 screen.container.querySelector<HTMLButtonElement>('[aria-label="Edit description"]')!.click(),
151 );
152 const textarea = screen.container.querySelector("textarea")!;
153 await userEvent.clear(textarea);
154 await userEvent.type(textarea, "Unsaved description");
155 await screen.click("Description");
156 expect(screen.expanded("Description")).toBe("false");
157 await screen.click("Description");
158 expect(screen.container.querySelector("textarea")!.value).toBe("Unsaved description");
159
160 await userEvent.click(screen.getByRole("button", { name: "Save" }));
161 expect(state.update).toHaveBeenCalledTimes(1);
162 await expect.element(screen.getByRole("button", { name: "Save" })).toBeEnabled();
163 expect(screen.container.querySelector("textarea")!.value).toBe("Unsaved description");
164});
165
166it("ticks a description checkbox placed after an attachment and edits from the ticked body", async () => {
167 setup();
168 let finishSave = (_result: unknown) => {};
169 state.update.mockReturnValueOnce(new Promise((resolve) => (finishSave = resolve)));
170 const body = "Intro\n\nhttps://example.com/shot.png\n\n## Test plan\n- [ ] First\n- [ ] Second";
171 const ticked = body.replace("- [ ] Second", "- [x] Second");
172 await using screen = await render({ ...detail, body, observedAt: 1 });
173 const boxes = () => screen.container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]');
174 expect([...boxes()].map((box) => box.disabled)).toEqual([false, false]);
175
176 await userEvent.click(boxes()[1]!);
177 expect(state.update).toHaveBeenCalledWith({
178 environmentId: "environment",
179 input: expect.objectContaining({ number: 1, body: ticked }),
180 });
181 expect([...boxes()].map((box) => box.checked)).toEqual([false, true]);
182 await act(async () => finishSave({ _tag: "Success", value: undefined }));
183
184 // The host has not been read since the save, so the editor starts from the ticked body.
185 await act(async () =>
186 screen.container.querySelector<HTMLButtonElement>('[aria-label="Edit description"]')!.click(),
187 );
188 expect(screen.container.querySelector("textarea")!.value).toBe(ticked);
189});
190
191it("leaves description checkboxes read-only without the right to edit it", async () => {
192 setup();
193 const body = "- [ ] First";
194 {
195 await using screen = await render({ ...detail, body, viewer: "someone-else" });
196 expect(
197 screen.container.querySelector<HTMLInputElement>('input[type="checkbox"]')!.disabled,
198 ).toBe(true);
199 }
200 state.canUpdate = false;
201 await using screen = await render({ ...detail, body });
202 expect(screen.container.querySelector<HTMLInputElement>('input[type="checkbox"]')!.disabled).toBe(
203 true,
204 );
205});
206
207it("fixes an overview thread as its opening remark, since it has no line to attach", async () => {
208 setup();
209 const author = { login: "reviewer", name: null, avatarUrl: null };
210 const note = { author, createdAt: "2026-09-01T00:00:00Z", url: null };
211 const remark = {
212 ...note,
213 id: "10",
214 kind: "review-comment" as const,
215 body: "Mention the flag in the README",
216 path: null,
217 reviewState: null,
218 };
219 const onFixFinding = vi.fn();
220 const value: PullRequestDetailView = {
221 ...detail,
222 comments: [remark],
223 overviewThreads: [
224 {
225 id: "overview",
226 path: null,
227 line: null,
228 side: "right",
229 isResolved: false,
230 isOutdated: false,
231 comments: [{ ...note, id: "10", body: remark.body }],
232 },
233 ],
234 };
235 await using screen = await renderUi(
236 <PullRequestSummaryTab
237 scrollerRef={() => {}}
238 environmentId={EnvironmentId.make("environment")}
239 threadRef={null}
240 reference={value}
241 detail={value}
242 activityPending={false}
243 activityError={null}
244 onRefresh={() => {}}
245 onFixFinding={onFixFinding}
246 />,
247 );
248
249 await userEvent.click(screen.getByRole("button", { name: "Fix in a thread" }));
250 expect(onFixFinding).toHaveBeenCalledWith({ kind: "comment", comment: remark });
251});
252
253it("shows a comment's exact time in the chosen 24-hour clock", async () => {
254 setup();
255 state.timestampFormat = "24-hour";
256 const createdAt = "2026-09-01T17:30:00Z";
257 const comment = {
258 id: "10",
259 kind: "review-comment" as const,
260 body: "A remark",
261 author: { login: "reviewer", name: null, avatarUrl: null },
262 createdAt,
263 url: null,
264 path: null,
265 reviewState: null,
266 };
267 await using screen = await render({ ...detail, comments: [comment], commentCount: 1 });
268
269 await userEvent.hover(screen.container.querySelector(`time[datetime="${createdAt}"]`)!);
270 const expected = new Date(createdAt).toLocaleString(undefined, { hour12: false });
271 await vi.waitFor(() =>
272 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toBe(expected),
273 );
274});
275
276it("scrolls from the keyboard after a click inside it", async () => {
277 setup();
278 const body = Array.from({ length: 80 }, (_, index) => `Paragraph ${index}`).join("\n\n");
279 const container = document.createElement("div");
280 container.className = "flex h-[300px]";
281 await using screen = await renderUi(
282 // The panel area takes focus itself, so a click on plain text lands on it unless the tab can.
283 <div {...workspaceAreaProps("panel", 4, "Workspace panel")} className="flex min-w-0 flex-1">
284 {tab({ ...detail, body })}
285 </div>,
286 { container },
287 );
288 const scroller = container.querySelector<HTMLElement>("[data-pull-request-summary-scroll]")!;
289 await userEvent.click(screen.getByText("Paragraph 0", { exact: true }));
290 await userEvent.keyboard("{PageDown}");
291 await vi.waitFor(() => expect(scroller.scrollTop).toBeGreaterThan(0));
292});