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

PullRequestDetailPanel.test.tsx

338 lines11.0 KB

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