Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import { EnvironmentId, ProjectId, type PullRequestDetailView } from "@t3tools/contracts";
3import { expect, it, vi } from "vite-plus/test";
4import { userEvent } from "vite-plus/test/browser";
5
6const state = vi.hoisted(() => ({ update: vi.fn(), canUpdate: true }));
7
8vi.mock(import("~/state/use-atom-command"), async (original) => ({
9 ...(await original()),
10 useAtomCommand: (() => state.update) as never,
11}));
12vi.mock(import("~/state/session"), async (original) => ({
13 ...(await original()),
14 readEnvironmentScope: () => true,
15 useEnvironmentScope: () => true,
16}));
17vi.mock(import("~/state/pullRequests"), async (original) => {
18 const actual = await original();
19 const { Atom } = await import("effect/reactivity");
20 const allowed = Atom.make(true);
21 const denied = Atom.make(false);
22 return {
23 ...actual,
24 pullRequestEnvironment: {
25 ...actual.pullRequestEnvironment,
26 update: {
27 ...actual.pullRequestEnvironment.update,
28 permissionAtom: () => (state.canUpdate ? allowed : denied),
29 },
30 },
31 };
32});
33
34function setup() {
35 state.update.mockReset();
36 state.update.mockResolvedValue({ _tag: "Success", value: undefined });
37 state.canUpdate = true;
38}
39
40import { act, render as renderUi } from "../../../test/render";
41import { PullRequestSummaryTab } from "./PullRequestSummaryTab";
42
43const detail: PullRequestDetailView = {
44 provider: SourceControlProviderKind.make("github"),
45 projectId: ProjectId.make("project"),
46 projectTitle: "Project",
47 workspaceRoot: "/workspace",
48 repository: "owner/repo",
49 number: 1,
50 title: "Test pull request",
51 body: "Original description",
52 url: "https://github.com/owner/repo/pull/1",
53 author: { login: "author", name: null, avatarUrl: null },
54 viewer: "author",
55 state: "open",
56 isDraft: false,
57 mergeability: "mergeable",
58 additions: 1,
59 deletions: 0,
60 changedFiles: 1,
61 headBranch: "feature",
62 baseBranch: "main",
63 createdAt: "2026-09-01T00:00:00Z",
64 updatedAt: "2026-09-01T00:00:00Z",
65 mergedAt: null,
66 closedAt: null,
67 reviewers: [],
68 labels: [],
69 checks: [{ name: "Unit tests", status: "success", description: null, url: null }],
70 comments: [],
71 commentCount: 0,
72 commentsTruncated: false,
73 reviewThreads: [],
74 commits: [],
75 mergeCapabilities: { merge: false, squash: false, rebase: false },
76 capabilities: {
77 diff: true,
78 comment: true,
79 search: true,
80 actions: [],
81 mergeMethods: [],
82 review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
83 reviewers: { request: false, listCandidates: false },
84 edit: { changeRequest: true, comment: true },
85 },
86 viewerPermissions: {
87 actions: [],
88 comment: true,
89 resolve: false,
90 verdicts: [],
91 requestReviewers: false,
92 },
93};
94
95// The comment filter persists to localStorage, so tests that touch it start and end empty.
96
97const tab = (value = detail) => (
98 <PullRequestSummaryTab
99 scrollerRef={() => {}}
100 environmentId={EnvironmentId.make("environment")}
101 threadRef={null}
102 reference={value}
103 detail={value}
104 activityPending={false}
105 activityError={null}
106 onRefresh={() => {}}
107 />
108);
109
110async function render(value = detail) {
111 const screen = await renderUi(tab(value));
112 const { container } = screen;
113 const heading = (title: string) => {
114 const section = container.querySelector(`section[aria-label="${title}"]`);
115 expect(section, `section ${title}`).not.toBeNull();
116 return [...section!.querySelectorAll("button")].find(
117 (button) => button.querySelector("span")?.textContent === title,
118 )!;
119 };
120 return Object.assign(screen, {
121 click: (title: string) => act(async () => heading(title).click()),
122 expanded: (title: string) => heading(title).getAttribute("aria-expanded"),
123 visibleText: () => container.innerText,
124 });
125}
126
127it("keeps an unsaved description when collapsed and reopened, and after a failed save", async () => {
128 setup();
129 state.update.mockResolvedValue({ _tag: "Failure", cause: new Error("offline") });
130 await using screen = await render();
131 await act(async () =>
132 screen.container.querySelector<HTMLButtonElement>('[aria-label="Edit description"]')!.click(),
133 );
134 const textarea = screen.container.querySelector("textarea")!;
135 await userEvent.clear(textarea);
136 await userEvent.type(textarea, "Unsaved description");
137 await screen.click("Description");
138 expect(screen.expanded("Description")).toBe("false");
139 await screen.click("Description");
140 expect(screen.container.querySelector("textarea")!.value).toBe("Unsaved description");
141
142 await userEvent.click(screen.getByRole("button", { name: "Save" }));
143 expect(state.update).toHaveBeenCalledTimes(1);
144 await expect.element(screen.getByRole("button", { name: "Save" })).toBeEnabled();
145 expect(screen.container.querySelector("textarea")!.value).toBe("Unsaved description");
146});
147
148it("ticks a description checkbox placed after an attachment and edits from the ticked body", async () => {
149 setup();
150 let finishSave = (_result: unknown) => {};
151 state.update.mockReturnValueOnce(new Promise((resolve) => (finishSave = resolve)));
152 const body = "Intro\n\nhttps://example.com/shot.png\n\n## Test plan\n- [ ] First\n- [ ] Second";
153 const ticked = body.replace("- [ ] Second", "- [x] Second");
154 await using screen = await render({ ...detail, body, observedAt: 1 });
155 const boxes = () => screen.container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]');
156 expect([...boxes()].map((box) => box.disabled)).toEqual([false, false]);
157
158 await userEvent.click(boxes()[1]!);
159 expect(state.update).toHaveBeenCalledWith({
160 environmentId: "environment",
161 input: expect.objectContaining({ number: 1, body: ticked }),
162 });
163 expect([...boxes()].map((box) => box.checked)).toEqual([false, true]);
164 await act(async () => finishSave({ _tag: "Success", value: undefined }));
165
166 // The host has not been read since the save, so the editor starts from the ticked body.
167 await act(async () =>
168 screen.container.querySelector<HTMLButtonElement>('[aria-label="Edit description"]')!.click(),
169 );
170 expect(screen.container.querySelector("textarea")!.value).toBe(ticked);
171});
172
173it("leaves description checkboxes read-only without the right to edit it", async () => {
174 setup();
175 const body = "- [ ] First";
176 {
177 await using screen = await render({ ...detail, body, viewer: "someone-else" });
178 expect(
179 screen.container.querySelector<HTMLInputElement>('input[type="checkbox"]')!.disabled,
180 ).toBe(true);
181 }
182 state.canUpdate = false;
183 await using screen = await render({ ...detail, body });
184 expect(screen.container.querySelector<HTMLInputElement>('input[type="checkbox"]')!.disabled).toBe(
185 true,
186 );
187});
188
189it("fixes an overview thread as its opening remark, since it has no line to attach", async () => {
190 setup();
191 const author = { login: "reviewer", name: null, avatarUrl: null };
192 const note = { author, createdAt: "2026-09-01T00:00:00Z", url: null };
193 const remark = {
194 ...note,
195 id: "10",
196 kind: "review-comment" as const,
197 body: "Mention the flag in the README",
198 path: null,
199 reviewState: null,
200 };
201 const onFixFinding = vi.fn();
202 const value: PullRequestDetailView = {
203 ...detail,
204 comments: [remark],
205 overviewThreads: [
206 {
207 id: "overview",
208 path: null,
209 line: null,
210 side: "right",
211 isResolved: false,
212 isOutdated: false,
213 comments: [{ ...note, id: "10", body: remark.body }],
214 },
215 ],
216 };
217 await using screen = await renderUi(
218 <PullRequestSummaryTab
219 scrollerRef={() => {}}
220 environmentId={EnvironmentId.make("environment")}
221 threadRef={null}
222 reference={value}
223 detail={value}
224 activityPending={false}
225 activityError={null}
226 onRefresh={() => {}}
227 onFixFinding={onFixFinding}
228 />,
229 );
230
231 await userEvent.click(screen.getByRole("button", { name: "Fix in a thread" }));
232 expect(onFixFinding).toHaveBeenCalledWith({ kind: "comment", comment: remark });
233});