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