Open History to see the last commit
1import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";
2import {
3 EnvironmentId,
4 ProjectId,
5 SourceControlProviderKind,
6 ThreadId,
7 type PullRequestRef,
8} from "@t3tools/contracts";
9import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
10import { Cause } from "effect";
11import { expect, it, vi } from "vite-plus/test";
12import { page, userEvent } from "vite-plus/test/browser";
13
14import { act, render } from "../../../test/render";
15import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
16import { readPendingWorkspaceDefault } from "~/lib/draftWorkspaceDefaults";
17import { ToastProvider } from "../ui/toast";
18import type { EnvironmentPullRequestEntry } from "./pullRequestList.logic";
19import {
20 usePullRequestActionRunner,
21 usePullRequestCloseBatch,
22 usePullRequestHandoffs,
23} from "./usePullRequestActions";
24
25const state = vi.hoisted(() => ({
26 runAction: vi.fn(),
27 newThread: vi.fn(),
28 prepareThread: vi.fn(),
29}));
30vi.mock(import("~/state/use-atom-command"), () => ({
31 useAtomCommand: (() => state.runAction) as never,
32}));
33vi.mock(import("~/hooks/useHandleNewThread"), () => ({
34 useNewThreadHandler: (() => state.newThread) as never,
35}));
36vi.mock(import("~/state/sourceControlActions"), () => ({
37 usePreparePullRequestThreadAction: (() => ({ run: state.prepareThread })) as never,
38}));
39
40function deferred<T>() {
41 let resolve!: (value: T) => void;
42 const promise = new Promise<T>((done) => {
43 resolve = done;
44 });
45 return { promise, resolve };
46}
47
48function MergeButton({ reference }: { reference: PullRequestRef }) {
49 const { actionPending, pendingAction, perform } = usePullRequestActionRunner({
50 environmentId: EnvironmentId.make("environment"),
51 reference,
52 headSha: `head-${reference.number}`,
53 terminology: sourceControlClients.get(undefined).changeRequest,
54 });
55 return (
56 <button type="button" disabled={actionPending} onClick={() => void perform("merge")}>
57 {pendingAction === "merge" ? "Merging..." : "Merge"}
58 </button>
59 );
60}
61
62function setup() {
63 state.runAction.mockReset();
64 state.newThread.mockReset();
65 state.prepareThread.mockReset();
66}
67
68it("keeps pending merges with their pull request when navigating between threads", async () => {
69 setup();
70 const first: PullRequestRef = {
71 projectId: ProjectId.make("project"),
72 repository: "owner/repo",
73 number: 1,
74 };
75 const second = { ...first, number: 2 };
76 const firstResult = deferred<{ _tag: "Success"; value: void }>();
77 const secondResult = deferred<{ _tag: "Success"; value: void }>();
78 state.runAction
79 .mockReturnValueOnce(firstResult.promise)
80 .mockReturnValueOnce(secondResult.promise);
81 await using screen = await render(<MergeButton reference={first} />);
82 const button = screen.getByRole("button");
83
84 await userEvent.click(button);
85 await expect.element(button).toHaveTextContent("Merging...");
86 await screen.rerender(
87 <MergeButton reference={{ ...first, projectId: ProjectId.make("other-project") }} />,
88 );
89 await expect.element(button).toHaveTextContent("Merge");
90 await expect.element(button).toBeEnabled();
91 await screen.rerender(<MergeButton reference={first} />);
92 await expect.element(button).toHaveTextContent("Merging...");
93 await expect.element(button).toBeDisabled();
94 await screen.rerender(<MergeButton reference={second} />);
95 await expect.element(button).toHaveTextContent("Merge");
96 await expect.element(button).toBeEnabled();
97 await userEvent.click(button);
98 expect(state.runAction).toHaveBeenCalledTimes(2);
99 // Each merge is pinned to the head its own row showed.
100 expect(state.runAction.mock.calls.map(([call]) => call.input.expectedHeadSha)).toEqual([
101 "head-1",
102 "head-2",
103 ]);
104
105 await screen.rerender(<MergeButton reference={first} />);
106 await expect.element(button).toHaveTextContent("Merging...");
107 await expect.element(button).toBeDisabled();
108 await act(async () => {
109 firstResult.resolve({ _tag: "Success", value: undefined });
110 await firstResult.promise;
111 });
112 await expect.element(button).toHaveTextContent("Merge");
113 await screen.rerender(<MergeButton reference={second} />);
114 await expect.element(button).toHaveTextContent("Merging...");
115 await act(async () => {
116 secondResult.resolve({ _tag: "Success", value: undefined });
117 await secondResult.promise;
118 });
119 await expect.element(button).toHaveTextContent("Merge");
120});
121
122function FixChecksButton() {
123 const { handoff, startHandoff } = usePullRequestHandoffs({
124 environmentId: EnvironmentId.make("environment"),
125 detail: {
126 projectId: ProjectId.make("project"),
127 workspaceRoot: "/repo",
128 url: "https://github.com/owner/repo/pull/1",
129 },
130 });
131 return (
132 <button
133 type="button"
134 disabled={handoff !== null}
135 onClick={() => void startHandoff("fix", { prompt: "Fix the checks" })}
136 >
137 Fix
138 </button>
139 );
140}
141
142it.each(["button", "escape"] as const)(
143 "stops a pull request handoff when its loading toast is dismissed via %s",
144 async (dismissVia) => {
145 setup();
146 const draftId = DraftId.make(`draft-dismiss-${dismissVia}`);
147 const threadId = ThreadId.make(`thread-dismiss-${dismissVia}`);
148 const prepared = deferred<{
149 _tag: "Success";
150 value: {
151 branch: string;
152 worktreePath: string;
153 isOnPullRequestHead: boolean;
154 pullRequest: { url: string };
155 };
156 }>();
157 state.newThread.mockImplementation(async (projectRef) => {
158 useComposerDraftStore
159 .getState()
160 .setLogicalProjectDraftThreadId(scopedProjectKey(projectRef), projectRef, draftId, {
161 threadId,
162 });
163 return { draftId, threadId };
164 });
165 state.prepareThread.mockReturnValueOnce(prepared.promise);
166 await using screen = await render(
167 <ToastProvider>
168 <FixChecksButton />
169 </ToastProvider>,
170 );
171
172 const fixButton = screen.getByRole("button", { name: "Fix" });
173 await userEvent.click(fixButton);
174 const toast = screen.getByRole("dialog", { name: "Preparing the pull request checkout..." });
175 await expect.element(toast).toBeVisible();
176 await vi.waitFor(() => {
177 expect(state.prepareThread).toHaveBeenCalledTimes(1);
178 });
179 if (dismissVia === "button") {
180 await userEvent.click(toast.getByRole("button", { name: "Dismiss notification" }));
181 } else {
182 await userEvent.click(toast.getByText("Preparing the pull request checkout..."));
183 await expect.element(toast).toHaveFocus();
184 await userEvent.keyboard("{Escape}");
185 }
186 await expect.element(toast).not.toBeInTheDocument();
187 await act(async () => {
188 prepared.resolve({
189 _tag: "Success",
190 value: {
191 branch: "pr-1",
192 worktreePath: "/repo-worktrees/pr-1",
193 isOnPullRequestHead: true,
194 pullRequest: { url: "https://github.com/owner/repo/pull/1" },
195 },
196 });
197 await prepared.promise;
198 });
199
200 await expect.element(fixButton).toBeEnabled();
201 await vi.waitFor(() => {
202 expect(useComposerDraftStore.getState().getDraftSession(draftId)?.branch ?? null).toBeNull();
203 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.prompt ?? "").toBe("");
204 });
205 },
206);
207
208function CheckOutButton({
209 number = 1,
210 label = "Check out",
211 prompt,
212}: {
213 number?: number;
214 label?: string;
215 prompt?: string;
216}) {
217 const { handoff, startHandoff } = usePullRequestHandoffs({
218 environmentId: EnvironmentId.make("environment"),
219 detail: {
220 projectId: ProjectId.make("project"),
221 workspaceRoot: "/repo",
222 url: `https://github.com/owner/repo/pull/${number}`,
223 },
224 });
225 return (
226 <button
227 type="button"
228 disabled={handoff !== null}
229 onClick={() => void startHandoff("checkout", prompt === undefined ? null : { prompt })}
230 >
231 {label}
232 </button>
233 );
234}
235
236it("clears a superseded checkout without adding its task to the draft", async () => {
237 setup();
238 const draftId = DraftId.make("shared-checkout-draft");
239 const threadId = ThreadId.make("shared-checkout-thread");
240 state.newThread.mockImplementation(async (projectRef) => {
241 useComposerDraftStore
242 .getState()
243 .setLogicalProjectDraftThreadId(scopedProjectKey(projectRef), projectRef, draftId, {
244 threadId,
245 });
246 return { draftId, threadId };
247 });
248 const success = (number: number) => ({
249 _tag: "Success" as const,
250 value: {
251 branch: `pr-${number}`,
252 worktreePath: `/repo-worktrees/pr-${number}`,
253 isOnPullRequestHead: true,
254 pullRequest: { url: `https://github.com/owner/repo/pull/${number}` },
255 },
256 });
257 const first = deferred<ReturnType<typeof success>>();
258 const second = deferred<ReturnType<typeof success>>();
259 state.prepareThread.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);
260 await using screen = await render(
261 <ToastProvider>
262 <CheckOutButton label="First checkout" prompt="Review the first pull request" />
263 <CheckOutButton number={2} label="Second checkout" />
264 </ToastProvider>,
265 );
266 const firstButton = screen.getByRole("button", { name: "First checkout" });
267 const secondButton = screen.getByRole("button", { name: "Second checkout" });
268 await userEvent.click(firstButton);
269 await userEvent.click(secondButton);
270 await expect.element(secondButton).toBeDisabled();
271
272 await act(async () => first.resolve(success(1)));
273
274 await expect.element(firstButton).toBeEnabled();
275 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.prompt ?? "").toBe("");
276
277 await act(async () => second.resolve(success(2)));
278
279 await expect.element(screen.getByRole("dialog", { name: "Checked out" })).toBeVisible();
280 await expect
281 .element(screen.getByRole("dialog", { name: "Preparing the pull request checkout..." }))
282 .not.toBeInTheDocument();
283 expect(useComposerDraftStore.getState().getDraftSession(draftId)?.branch).toBe("pr-2");
284});
285
286it("moves the draft the user typed into during a checkout onto the checkout", async () => {
287 setup();
288 const prepared = deferred<{
289 _tag: "Success";
290 value: {
291 branch: string;
292 worktreePath: string;
293 isOnPullRequestHead: boolean;
294 pullRequest: { url: string };
295 };
296 }>();
297 // Like the real handler: a draft with user content is not reused, so a later call opens another.
298 state.newThread.mockImplementation(
299 async (projectRef, options?: { branch?: string; worktreePath?: string }) => {
300 const store = useComposerDraftStore.getState();
301 const draftId = DraftId.make(options === undefined ? "draft-opened" : "draft-pointed");
302 store.setLogicalProjectDraftThreadId(scopedProjectKey(projectRef), projectRef, draftId, {
303 threadId: ThreadId.make(`thread-${draftId}`),
304 branch: options?.branch ?? null,
305 worktreePath: options?.worktreePath ?? null,
306 });
307 return { draftId, threadId: ThreadId.make(`thread-${draftId}`) };
308 },
309 );
310 state.prepareThread.mockReturnValueOnce(prepared.promise);
311 await using screen = await render(
312 <ToastProvider>
313 <CheckOutButton />
314 </ToastProvider>,
315 );
316
317 await userEvent.click(screen.getByRole("button", { name: "Check out" }));
318 await expect.poll(() => state.prepareThread.mock.calls.length).toBe(1);
319 const opened = DraftId.make("draft-opened");
320 useComposerDraftStore.getState().setPrompt(opened, "Review this pull request");
321 // A send from this draft waits for the checkout.
322 expect(readPendingWorkspaceDefault(opened)).not.toBeNull();
323 await act(async () => {
324 prepared.resolve({
325 _tag: "Success",
326 value: {
327 branch: "pr-1",
328 worktreePath: "/repo-worktrees/pr-1",
329 isOnPullRequestHead: true,
330 pullRequest: { url: "https://github.com/owner/repo/pull/1" },
331 },
332 });
333 await prepared.promise;
334 });
335 await expect.element(screen.getByRole("dialog", { name: "Checked out" })).toBeVisible();
336
337 expect(useComposerDraftStore.getState().getComposerDraft(opened)?.prompt).toBe(
338 "Review this pull request",
339 );
340 expect(useComposerDraftStore.getState().getDraftSession(opened)).toMatchObject({
341 branch: "pr-1",
342 worktreePath: "/repo-worktrees/pr-1",
343 });
344 expect(readPendingWorkspaceDefault(opened)).toBeNull();
345});
346
347it("keeps the destination branch and skips the task when checkout succeeds after a move", async () => {
348 setup();
349 const draftId = DraftId.make("draft-moved-during-checkout");
350 const threadId = ThreadId.make("thread-moved-during-checkout");
351 const store = useComposerDraftStore.getState();
352 const prepared = Promise.withResolvers<{
353 _tag: "Success";
354 value: {
355 branch: string;
356 worktreePath: string;
357 isOnPullRequestHead: boolean;
358 pullRequest: { url: string };
359 };
360 }>();
361 state.newThread.mockImplementation(async (projectRef) => {
362 store.setLogicalProjectDraftThreadId(scopedProjectKey(projectRef), projectRef, draftId, {
363 threadId,
364 });
365 return { draftId, threadId };
366 });
367 state.prepareThread.mockReturnValueOnce(prepared.promise);
368 await using screen = await render(
369 <ToastProvider>
370 <FixChecksButton />
371 </ToastProvider>,
372 );
373
374 await userEvent.click(screen.getByRole("button", { name: "Fix" }));
375 await expect.poll(() => state.prepareThread.mock.calls.length).toBe(1);
376 store.setPrompt(draftId, "My draft");
377 const waitingSend = readPendingWorkspaceDefault(draftId);
378
379 const destination = scopeProjectRef(EnvironmentId.make("environment"), ProjectId.make("other"));
380 store.setLogicalProjectDraftThreadId(scopedProjectKey(destination), destination, draftId, {
381 branch: "destination",
382 });
383 // A waiting send is released as soon as the draft moves, before the checkout finishes.
384 await expect(waitingSend).resolves.toBe("moved");
385
386 await act(async () => {
387 prepared.resolve({
388 _tag: "Success",
389 value: {
390 branch: "pr-1",
391 worktreePath: "/repo-worktrees/pr-1",
392 isOnPullRequestHead: true,
393 pullRequest: { url: "https://github.com/owner/repo/pull/1" },
394 },
395 });
396 await prepared.promise;
397 });
398 await expect
399 .element(screen.getByRole("dialog", { name: "Preparing the pull request checkout..." }))
400 .not.toBeInTheDocument();
401 expect(store.getComposerDraft(draftId)?.prompt).toBe("My draft");
402 expect(store.getDraftSession(draftId)).toMatchObject({
403 projectId: destination.projectId,
404 branch: "destination",
405 worktreePath: null,
406 });
407});
408
409function batchPullRequestEntry(number: number): EnvironmentPullRequestEntry {
410 return {
411 environmentId: EnvironmentId.make("environment"),
412 provider: SourceControlProviderKind.make("github"),
413 host: "github.com",
414 projectId: ProjectId.make("project"),
415 projectTitle: "repo",
416 repository: "owner/repo",
417 number,
418 title: `Pull request ${number}`,
419 url: `https://github.com/owner/repo/pull/${number}`,
420 author: { login: "octocat", name: null, avatarUrl: null },
421 headBranch: `pr-${number}`,
422 baseBranch: "main",
423 state: "open",
424 isDraft: false,
425 mergeability: "mergeable",
426 additions: 1,
427 deletions: 0,
428 createdAt: "2026-07-01T00:00:00Z",
429 updatedAt: "2026-07-02T00:00:00Z",
430 viewerReviewRequested: false,
431 labels: [],
432 };
433}
434
435function BatchCloseButton({ entries }: { entries: readonly EnvironmentPullRequestEntry[] }) {
436 const { close } = usePullRequestCloseBatch(() => {});
437 return (
438 <button type="button" onClick={() => void close(entries)}>
439 Close batch
440 </button>
441 );
442}
443
444it("uses singular wording when a single-entry batch close fails and plural for multi-entry batches", async () => {
445 setup();
446 state.runAction
447 .mockResolvedValueOnce({
448 _tag: "Failure",
449 cause: Cause.fail(new Error("Permission denied")),
450 })
451 .mockResolvedValueOnce({ _tag: "Success", value: undefined })
452 .mockResolvedValueOnce({
453 _tag: "Failure",
454 cause: Cause.fail(new Error("Permission denied")),
455 });
456
457 await using screen = await render(
458 <ToastProvider>
459 <BatchCloseButton entries={[batchPullRequestEntry(1)]} />
460 </ToastProvider>,
461 );
462
463 await userEvent.click(screen.getByRole("button", { name: "Close batch" }));
464 const firstToast = page.getByRole("dialog");
465 await expect
466 .element(page.getByRole("dialog", { name: "Closed 0 of 1 pull request", exact: true }))
467 .toBeVisible();
468 await userEvent.click(firstToast.getByRole("button", { name: "Dismiss notification" }));
469 await expect.element(firstToast).not.toBeInTheDocument();
470
471 await screen.rerender(
472 <ToastProvider>
473 <BatchCloseButton entries={[batchPullRequestEntry(2), batchPullRequestEntry(3)]} />
474 </ToastProvider>,
475 );
476
477 await userEvent.click(screen.getByRole("button", { name: "Close batch" }));
478 await expect
479 .element(page.getByRole("dialog", { name: "Closed 1 of 2 pull requests", exact: true }))
480 .toBeVisible();
481});