Open History to see the last commit
1import { scopedProjectKey } from "@t3tools/client-runtime/environment";
2import { EnvironmentId, ProjectId, ThreadId, type PullRequestRef } from "@t3tools/contracts";
3import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
4import { expect, it, vi } from "vite-plus/test";
5import { userEvent } from "vite-plus/test/browser";
6
7import { act, render } from "../../../test/render";
8import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
9import { readPendingWorkspaceDefault } from "~/lib/draftWorkspaceDefaults";
10import { ToastProvider } from "../ui/toast";
11import { usePullRequestActionRunner, usePullRequestHandoffs } from "./usePullRequestActions";
12
13const state = vi.hoisted(() => ({
14 runAction: vi.fn(),
15 newThread: vi.fn(),
16 prepareThread: vi.fn(),
17}));
18vi.mock(import("~/state/use-atom-command"), () => ({
19 useAtomCommand: (() => state.runAction) as never,
20}));
21vi.mock(import("~/hooks/useHandleNewThread"), () => ({
22 useNewThreadHandler: (() => state.newThread) as never,
23}));
24vi.mock(import("~/state/sourceControlActions"), () => ({
25 usePreparePullRequestThreadAction: (() => ({ run: state.prepareThread })) as never,
26}));
27
28function deferred<T>() {
29 let resolve!: (value: T) => void;
30 const promise = new Promise<T>((done) => {
31 resolve = done;
32 });
33 return { promise, resolve };
34}
35
36function MergeButton({ reference }: { reference: PullRequestRef }) {
37 const { actionPending, pendingAction, perform } = usePullRequestActionRunner({
38 environmentId: EnvironmentId.make("environment"),
39 reference,
40 headSha: `head-${reference.number}`,
41 terminology: sourceControlClients.get(undefined).changeRequest,
42 });
43 return (
44 <button type="button" disabled={actionPending} onClick={() => void perform("merge")}>
45 {pendingAction === "merge" ? "Merging..." : "Merge"}
46 </button>
47 );
48}
49
50function setup() {
51 state.runAction.mockReset();
52 state.newThread.mockReset();
53 state.prepareThread.mockReset();
54}
55
56it("keeps pending merges with their pull request when navigating between threads", async () => {
57 setup();
58 const first: PullRequestRef = {
59 projectId: ProjectId.make("project"),
60 repository: "owner/repo",
61 number: 1,
62 };
63 const second = { ...first, number: 2 };
64 const firstResult = deferred<{ _tag: "Success"; value: void }>();
65 const secondResult = deferred<{ _tag: "Success"; value: void }>();
66 state.runAction
67 .mockReturnValueOnce(firstResult.promise)
68 .mockReturnValueOnce(secondResult.promise);
69 await using screen = await render(<MergeButton reference={first} />);
70 const button = screen.getByRole("button");
71
72 await userEvent.click(button);
73 await expect.element(button).toHaveTextContent("Merging...");
74 await screen.rerender(
75 <MergeButton reference={{ ...first, projectId: ProjectId.make("other-project") }} />,
76 );
77 await expect.element(button).toHaveTextContent("Merge");
78 await expect.element(button).toBeEnabled();
79 await screen.rerender(<MergeButton reference={first} />);
80 await expect.element(button).toHaveTextContent("Merging...");
81 await expect.element(button).toBeDisabled();
82 await screen.rerender(<MergeButton reference={second} />);
83 await expect.element(button).toHaveTextContent("Merge");
84 await expect.element(button).toBeEnabled();
85 await userEvent.click(button);
86 expect(state.runAction).toHaveBeenCalledTimes(2);
87 // Each merge is pinned to the head its own row showed.
88 expect(state.runAction.mock.calls.map(([call]) => call.input.expectedHeadSha)).toEqual([
89 "head-1",
90 "head-2",
91 ]);
92
93 await screen.rerender(<MergeButton reference={first} />);
94 await expect.element(button).toHaveTextContent("Merging...");
95 await expect.element(button).toBeDisabled();
96 await act(async () => {
97 firstResult.resolve({ _tag: "Success", value: undefined });
98 await firstResult.promise;
99 });
100 await expect.element(button).toHaveTextContent("Merge");
101 await screen.rerender(<MergeButton reference={second} />);
102 await expect.element(button).toHaveTextContent("Merging...");
103 await act(async () => {
104 secondResult.resolve({ _tag: "Success", value: undefined });
105 await secondResult.promise;
106 });
107 await expect.element(button).toHaveTextContent("Merge");
108});
109
110function FixChecksButton() {
111 const { startHandoff } = usePullRequestHandoffs({
112 environmentId: EnvironmentId.make("environment"),
113 detail: {
114 projectId: ProjectId.make("project"),
115 workspaceRoot: "/repo",
116 url: "https://github.com/owner/repo/pull/1",
117 },
118 });
119 return (
120 <button type="button" onClick={() => void startHandoff("fix", { prompt: "Fix the checks" })}>
121 Fix
122 </button>
123 );
124}
125
126it("stops a pull request handoff when its loading toast is dismissed", async () => {
127 setup();
128 const prepared = deferred<{
129 _tag: "Success";
130 value: {
131 branch: string;
132 worktreePath: string;
133 isOnPullRequestHead: boolean;
134 pullRequest: { url: string };
135 };
136 }>();
137 state.newThread
138 .mockResolvedValueOnce({ draftId: "draft-1", threadId: ThreadId.make("thread-1") })
139 .mockResolvedValueOnce({ draftId: "draft-2", threadId: ThreadId.make("thread-1") });
140 state.prepareThread.mockReturnValueOnce(prepared.promise);
141 await using screen = await render(
142 <ToastProvider>
143 <FixChecksButton />
144 </ToastProvider>,
145 );
146
147 await userEvent.click(screen.getByRole("button", { name: "Fix" }));
148 const toast = screen.getByRole("dialog", { name: "Preparing the pull request checkout..." });
149 await expect.element(toast).toBeVisible();
150 await userEvent.click(toast.getByRole("button", { name: "Dismiss notification" }));
151 await expect.element(toast).not.toBeInTheDocument();
152 await act(async () => {
153 prepared.resolve({
154 _tag: "Success",
155 value: {
156 branch: "pr-1",
157 worktreePath: "/repo-worktrees/pr-1",
158 isOnPullRequestHead: true,
159 pullRequest: { url: "https://github.com/owner/repo/pull/1" },
160 },
161 });
162 await prepared.promise;
163 });
164
165 expect(state.newThread).toHaveBeenCalledTimes(1);
166 expect(useComposerDraftStore.getState().getComposerDraft("draft-2" as never)?.prompt ?? "").toBe(
167 "",
168 );
169});
170
171function CheckOutButton() {
172 const { startHandoff } = usePullRequestHandoffs({
173 environmentId: EnvironmentId.make("environment"),
174 detail: {
175 projectId: ProjectId.make("project"),
176 workspaceRoot: "/repo",
177 url: "https://github.com/owner/repo/pull/1",
178 },
179 });
180 return (
181 <button type="button" onClick={() => void startHandoff("checkout", null)}>
182 Check out
183 </button>
184 );
185}
186
187it("moves the draft the user typed into during a checkout onto the checkout", async () => {
188 setup();
189 const prepared = deferred<{
190 _tag: "Success";
191 value: {
192 branch: string;
193 worktreePath: string;
194 isOnPullRequestHead: boolean;
195 pullRequest: { url: string };
196 };
197 }>();
198 // Like the real handler: a draft with user content is not reused, so a later call opens another.
199 state.newThread.mockImplementation(
200 async (projectRef, options?: { branch?: string; worktreePath?: string }) => {
201 const store = useComposerDraftStore.getState();
202 const draftId = DraftId.make(options === undefined ? "draft-opened" : "draft-pointed");
203 store.setLogicalProjectDraftThreadId(scopedProjectKey(projectRef), projectRef, draftId, {
204 threadId: ThreadId.make(`thread-${draftId}`),
205 branch: options?.branch ?? null,
206 worktreePath: options?.worktreePath ?? null,
207 });
208 return { draftId, threadId: ThreadId.make(`thread-${draftId}`) };
209 },
210 );
211 state.prepareThread.mockReturnValueOnce(prepared.promise);
212 await using screen = await render(
213 <ToastProvider>
214 <CheckOutButton />
215 </ToastProvider>,
216 );
217
218 await userEvent.click(screen.getByRole("button", { name: "Check out" }));
219 await expect.poll(() => state.prepareThread.mock.calls.length).toBe(1);
220 const opened = DraftId.make("draft-opened");
221 useComposerDraftStore.getState().setPrompt(opened, "Review this pull request");
222 // A send from this draft waits for the checkout.
223 expect(readPendingWorkspaceDefault(opened)).not.toBeNull();
224 await act(async () => {
225 prepared.resolve({
226 _tag: "Success",
227 value: {
228 branch: "pr-1",
229 worktreePath: "/repo-worktrees/pr-1",
230 isOnPullRequestHead: true,
231 pullRequest: { url: "https://github.com/owner/repo/pull/1" },
232 },
233 });
234 await prepared.promise;
235 });
236 await expect.element(screen.getByRole("dialog", { name: "Checked out" })).toBeVisible();
237
238 expect(useComposerDraftStore.getState().getComposerDraft(opened)?.prompt).toBe(
239 "Review this pull request",
240 );
241 expect(useComposerDraftStore.getState().getDraftSession(opened)).toMatchObject({
242 branch: "pr-1",
243 worktreePath: "/repo-worktrees/pr-1",
244 });
245 expect(readPendingWorkspaceDefault(opened)).toBeNull();
246});