Open History to see the last commit
1import {
2 EnvironmentId,
3 ProjectId,
4 ThreadId,
5 type ScopedThreadRef,
6 type PullRequestDetailView,
7 type ThreadPullRequestLink,
8} from "@t3tools/contracts";
9import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
10import { act, type ReactNode, type ReactElement, type ComponentProps } from "react";
11import { create, type ReactTestRenderer } from "react-test-renderer";
12import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
13import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
14
15const { newThread, prepareThread, refresh, Wrapper, Trigger } = vi.hoisted(() => ({
16 newThread: vi.fn(),
17 prepareThread: vi.fn(),
18 refresh: vi.fn(),
19 Wrapper: ({ children }: { children?: ReactNode }) => children,
20 Trigger: ({ children, render }: { children?: ReactNode; render?: ReactElement }) => (
21 <>
22 {render}
23 {children}
24 </>
25 ),
26}));
27vi.mock("@effect/atom-react", () => ({ useAtomValue: () => [] }));
28vi.mock("~/state/server", () => ({ primaryServerKeybindingsAtom: {} }));
29vi.mock("~/state/entities", () => ({ useProjects: () => [], useServerConfigs: () => new Map() }));
30vi.mock("~/state/environments", () => ({
31 useEnvironments: () => ({ environments: [] }),
32 usePrimaryEnvironmentId: () => EnvironmentId.make("env-1"),
33}));
34vi.mock("~/hooks/useSettings", () => ({
35 useClientSettings: (select: (settings: typeof DEFAULT_CLIENT_SETTINGS) => unknown) =>
36 select(DEFAULT_CLIENT_SETTINGS),
37}));
38vi.mock("~/hooks/useLiveRefresh", () => ({ useLiveRefresh: () => {} }));
39vi.mock("~/hooks/useHandleNewThread", () => ({ useNewThreadHandler: () => newThread }));
40vi.mock("~/lib/sourceControlActions", () => ({
41 usePreparePullRequestThreadAction: () => ({ run: prepareThread }),
42}));
43vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
44vi.mock("~/state/pullRequests", () => ({
45 pullRequestEnvironment: { detail: () => "detail", activity: () => "activity" },
46 usePullRequestTurnRefresh: () => 0,
47 useSharedPullRequestSummary: () => null,
48}));
49vi.mock("~/state/vcs", () => ({ vcsEnvironment: { listRefs: () => null } }));
50vi.mock("~/state/query", () => ({
51 useEnvironmentQuery: (query: string) => ({
52 data: query === "detail" ? detail : null,
53 isPending: false,
54 isSuccess: true,
55 error: null,
56 refresh,
57 }),
58}));
59vi.mock("~/state/usePullRequestStack", () => ({
60 usePullRequestStack: () => ({
61 data: null,
62 isSuccess: true,
63 isPending: false,
64 error: null,
65 refresh,
66 }),
67}));
68vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn(), update: vi.fn() } }));
69vi.mock("../ui/tooltip", () => ({
70 TooltipProvider: Wrapper,
71 Tooltip: Wrapper,
72 TooltipTrigger: Trigger,
73 TooltipPopup: () => null,
74}));
75vi.mock("../ui/menu", () => ({
76 Menu: Wrapper,
77 MenuPopup: Wrapper,
78 MenuTrigger: Trigger,
79 MenuItem: "button",
80 MenuRadioGroup: Wrapper,
81 MenuRadioItem: "button",
82 MenuSeparator: () => null,
83 MenuShortcut: () => null,
84}));
85vi.mock("../ui/alert-dialog", () => ({
86 AlertDialog: () => null,
87 AlertDialogPopup: Wrapper,
88 AlertDialogHeader: Wrapper,
89 AlertDialogTitle: Wrapper,
90 AlertDialogDescription: Wrapper,
91 AlertDialogFooter: Wrapper,
92 AlertDialogClose: Wrapper,
93}));
94vi.mock("./PullRequestMarkdown", () => ({
95 PullRequestMarkdownContext: Wrapper,
96 PullRequestMarkdown: () => null,
97}));
98vi.mock("~/browser/useOpenLink", () => ({ useOpenLink: () => vi.fn() }));
99vi.mock("./PullRequestThreadLinks", () => ({ PullRequestThreadLinks: () => null }));
100vi.mock("./PullRequestSummaryTab", () => ({
101 PullRequestSummaryTab: ({
102 onFixFinding,
103 }: ComponentProps<typeof import("./PullRequestSummaryTab").PullRequestSummaryTab>) => (
104 <button
105 onClick={() =>
106 onFixFinding?.({
107 kind: "check",
108 check: { name: "Unit tests", status: "failure", description: "Test failed", url: null },
109 })
110 }
111 >
112 Fix check
113 </button>
114 ),
115}));
116vi.mock("./PullRequestCodeTab", () => ({
117 default: ({
118 onAddToAgentSelection,
119 }: ComponentProps<typeof import("./PullRequestCodeTab").default>) => (
120 <button
121 onClick={() =>
122 onAddToAgentSelection?.({
123 request: "Fix this line",
124 comment: {
125 id: "note-1",
126 sectionId: "file:a.ts",
127 sectionTitle: "a.ts",
128 filePath: "a.ts",
129 startIndex: 0,
130 endIndex: 0,
131 rangeLabel: "L1",
132 text: "Please fix",
133 diff: "+broken()",
134 },
135 })
136 }
137 >
138 Add to agent
139 </button>
140 ),
141}));
142
143import { PullRequestDetailPanel } from "./PullRequestDetailPanel";
144import { pullRequestPanelContext } from "./pullRequestDetail.logic";
145
146const detail: PullRequestDetailView = {
147 provider: "github",
148 projectId: ProjectId.make("project"),
149 projectTitle: "Project",
150 workspaceRoot: "/workspace",
151 repository: "owner/repo",
152 number: 1,
153 title: "Test pull request",
154 body: "Original description",
155 url: "https://github.com/owner/repo/pull/1",
156 author: { login: "author", name: null, avatarUrl: null },
157 viewer: "author",
158 state: "open",
159 isDraft: false,
160 mergeability: "conflicting",
161 additions: 1,
162 deletions: 0,
163 changedFiles: 1,
164 headBranch: "feature",
165 baseBranch: "main",
166 createdAt: "2026-09-01T00:00:00Z",
167 updatedAt: "2026-09-01T00:00:00Z",
168 mergedAt: null,
169 closedAt: null,
170 reviewers: [],
171 labels: [],
172 checks: [{ name: "Unit tests", status: "success", description: null, url: null }],
173 comments: [],
174 commentCount: 0,
175 commentsTruncated: false,
176 reviewThreads: [],
177 commits: [],
178 mergeCapabilities: { merge: false, squash: false, rebase: false },
179 capabilities: {
180 diff: true,
181 comment: false,
182 search: true,
183 actions: [],
184 mergeMethods: [],
185 review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
186 reviewers: { request: false, listCandidates: false },
187 edit: { changeRequest: true, comment: false },
188 },
189 viewerPermissions: {
190 actions: [],
191 comment: false,
192 resolve: false,
193 verdicts: [],
194 requestReviewers: false,
195 },
196};
197
198const threadRef: ScopedThreadRef = {
199 environmentId: EnvironmentId.make("env-1"),
200 threadId: ThreadId.make("thread-1"),
201};
202const draftId = DraftId.make("draft-1");
203const newDraftId = DraftId.make("new-draft");
204let renderer: ReactTestRenderer;
205
206beforeEach(() => {
207 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
208 vi.stubGlobal("window", { addEventListener: vi.fn(), removeEventListener: vi.fn() });
209 useComposerDraftStore.setState({ draftsByThreadKey: {} });
210 newThread
211 .mockReset()
212 .mockResolvedValue({ draftId: newDraftId, threadId: ThreadId.make("new-thread") });
213 prepareThread.mockReset().mockResolvedValue({
214 _tag: "Success",
215 value: { branch: "feature", worktreePath: "/workspace/pr" },
216 });
217});
218afterEach(() => {
219 act(() => renderer?.unmount());
220 vi.unstubAllGlobals();
221});
222
223async function click(label: string) {
224 const button = renderer.root
225 .findAllByType("button")
226 .find(
227 (node) =>
228 node.props["aria-label"] === label ||
229 node.findAll((child) => child.children.includes(label)).length > 0,
230 );
231 expect(button, label).toBeDefined();
232 await act(async () =>
233 button!.props.onClick({
234 nativeEvent: new Event("click"),
235 preventDefault() {},
236 stopPropagation() {},
237 }),
238 );
239}
240
241const actions = [
242 "Resolve conflicts",
243 "Ask a question",
244 "Explain this PR",
245 "Fix findings in this thread",
246 "Fix check",
247 "Add to agent",
248];
249
250// The surface ChatView opens for `detail`, and the thread states it can be opened beside. The
251// context prop is derived here the way ChatView derives it, so a wrong answer from the thread's
252// link list fails these cases rather than only a hand-picked prop.
253const surface = { projectId: detail.projectId, repository: detail.repository, number: 1 };
254const link = (number: number, source: ThreadPullRequestLink["source"]): ThreadPullRequestLink => ({
255 host: "github.com",
256 repository: detail.repository,
257 number,
258 url: `https://github.com/${detail.repository}/pull/${number}`,
259 source,
260 linkedAt: "2026-09-01T00:00:00Z",
261 snapshot: null,
262 stack: null,
263});
264const stackThread = {
265 projectId: detail.projectId,
266 pullRequests: [link(3, "manual"), link(2, "stack"), link(1, "stack")],
267 // The server's one-slot field names the top layer; the panel shows the bottom one.
268 linkedPullRequest: { ...surface, number: 3, url: link(3, "manual").url },
269};
270const unrelatedThread = {
271 projectId: detail.projectId,
272 pullRequests: [link(9, "created")],
273 linkedPullRequest: { ...surface, number: 9, url: link(9, "created").url },
274};
275
276describe.each([
277 ["own PR, a lower layer of the thread's stack", stackThread, threadRef],
278 ["another PR beside the current thread", unrelatedThread, threadRef],
279 ["PR beside an unsent draft", null, draftId],
280 ["standalone PR page", null, undefined],
281] as const)("%s", (_name, thread, target) => {
282 const context = thread ? pullRequestPanelContext(thread, surface) : "page";
283
284 function render() {
285 renderer = create(
286 <PullRequestDetailPanel
287 environmentId={threadRef.environmentId}
288 reference={detail}
289 context={context}
290 {...(target ? { composerDraftTarget: target, threadRef } : {})}
291 shortcutsEnabled={false}
292 getShortcutContext={() => ({
293 terminalFocus: false,
294 terminalOpen: false,
295 previewFocus: false,
296 previewOpen: false,
297 isWeb: true,
298 isDesktop: false,
299 })}
300 />,
301 );
302 }
303
304 it(`${thread === stackThread ? "hides" : "offers"} the checkout`, async () => {
305 await act(async () => render());
306 const checkout = renderer.root
307 .findAllByType("button")
308 .filter((node) => node.props["aria-label"] === "Check out");
309 expect(checkout).toHaveLength(thread === stackThread ? 0 : 1);
310 });
311
312 it.each(actions)("%s writes to the correct composer", async (action) => {
313 if (target) useComposerDraftStore.getState().setPrompt(target, "Keep my draft");
314 await act(async () => render());
315 if (action === "Add to agent") await click("Code");
316 await click(target ? action : action.replace("in this thread", "in a thread"));
317 const draft = useComposerDraftStore.getState().getComposerDraft(target ?? newDraftId);
318 if (action === "Resolve conflicts") expect(draft?.prompt).toContain("resolve every conflict");
319 else if (action === "Fix check") expect(draft?.prompt).toContain("Fix the failing check");
320 else if (action.startsWith("Fix findings"))
321 expect(draft?.prompt).toContain("Fix the actionable findings");
322 else expect(draft?.reviewComments?.length).toBeGreaterThan(0);
323 if (action === "Add to agent") {
324 expect(draft?.prompt).toContain("Fix this line");
325 expect(draft?.reviewComments).toEqual(
326 expect.arrayContaining([expect.objectContaining({ id: "note-1", diff: "+broken()" })]),
327 );
328 }
329 if (target) {
330 expect(draft?.prompt).toContain("Keep my draft");
331 expect(newThread).not.toHaveBeenCalled();
332 expect(prepareThread).not.toHaveBeenCalled();
333 } else {
334 expect(newThread).toHaveBeenCalled();
335 }
336 });
337});