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

PullRequestDetailPanel.test.tsx

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