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

PullRequestDetailPanel.browser.test.tsx

388 lines12.6 KB

1import {
2 EnvironmentId,
3 ProjectId,
4 SourceControlProviderKind,
5 ThreadId,
6 type PullRequestDetailView,
7 type ScopedThreadRef,
8 type ThreadPullRequestLink,
9} from "@t3tools/contracts";
10import { act, type ComponentProps } from "react";
11import { createRoot, type Root } from "react-dom/client";
12import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
13import { page } from "vite-plus/test/browser";
14import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
15​
16import "~/index.css";
17​
18const { newThread, prepareThread, refresh } = vi.hoisted(() => ({
19 newThread: vi.fn(),
20 prepareThread: vi.fn(),
21 refresh: vi.fn(),
22}));
23​
24vi.mock(import("~/state/session"), async (original) => ({
25 ...(await original()),
26 useEnvironmentScope: () => true,
27 readEnvironmentScope: () => true,
28}));
29vi.mock(import("~/hooks/useSettings"), async (original) => ({
30 ...(await original()),
31 useEnvironmentSettings: (() => undefined) as never,
32}));
33vi.mock(import("~/hooks/useHandleNewThread"), async (original) => ({
34 ...(await original()),
35 useNewThreadHandler: (() => newThread) as never,
36}));
37vi.mock(import("~/lib/sourceControlActions"), async (original) => ({
38 ...(await original()),
39 usePreparePullRequestThreadAction: (() => ({
40 run: prepareThread,
41 isAllowed: true,
42 error: null,
43 })) as never,
44}));
45vi.mock(import("~/state/use-atom-command"), async (original) => ({
46 ...(await original()),
47 useAtomCommand: (() => vi.fn()) as never,
48}));
49vi.mock(import("~/state/pullRequests"), async (original) => {
50 const actual = await original();
51 const { Atom } = await import("effect/reactivity");
52 const cannotWriteGuides = Atom.make(false);
53 return {
54 ...actual,
55 pullRequestEnvironment: {
56 ...actual.pullRequestEnvironment,
57 detail: (() => "detail") as never,
58 activity: (() => "activity") as never,
59 reviewGuide: (() => "review-guide") as never,
60 generateReviewGuide: {
61 ...actual.pullRequestEnvironment.generateReviewGuide,
62 permissionAtom: () => cannotWriteGuides,
63 },
64 },
65 };
66});
67vi.mock(import("~/state/query"), async (original) => ({
68 ...(await original()),
69 useEnvironmentQuery: ((query: unknown) => ({
70 data: query === "detail" ? detail : null,
71 dataUpdatedAt: 0,
72 failure: null,
73 isPending: false,
74 isSuccess: true,
75 error: null,
76 refresh,
77 })) as never,
78}));
79vi.mock(import("~/state/usePullRequestStack"), async (original) => ({
80 ...(await original()),
81 usePullRequestStack: (() => ({
82 data: null,
83 isSuccess: true,
84 isPending: false,
85 error: null,
86 refresh,
87 })) as never,
88}));
89// The real tabs load diffs, markdown and checks from the environment; these stand-ins
90// expose the actions they hand back to the panel and a tall scroller.
91vi.mock(import("./PullRequestSummaryTab"), async (original) => ({
92 ...(await original()),
93 PullRequestSummaryTab: (({
94 onFixFinding,
95 scrollerRef,
96 }: ComponentProps<typeof import("./PullRequestSummaryTab").PullRequestSummaryTab>) => (
97 <div ref={scrollerRef} data-testid="summary-scroller" className="h-full overflow-y-auto">
98 <button
99 type="button"
100 onClick={() =>
101 onFixFinding?.({
102 kind: "check",
103 check: { name: "Unit tests", status: "failure", description: "Test failed", url: null },
104 })
105 }
106 >
107 Fix check
108 </button>
109 <div data-testid="nested-scroller" className="h-40 overflow-y-auto">
110 <div className="h-[2000px]" />
111 </div>
112 <div className="h-[3000px]" />
113 </div>
114 )) as never,
115}));
116vi.mock(import("./PullRequestCodeTab"), async (original) => ({
117 ...(await original()),
118 default: (({
119 onAddToAgentSelection,
120 scrollerRef,
121 }: ComponentProps<typeof import("./PullRequestCodeTab").default>) => (
122 <div ref={scrollerRef} data-testid="code-scroller" className="h-full overflow-y-auto">
123 <button
124 type="button"
125 onClick={() =>
126 onAddToAgentSelection?.({
127 request: "Fix this line",
128 comment: {
129 id: "note-1",
130 sectionId: "file:a.ts",
131 sectionTitle: "a.ts",
132 filePath: "a.ts",
133 startIndex: 0,
134 endIndex: 0,
135 rangeLabel: "L1",
136 text: "Please fix",
137 diff: "+broken()",
138 },
139 })
140 }
141 >
142 Add to agent
143 </button>
144 <div className="h-[3000px]" />
145 </div>
146 )) as never,
147}));
148​
149import { PullRequestDetailPanel } from "./PullRequestDetailPanel";
150import { pullRequestPanelContext } from "./pullRequestDetail.logic";
151​
152const detail: PullRequestDetailView = {
153 provider: SourceControlProviderKind.make("github"),
154 projectId: ProjectId.make("project"),
155 projectTitle: "Project",
156 workspaceRoot: "/workspace",
157 repository: "owner/repo",
158 number: 1,
159 title: "Test pull request",
160 body: "Original description",
161 url: "https://github.com/owner/repo/pull/1",
162 author: { login: "author", name: null, avatarUrl: null },
163 viewer: "author",
164 state: "open",
165 isDraft: false,
166 mergeability: "conflicting",
167 additions: 1,
168 deletions: 0,
169 changedFiles: 1,
170 headBranch: "feature",
171 baseBranch: "main",
172 createdAt: "2026-09-01T00:00:00Z",
173 updatedAt: "2026-09-01T00:00:00Z",
174 mergedAt: null,
175 closedAt: null,
176 reviewers: [],
177 labels: [],
178 checks: [{ name: "Unit tests", status: "success", description: null, url: null }],
179 comments: [],
180 commentCount: 0,
181 commentsTruncated: false,
182 reviewThreads: [],
183 commits: [],
184 mergeCapabilities: { merge: false, squash: false, rebase: false },
185 capabilities: {
186 diff: true,
187 comment: false,
188 search: true,
189 actions: [],
190 mergeMethods: [],
191 review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
192 reviewers: { request: false, listCandidates: false },
193 edit: { changeRequest: true, comment: false },
194 },
195 viewerPermissions: {
196 actions: [],
197 comment: false,
198 resolve: false,
199 verdicts: [],
200 requestReviewers: false,
201 },
202};
203​
204const threadRef: ScopedThreadRef = {
205 environmentId: EnvironmentId.make("env-1"),
206 threadId: ThreadId.make("thread-1"),
207};
208const draftId = DraftId.make("draft-1");
209const newDraftId = DraftId.make("new-draft");
210const shortcutContext = () => ({
211 terminalFocus: false,
212 terminalOpen: false,
213 previewFocus: false,
214 previewOpen: false,
215 isWeb: true,
216 isDesktop: false,
217});
218​
219const roots: Root[] = [];
220​
221function render(props: Partial<ComponentProps<typeof PullRequestDetailPanel>> = {}) {
222 const container = document.createElement("div");
223 container.className = "flex h-[700px] w-[900px]";
224 document.body.append(container);
225 const root = createRoot(container);
226 roots.push(root);
227 return act(async () =>
228 root.render(
229 <PullRequestDetailPanel
230 environmentId={threadRef.environmentId}
231 reference={detail}
232 context="page"
233 shortcutsEnabled={false}
234 getShortcutContext={shortcutContext}
235 {...props}
236 />,
237 ),
238 );
240​
241beforeEach(() => {
242 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
243 useComposerDraftStore.setState({ draftsByThreadKey: {} });
244 newThread
245 .mockReset()
246 .mockResolvedValue({ draftId: newDraftId, threadId: ThreadId.make("new-thread") });
247 prepareThread.mockReset().mockResolvedValue({
248 _tag: "Success",
249 value: { branch: "feature", worktreePath: "/workspace/pr" },
250 });
251});
252afterEach(async () => {
253 for (const root of roots.splice(0)) await act(async () => root.unmount());
254 document.body.replaceChildren();
255 vi.unstubAllGlobals();
256});
257​
258const surface = { projectId: detail.projectId, repository: detail.repository, number: 1 };
259const link = (number: number, source: ThreadPullRequestLink["source"]): ThreadPullRequestLink => ({
260 host: "github.com",
261 repository: detail.repository,
262 number,
263 url: `https://github.com/${detail.repository}/pull/${number}`,
264 source,
265 linkedAt: "2026-09-01T00:00:00Z",
266 snapshot: null,
267 stack: null,
268});
269const stackThread = {
270 projectId: detail.projectId,
271 pullRequests: [link(3, "manual"), link(2, "stack"), link(1, "stack")],
272 linkedPullRequest: { ...surface, number: 3, url: link(3, "manual").url },
273};
274const unrelatedThread = {
275 projectId: detail.projectId,
276 pullRequests: [link(9, "created")],
277 linkedPullRequest: { ...surface, number: 9, url: link(9, "created").url },
278};
279​
280const tab = (name: string) => page.getByRole("button", { name, exact: true });
281​
282async function runAction(action: string) {
283 if (action === "Add to agent") {
284 await tab("Code").click();
285 }
286 if (["Ask a question", "Explain this PR"].includes(action) || action.startsWith("Fix findings")) {
287 await page.getByRole("button", { name: "More pull request actions" }).click();
288 // Menu items carry a description under their label.
289 await page.getByRole("menuitem", { name: new RegExp(`^${action}`) }).click();
290 return;
291 }
292 await page.getByRole("button", { name: action, exact: true }).click();
294​
295describe.each([
296 ["own PR, a lower layer of the thread's stack", stackThread, threadRef],
297 ["another PR beside the current thread", unrelatedThread, threadRef],
298 ["PR beside an unsent draft", null, draftId],
299 ["standalone PR page", null, undefined],
300] as const)("%s", (_name, thread, target) => {
301 const context = thread ? pullRequestPanelContext(thread, surface) : "page";
302 const renderPanel = () =>
303 render({ context, ...(target ? { composerDraftTarget: target, threadRef } : {}) });
304​
305 it(`${thread === stackThread ? "hides" : "offers"} the checkout`, async () => {
306 await renderPanel();
307 await expect.element(page.getByText("Test pull request").first()).toBeVisible();
308 expect(page.getByRole("button", { name: "Check out" }).elements()).toHaveLength(
309 thread === stackThread ? 0 : 1,
310 );
311 });
312​
313 it.each([
314 "Resolve conflicts",
315 "Ask a question",
316 "Explain this PR",
317 "Fix findings in this thread",
318 "Fix check",
319 "Add to agent",
320 ])("%s writes to the correct composer", async (action) => {
321 if (target) useComposerDraftStore.getState().setPrompt(target, "Keep my draft");
322 await renderPanel();
323 await runAction(target ? action : action.replace("in this thread", "in a thread"));
324 const draft = () => useComposerDraftStore.getState().getComposerDraft(target ?? newDraftId);
325 await vi.waitFor(() => {
326 if (action === "Resolve conflicts")
327 expect(draft()?.prompt).toContain("resolve every conflict");
328 else if (action === "Fix check") expect(draft()?.prompt).toContain("Fix the failing check");
329 else if (action.startsWith("Fix findings"))
330 expect(draft()?.prompt).toContain("Fix the actionable findings");
331 else expect(draft()?.reviewComments?.length).toBeGreaterThan(0);
332 });
333 if (action === "Add to agent") {
334 expect(draft()?.prompt).toContain("Fix this line");
335 expect(draft()?.reviewComments).toEqual(
336 expect.arrayContaining([expect.objectContaining({ id: "note-1", diff: "+broken()" })]),
337 );
338 }
339 if (target) {
340 expect(draft()?.prompt).toContain("Keep my draft");
341 expect(newThread).not.toHaveBeenCalled();
342 expect(prepareThread).not.toHaveBeenCalled();
343 } else {
344 expect(newThread).toHaveBeenCalled();
345 }
346 });
347});
348​
349it("folds the title only for the active tab's own scroller", async () => {
350 await render();
351 const title = page.getByRole("heading", { level: 1, name: "Test pull request" });
352 await expect.element(title).toBeVisible();
353 const titleFold = () => title.element().closest("[inert]") !== null;
354 const scrollTo = async (testId: string, top: number) => {
355 const scroller = page.getByTestId(testId).element() as HTMLElement;
356 await act(async () => {
357 scroller.scrollTop = top;
358 scroller.dispatchEvent(new Event("scroll"));
359 });
360 return scroller;
361 };
362​
363 await scrollTo("nested-scroller", 600);
364 expect(titleFold()).toBe(false);
365​
366 const summary = await scrollTo("summary-scroller", 600);
367 await vi.waitFor(() => expect(titleFold()).toBe(true));
368 // Folding the header keeps the content under the reader's eye.
369 expect(summary.scrollTop).toBeLessThan(600);
370​
371 await scrollTo("summary-scroller", 0);
372 await vi.waitFor(() => expect(titleFold()).toBe(false));
373 await scrollTo("summary-scroller", 600);
374 await vi.waitFor(() => expect(titleFold()).toBe(true));
375​
376 await tab("Code").click();
377 await expect.element(page.getByTestId("code-scroller")).toBeInTheDocument();
378 await vi.waitFor(() => expect(titleFold()).toBe(false));
379 await scrollTo("code-scroller", 600);
380 await vi.waitFor(() => expect(titleFold()).toBe(true));
381​
382 await tab("Summary").click();
383 await vi.waitFor(() => expect(titleFold()).toBe(true));
384 await scrollTo("summary-scroller", 0);
385 await vi.waitFor(() => expect(titleFold()).toBe(false));
386 await tab("Code").click();
387 await vi.waitFor(() => expect(titleFold()).toBe(true));
388});