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

PullRequestDetailPanel.test.tsx

435 lines14.2 KB

1import { SourceControlProviderKind } from "@t3tools/contracts";
2import {
3 EnvironmentId,
4 ProjectId,
5 ThreadId,
6 type ScopedThreadRef,
7 type PullRequestDetailView,
8 type ThreadPullRequestLink,
9} from "@t3tools/contracts";
10import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
11import { act, type ReactNode, type ReactElement, type ComponentProps } from "react";
12import { create, type ReactTestRenderer } from "react-test-renderer";
13import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
14import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
15​
16const { newThread, prepareThread, refresh, Wrapper, Trigger } = vi.hoisted(() => ({
17 newThread: vi.fn(),
18 prepareThread: vi.fn(),
19 refresh: vi.fn(),
20 Wrapper: ({ children }: { children?: ReactNode }) => children,
21 Trigger: ({ children, render }: { children?: ReactNode; render?: ReactElement }) => (
22 <>
23 {render}
24 {children}
25 </>
26 ),
27}));
28vi.mock("~/state/session", async (original) => ({
29 ...(await original<typeof import("~/state/session")>()),
30 useEnvironmentScope: () => true,
31 readEnvironmentScope: () => true,
32}));
33vi.mock("@effect/atom-react", () => ({ useAtomValue: () => [] }));
34vi.mock("~/state/server", () => ({ primaryServerKeybindingsAtom: {} }));
35vi.mock("~/state/entities", () => ({ useProjects: () => [], useServerConfigs: () => new Map() }));
36vi.mock("~/state/environments", () => ({
37 useEnvironments: () => ({ environments: [] }),
38 usePrimaryEnvironmentId: () => EnvironmentId.make("env-1"),
39}));
40vi.mock("~/hooks/useSettings", () => ({
41 useEnvironmentSettings: () => undefined,
42 useClientSettings: (select: (settings: typeof DEFAULT_CLIENT_SETTINGS) => unknown) =>
43 select(DEFAULT_CLIENT_SETTINGS),
44}));
45vi.mock("~/hooks/useLiveRefresh", () => ({ useLiveRefresh: () => {} }));
46vi.mock("~/hooks/useHandleNewThread", () => ({ useNewThreadHandler: () => newThread }));
47vi.mock("~/lib/sourceControlActions", () => ({
48 usePreparePullRequestThreadAction: () => ({ run: prepareThread, isAllowed: true, error: null }),
49}));
50vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
51vi.mock("~/state/pullRequests", async (importOriginal) => ({
52 ...(await importOriginal<typeof import("~/state/pullRequests")>()),
53 pullRequestEnvironment: {
54 detail: () => "detail",
55 activity: () => "activity",
56​
57 reviewGuide: () => "review-guide",
58 generateReviewGuide: { permissionAtom: () => "generate-review-guide" },
59 },
60 usePullRequestTurnRefresh: () => 0,
61 useSharedPullRequestSummary: () => null,
62}));
63vi.mock("~/state/vcs", () => ({ vcsEnvironment: { listRefs: () => null } }));
64vi.mock("~/state/query", () => ({
65 useEnvironmentQuery: (query: string) => ({
66 data: query === "detail" ? detail : null,
67 isPending: false,
68 isSuccess: true,
69 error: null,
70 refresh,
71 }),
72}));
73vi.mock("~/state/usePullRequestStack", () => ({
74 usePullRequestStack: () => ({
75 data: null,
76 isSuccess: true,
77 isPending: false,
78 error: null,
79 refresh,
80 }),
81}));
82vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn(), update: vi.fn() } }));
83vi.mock("../ui/tooltip", () => ({
84 TooltipProvider: Wrapper,
85 Tooltip: Wrapper,
86 TooltipTrigger: Trigger,
87 TooltipPopup: () => null,
88}));
89vi.mock("../ui/menu", () => ({
90 Menu: Wrapper,
91 MenuPopup: Wrapper,
92 MenuTrigger: Trigger,
93 MenuItem: "button",
94 MenuRadioGroup: Wrapper,
95 MenuRadioItem: "button",
96 MenuSeparator: () => null,
97 MenuShortcut: () => null,
98}));
99vi.mock("../ui/alert-dialog", () => ({
100 AlertDialog: () => null,
101 AlertDialogPopup: Wrapper,
102 AlertDialogHeader: Wrapper,
103 AlertDialogTitle: Wrapper,
104 AlertDialogDescription: Wrapper,
105 AlertDialogFooter: Wrapper,
106 AlertDialogClose: Wrapper,
107}));
108vi.mock("./PullRequestMarkdown", () => ({
109 PullRequestMarkdownContext: Wrapper,
110 PullRequestMarkdown: () => null,
111}));
112vi.mock("~/browser/useOpenLink", () => ({ useOpenLink: () => vi.fn() }));
113vi.mock("./PullRequestThreadLinks", () => ({ PullRequestThreadLinks: () => null }));
114vi.mock("./PullRequestSummaryTab", () => ({
115 PullRequestSummaryTab: ({
116 onFixFinding,
117 scrollerRef,
118 }: ComponentProps<typeof import("./PullRequestSummaryTab").PullRequestSummaryTab>) => (
119 <div ref={scrollerRef} data-test-scroll="summary">
120 <button
121 onClick={() =>
122 onFixFinding?.({
123 kind: "check",
124 check: { name: "Unit tests", status: "failure", description: "Test failed", url: null },
125 })
126 }
127 >
128 Fix check
129 </button>
130 </div>
131 ),
132}));
133​
134vi.mock("./PullRequestGuideTab", () => ({ PullRequestGuideTab: () => null }));
135vi.mock("./PullRequestCodeTab", () => ({
136 default: ({
137 onAddToAgentSelection,
138 scrollerRef,
139 }: ComponentProps<typeof import("./PullRequestCodeTab").default>) => (
140 <div ref={scrollerRef} data-test-scroll="code">
141 <button
142 onClick={() =>
143 onAddToAgentSelection?.({
144 request: "Fix this line",
145 comment: {
146 id: "note-1",
147 sectionId: "file:a.ts",
148 sectionTitle: "a.ts",
149 filePath: "a.ts",
150 startIndex: 0,
151 endIndex: 0,
152 rangeLabel: "L1",
153 text: "Please fix",
154 diff: "+broken()",
155 },
156 })
157 }
158 >
159 Add to agent
160 </button>
161 </div>
162 ),
163}));
164​
165import { PullRequestDetailPanel } from "./PullRequestDetailPanel";
166import { pullRequestPanelContext } from "./pullRequestDetail.logic";
167​
168const detail: PullRequestDetailView = {
169 provider: SourceControlProviderKind.make("github"),
170 projectId: ProjectId.make("project"),
171 projectTitle: "Project",
172 workspaceRoot: "/workspace",
173 repository: "owner/repo",
174 number: 1,
175 title: "Test pull request",
176 body: "Original description",
177 url: "https://github.com/owner/repo/pull/1",
178 author: { login: "author", name: null, avatarUrl: null },
179 viewer: "author",
180 state: "open",
181 isDraft: false,
182 mergeability: "conflicting",
183 additions: 1,
184 deletions: 0,
185 changedFiles: 1,
186 headBranch: "feature",
187 baseBranch: "main",
188 createdAt: "2026-09-01T00:00:00Z",
189 updatedAt: "2026-09-01T00:00:00Z",
190 mergedAt: null,
191 closedAt: null,
192 reviewers: [],
193 labels: [],
194 checks: [{ name: "Unit tests", status: "success", description: null, url: null }],
195 comments: [],
196 commentCount: 0,
197 commentsTruncated: false,
198 reviewThreads: [],
199 commits: [],
200 mergeCapabilities: { merge: false, squash: false, rebase: false },
201 capabilities: {
202 diff: true,
203 comment: false,
204 search: true,
205 actions: [],
206 mergeMethods: [],
207 review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
208 reviewers: { request: false, listCandidates: false },
209 edit: { changeRequest: true, comment: false },
210 },
211 viewerPermissions: {
212 actions: [],
213 comment: false,
214 resolve: false,
215 verdicts: [],
216 requestReviewers: false,
217 },
218};
219​
220const threadRef: ScopedThreadRef = {
221 environmentId: EnvironmentId.make("env-1"),
222 threadId: ThreadId.make("thread-1"),
223};
224const draftId = DraftId.make("draft-1");
225const newDraftId = DraftId.make("new-draft");
226let renderer: ReactTestRenderer;
227​
228beforeEach(() => {
229 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
230 vi.stubGlobal("window", { addEventListener: vi.fn(), removeEventListener: vi.fn() });
231 useComposerDraftStore.setState({ draftsByThreadKey: {} });
232 newThread
233 .mockReset()
234 .mockResolvedValue({ draftId: newDraftId, threadId: ThreadId.make("new-thread") });
235 prepareThread.mockReset().mockResolvedValue({
236 _tag: "Success",
237 value: { branch: "feature", worktreePath: "/workspace/pr" },
238 });
239});
240afterEach(() => {
241 act(() => renderer?.unmount());
242 vi.unstubAllGlobals();
243});
244​
245async function click(label: string) {
246 const button = renderer.root
247 .findAllByType("button")
248 .find(
249 (node) =>
250 node.props["aria-label"] === label ||
251 node.findAll((child) => child.children.includes(label)).length > 0,
252 );
253 expect(button, label).toBeDefined();
254 await act(async () =>
255 button!.props.onClick({
256 nativeEvent: new Event("click"),
257 preventDefault() {},
258 stopPropagation() {},
259 }),
260 );
262​
263const actions = [
264 "Resolve conflicts",
265 "Ask a question",
266 "Explain this PR",
267 "Fix findings in this thread",
268 "Fix check",
269 "Add to agent",
270];
271​
272const surface = { projectId: detail.projectId, repository: detail.repository, number: 1 };
273const link = (number: number, source: ThreadPullRequestLink["source"]): ThreadPullRequestLink => ({
274 host: "github.com",
275 repository: detail.repository,
276 number,
277 url: `https://github.com/${detail.repository}/pull/${number}`,
278 source,
279 linkedAt: "2026-09-01T00:00:00Z",
280 snapshot: null,
281 stack: null,
282});
283const stackThread = {
284 projectId: detail.projectId,
285 pullRequests: [link(3, "manual"), link(2, "stack"), link(1, "stack")],
286​
287 linkedPullRequest: { ...surface, number: 3, url: link(3, "manual").url },
288};
289const unrelatedThread = {
290 projectId: detail.projectId,
291 pullRequests: [link(9, "created")],
292 linkedPullRequest: { ...surface, number: 9, url: link(9, "created").url },
293};
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​
303 function render() {
304 renderer = create(
305 <PullRequestDetailPanel
306 environmentId={threadRef.environmentId}
307 reference={detail}
308 context={context}
309 {...(target ? { composerDraftTarget: target, threadRef } : {})}
310 shortcutsEnabled={false}
311 getShortcutContext={() => ({
312 terminalFocus: false,
313 terminalOpen: false,
314 previewFocus: false,
315 previewOpen: false,
316 isWeb: true,
317 isDesktop: false,
318 })}
319 />,
320 );
321 }
322​
323 it(`${thread === stackThread ? "hides" : "offers"} the checkout`, async () => {
324 await act(async () => render());
325 const checkout = renderer.root
326 .findAllByType("button")
327 .filter((node) => node.props["aria-label"] === "Check out");
328 expect(checkout).toHaveLength(thread === stackThread ? 0 : 1);
329 });
330​
331 it.each(actions)("%s writes to the correct composer", async (action) => {
332 if (target) useComposerDraftStore.getState().setPrompt(target, "Keep my draft");
333 await act(async () => render());
334 if (action === "Add to agent") await click("Code");
335 await click(target ? action : action.replace("in this thread", "in a thread"));
336 const draft = useComposerDraftStore.getState().getComposerDraft(target ?? newDraftId);
337 if (action === "Resolve conflicts") expect(draft?.prompt).toContain("resolve every conflict");
338 else if (action === "Fix check") expect(draft?.prompt).toContain("Fix the failing check");
339 else if (action.startsWith("Fix findings"))
340 expect(draft?.prompt).toContain("Fix the actionable findings");
341 else expect(draft?.reviewComments?.length).toBeGreaterThan(0);
342 if (action === "Add to agent") {
343 expect(draft?.prompt).toContain("Fix this line");
344 expect(draft?.reviewComments).toEqual(
345 expect.arrayContaining([expect.objectContaining({ id: "note-1", diff: "+broken()" })]),
346 );
347 }
348 if (target) {
349 expect(draft?.prompt).toContain("Keep my draft");
350 expect(newThread).not.toHaveBeenCalled();
351 expect(prepareThread).not.toHaveBeenCalled();
352 } else {
353 expect(newThread).toHaveBeenCalled();
354 }
355 });
356});
357​
358it("changes the title only for the active tab's main scroller", async () => {
359 const scrollers = new Map<string, { scrollTop: number; scrollHeight: number }>();
360 await act(async () => {
361 renderer = create(
362 <PullRequestDetailPanel
363 environmentId={threadRef.environmentId}
364 reference={detail}
365 context="page"
366 shortcutsEnabled={false}
367 getShortcutContext={() => ({
368 terminalFocus: false,
369 terminalOpen: false,
370 previewFocus: false,
371 previewOpen: false,
372 isWeb: true,
373 isDesktop: false,
374 })}
375 />,
376 {
377 createNodeMock: (element) => {
378 const props = element.props as Record<string, unknown>;
379 const name = props["data-test-scroll"] as string | undefined;
380 if (name) {
381 const scroller = { scrollTop: 0, scrollHeight: 300 };
382 scrollers.set(name, scroller);
383 return scroller;
384 }
385 return { scrollHeight: props.inert === false ? 100 : 20 };
386 },
387 },
388 );
389 });
390​
391 const mainScroll = renderer.root.findByProps({
392 className: "relative flex min-h-0 flex-1 flex-col overflow-hidden",
393 });
394 const titleFold = () => {
395 let node = renderer.root.findByType("h1");
396 while (typeof node.props.inert !== "boolean") node = node.parent!;
397 return node;
398 };
399 const summary = scrollers.get("summary")!;
400 const nested = { scrollTop: 200 };
401 await act(async () => mainScroll.props.onScrollCapture({ target: nested }));
402 expect(titleFold().props.inert).toBe(false);
403 summary.scrollTop = 180;
404 nested.scrollTop = 0;
405 await act(async () => {
406 mainScroll.props.onScrollCapture({ target: summary });
407 mainScroll.props.onScrollCapture({ target: nested });
408 });
409 expect(titleFold().props.inert).toBe(true);
410 expect(summary.scrollTop).toBe(100);
411 expect(nested.scrollTop).toBe(0);
412​
413 await act(async () => mainScroll.props.onScrollCapture({ target: { scrollTop: 0 } }));
414 expect(titleFold().props.inert).toBe(true);
415 summary.scrollTop = 0;
416 await act(async () => mainScroll.props.onScrollCapture({ target: summary }));
417 expect(titleFold().props.inert).toBe(false);
418​
419 await click("Code");
420 const code = scrollers.get("code")!;
421 summary.scrollTop = 180;
422 await act(async () => mainScroll.props.onScrollCapture({ target: summary }));
423 expect(titleFold().props.inert).toBe(false);
424 code.scrollTop = 180;
425 await act(async () => mainScroll.props.onScrollCapture({ target: code }));
426 expect(titleFold().props.inert).toBe(true);
427 expect(code.scrollTop).toBe(100);
428 await click("Summary");
429 expect(titleFold().props.inert).toBe(false);
430 await click("Code");
431 expect(titleFold().props.inert).toBe(true);
432 code.scrollTop = 0;
433 await act(async () => mainScroll.props.onScrollCapture({ target: code }));
434 expect(titleFold().props.inert).toBe(false);
435});