Open History to see the last commit
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 // The header menu reads the stored guide to label "Write guide" or "Rewrite guide".
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// The guide renders diffs, which start the diff worker; this suite never opens it.
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 );
261}
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
272// The surface ChatView opens for `detail`, and the thread states it can be opened beside. The
273// context prop is derived here the way ChatView derives it, so a wrong answer from the thread's
274// link list fails these cases rather than only a hand-picked prop.
275const surface = { projectId: detail.projectId, repository: detail.repository, number: 1 };
276const link = (number: number, source: ThreadPullRequestLink["source"]): ThreadPullRequestLink => ({
277 host: "github.com",
278 repository: detail.repository,
279 number,
280 url: `https://github.com/${detail.repository}/pull/${number}`,
281 source,
282 linkedAt: "2026-09-01T00:00:00Z",
283 snapshot: null,
284 stack: null,
285});
286const stackThread = {
287 projectId: detail.projectId,
288 pullRequests: [link(3, "manual"), link(2, "stack"), link(1, "stack")],
289 // The server's one-slot field names the top layer; the panel shows the bottom one.
290 linkedPullRequest: { ...surface, number: 3, url: link(3, "manual").url },
291};
292const unrelatedThread = {
293 projectId: detail.projectId,
294 pullRequests: [link(9, "created")],
295 linkedPullRequest: { ...surface, number: 9, url: link(9, "created").url },
296};
297
298describe.each([
299 ["own PR, a lower layer of the thread's stack", stackThread, threadRef],
300 ["another PR beside the current thread", unrelatedThread, threadRef],
301 ["PR beside an unsent draft", null, draftId],
302 ["standalone PR page", null, undefined],
303] as const)("%s", (_name, thread, target) => {
304 const context = thread ? pullRequestPanelContext(thread, surface) : "page";
305
306 function render() {
307 renderer = create(
308 <PullRequestDetailPanel
309 environmentId={threadRef.environmentId}
310 reference={detail}
311 context={context}
312 {...(target ? { composerDraftTarget: target, threadRef } : {})}
313 shortcutsEnabled={false}
314 getShortcutContext={() => ({
315 terminalFocus: false,
316 terminalOpen: false,
317 previewFocus: false,
318 previewOpen: false,
319 isWeb: true,
320 isDesktop: false,
321 })}
322 />,
323 );
324 }
325
326 it(`${thread === stackThread ? "hides" : "offers"} the checkout`, async () => {
327 await act(async () => render());
328 const checkout = renderer.root
329 .findAllByType("button")
330 .filter((node) => node.props["aria-label"] === "Check out");
331 expect(checkout).toHaveLength(thread === stackThread ? 0 : 1);
332 });
333
334 it.each(actions)("%s writes to the correct composer", async (action) => {
335 if (target) useComposerDraftStore.getState().setPrompt(target, "Keep my draft");
336 await act(async () => render());
337 if (action === "Add to agent") await click("Code");
338 await click(target ? action : action.replace("in this thread", "in a thread"));
339 const draft = useComposerDraftStore.getState().getComposerDraft(target ?? newDraftId);
340 if (action === "Resolve conflicts") expect(draft?.prompt).toContain("resolve every conflict");
341 else if (action === "Fix check") expect(draft?.prompt).toContain("Fix the failing check");
342 else if (action.startsWith("Fix findings"))
343 expect(draft?.prompt).toContain("Fix the actionable findings");
344 else expect(draft?.reviewComments?.length).toBeGreaterThan(0);
345 if (action === "Add to agent") {
346 expect(draft?.prompt).toContain("Fix this line");
347 expect(draft?.reviewComments).toEqual(
348 expect.arrayContaining([expect.objectContaining({ id: "note-1", diff: "+broken()" })]),
349 );
350 }
351 if (target) {
352 expect(draft?.prompt).toContain("Keep my draft");
353 expect(newThread).not.toHaveBeenCalled();
354 expect(prepareThread).not.toHaveBeenCalled();
355 } else {
356 expect(newThread).toHaveBeenCalled();
357 }
358 });
359});
360
361it("changes the title only for the active tab's main scroller", async () => {
362 const scrollers = new Map<string, { scrollTop: number; scrollHeight: number }>();
363 await act(async () => {
364 renderer = create(
365 <PullRequestDetailPanel
366 environmentId={threadRef.environmentId}
367 reference={detail}
368 context="page"
369 shortcutsEnabled={false}
370 getShortcutContext={() => ({
371 terminalFocus: false,
372 terminalOpen: false,
373 previewFocus: false,
374 previewOpen: false,
375 isWeb: true,
376 isDesktop: false,
377 })}
378 />,
379 {
380 createNodeMock: (element) => {
381 const props = element.props as Record<string, unknown>;
382 const name = props["data-test-scroll"] as string | undefined;
383 if (name) {
384 const scroller = { scrollTop: 0, scrollHeight: 300 };
385 scrollers.set(name, scroller);
386 return scroller;
387 }
388 return { scrollHeight: props.inert === false ? 100 : 20 };
389 },
390 },
391 );
392 });
393
394 const mainScroll = renderer.root.findByProps({
395 className: "relative flex min-h-0 flex-1 flex-col overflow-hidden",
396 });
397 const titleFold = () => {
398 let node = renderer.root.findByType("h1");
399 while (typeof node.props.inert !== "boolean") node = node.parent!;
400 return node;
401 };
402 const summary = scrollers.get("summary")!;
403 const nested = { scrollTop: 200 };
404 await act(async () => mainScroll.props.onScrollCapture({ target: nested }));
405 expect(titleFold().props.inert).toBe(false);
406 summary.scrollTop = 180;
407 nested.scrollTop = 0;
408 await act(async () => {
409 mainScroll.props.onScrollCapture({ target: summary });
410 mainScroll.props.onScrollCapture({ target: nested });
411 });
412 expect(titleFold().props.inert).toBe(true);
413 expect(summary.scrollTop).toBe(100);
414 expect(nested.scrollTop).toBe(0);
415
416 await act(async () => mainScroll.props.onScrollCapture({ target: { scrollTop: 0 } }));
417 expect(titleFold().props.inert).toBe(true);
418 summary.scrollTop = 0;
419 await act(async () => mainScroll.props.onScrollCapture({ target: summary }));
420 expect(titleFold().props.inert).toBe(false);
421
422 await click("Code");
423 const code = scrollers.get("code")!;
424 summary.scrollTop = 180;
425 await act(async () => mainScroll.props.onScrollCapture({ target: summary }));
426 expect(titleFold().props.inert).toBe(false);
427 code.scrollTop = 180;
428 await act(async () => mainScroll.props.onScrollCapture({ target: code }));
429 expect(titleFold().props.inert).toBe(true);
430 expect(code.scrollTop).toBe(100);
431 await click("Summary");
432 expect(titleFold().props.inert).toBe(false);
433 await click("Code");
434 expect(titleFold().props.inert).toBe(true);
435 code.scrollTop = 0;
436 await act(async () => mainScroll.props.onScrollCapture({ target: code }));
437 expect(titleFold().props.inert).toBe(false);
438});