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

PullRequestDetailPanel.test.tsx

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