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

usePullRequestActions.ts

415 lines15.4 KB

1import { useAtomCommand } from "~/state/use-atom-command";
2import { scopeProjectRef } from "@t3tools/client-runtime/environment";
3import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
4import type {
5 EnvironmentId,
6 ProjectId,
7 PullRequestAction,
8 PullRequestDetail,
9 PullRequestMergeMethod,
10 PullRequestRef,
11} from "@t3tools/contracts";
12import { useCallback, useRef, useState } from "react";
13import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
14import { useClientSettings, useEnvironmentSettings } from "~/hooks/useSettings";
15import {
16 deriveLogicalProjectKeyFromSettings,
17 derivePhysicalProjectKey,
18 selectProjectGroupingSettings,
19} from "~/logicalProject";
20import { buildPhysicalToLogicalProjectKeyMap } from "~/sidebarProjectGrouping";
21import { useProjects } from "~/state/entities";
22import { usePrimaryEnvironmentId } from "~/state/environments";
23​
24import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
25import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
26import { usePreparePullRequestThreadAction } from "~/lib/sourceControlActions";
27import type { ReviewCommentContext } from "~/reviewCommentContext";
28import { pullRequestEnvironment } from "~/state/pullRequests";
29​
30import { toastManager } from "../ui/toast";
31import { handoffPrompt, handoffReviewComments, readableFailure } from "./pullRequestDetail.logic";
32import { pullRequestEntryKey, type EnvironmentPullRequestEntry } from "./pullRequestList.logic";
33​
34export function usePullRequestDefaultMergeMethodResolver(
35 environmentId: EnvironmentId,
36 projectId: ProjectId,
37) {
38 const projectDefault = useEnvironmentSettings(
39 environmentId,
40 (settings) => resolveProjectSettings(settings, projectId).settings.pullRequestMergeMethod,
41 );
42 const legacyOverrides = useClientSettings((settings) => settings.pullRequestMergeMethodOverrides);
43 const grouping = useClientSettings(selectProjectGroupingSettings);
44 const projects = useProjects();
45 const primaryEnvironmentId = usePrimaryEnvironmentId();
46 return useCallback(() => {
47 if (projectDefault != null) return projectDefault;
48 if (Object.keys(legacyOverrides).length === 0) return undefined;
49 const project = projects.find(
50 (candidate) => candidate.environmentId === environmentId && candidate.id === projectId,
51 );
52 if (!project) return undefined;
53 const key =
54 buildPhysicalToLogicalProjectKeyMap({
55 projects,
56 settings: grouping,
57 primaryEnvironmentId,
58 }).get(derivePhysicalProjectKey(project)) ??
59 deriveLogicalProjectKeyFromSettings(project, grouping);
60 return legacyOverrides[key];
61 }, [
62 projectDefault,
63 projects,
64 environmentId,
65 projectId,
66 grouping,
67 primaryEnvironmentId,
68 legacyOverrides,
69 ]);
71​
72const ACTION_SUCCESS_LABELS: Record<PullRequestAction, string> = {
73 merge: "Merge requested",
74 ready: "Marked ready for review",
75 draft: "Converted to draft",
76 close: "Pull request closed",
77 reopen: "Pull request reopened",
78 "update-branch": "Branch updated with the base branch",
79 "enable-auto-merge": "Auto-merge enabled",
80 "disable-auto-merge": "Auto-merge disabled",
81 revert: "Revert pull request opened",
82 "delete-branch": "Branch deleted",
83 "approve-workflows": "Workflows approved",
84};
85​
86const ACTION_FAILURE_LABELS: Record<PullRequestAction, string> = {
87 merge: "Could not merge this pull request",
88 ready: "Could not mark this ready for review",
89 draft: "Could not convert this to a draft",
90 close: "Could not close this pull request",
91 reopen: "Could not reopen this pull request",
92 "update-branch": "Could not update this branch",
93 "enable-auto-merge": "Could not enable auto-merge",
94 "disable-auto-merge": "Could not disable auto-merge",
95 revert: "Could not open a revert pull request",
96 "delete-branch": "Could not delete this branch",
97 "approve-workflows": "Could not approve workflows",
98};
99​
100const ACTION_FAILURE_HINTS: Record<PullRequestAction, string> = {
101 merge:
102 "The host refused the merge. Check that you have write access, that the checks it requires have passed, and that the branch is not conflicting.",
103 ready: "The host refused it. Check that you have write access to this repository.",
104 draft: "The host refused it. Check that you have write access to this repository.",
105 close: "The host refused it. Check that you have write access, or that you opened it.",
106 reopen:
107 "The host refused it. Check that you have write access, and that the branch still exists.",
108 "update-branch":
109 "The host refused it. Check that you have write access, and that the base branch has not diverged in a way the host cannot merge.",
110 "enable-auto-merge":
111 "The host refused it. Check that auto-merge is enabled for this repository and that you have write access.",
112 "disable-auto-merge": "The host refused it. Check that you have write access to this repository.",
113 revert:
114 "The host refused it. Check that you have write access and that this pull request was merged on the host.",
115 "delete-branch":
116 "The host refused it. Check that you have write access to the source repository and that the branch has not moved since this page loaded.",
117 "approve-workflows":
118 "The host refused it. Check that you have Actions write access and that these workflow runs are still awaiting approval.",
119};
120​
121export function usePullRequestActionRunner({
122 environmentId,
123 reference,
124 onSuccess,
125 resolveMergeMethod,
126}: {
127 environmentId: EnvironmentId;
128 reference: PullRequestRef | null;
129 onSuccess?: (action: PullRequestAction) => void;
130 /** Small surfaces resolve repository settings on the click, not for every visible row. */
131 resolveMergeMethod?: (detail: PullRequestDetail) => PullRequestMergeMethod;
132}) {
133 const runAction = useAtomCommand(pullRequestEnvironment.runAction, {
134 reportFailure: false,
135 });
136 const [actionPending, setActionPending] = useState(false);
137 const pendingRef = useRef(false);
138​
139 const perform = async (action: PullRequestAction, method?: PullRequestMergeMethod) => {
140 if (pendingRef.current || reference === null) return;
141 pendingRef.current = true;
142 setActionPending(true);
143 try {
144 const result = await runAction({
145 environmentId,
146 input: {
147 ...reference,
148 action,
149 ...(method ? { mergeMethod: method } : resolveMergeMethod ? { resolveMergeMethod } : {}),
150 },
151 });
152 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
153 toastManager.add({ type: "success", title: ACTION_SUCCESS_LABELS[action] });
154 onSuccess?.(action);
155 } catch (failure) {
156 toastManager.add({
157 type: "error",
158 title: ACTION_FAILURE_LABELS[action],
159 description: readableFailure(failure, ACTION_FAILURE_HINTS[action]),
160 });
161 } finally {
162 pendingRef.current = false;
163 setActionPending(false);
164 }
165 };
166​
167 return { actionPending, perform };
169​
170export function usePullRequestCloseBatch(onClosed: (entry: EnvironmentPullRequestEntry) => void) {
171 const runAction = useAtomCommand(pullRequestEnvironment.runAction, { reportFailure: false });
172 const pending = useRef(new Set<string>());
173 const [closingKeys, setClosingKeys] = useState<ReadonlySet<string>>(() => new Set());
174 const close = useCallback(
175 async (entries: readonly EnvironmentPullRequestEntry[]) => {
176 const batch = entries.filter((entry) => {
177 const key = pullRequestEntryKey(entry);
178 if (entry.state !== "open" || pending.current.has(key)) return false;
179 pending.current.add(key);
180 return true;
181 });
182 if (batch.length === 0) return;
183 setClosingKeys(new Set(pending.current));
184 let closed = 0;
185 const failures: string[] = [];
186 await Promise.all(
187 batch.map(async (entry) => {
188 try {
189 const result = await runAction({
190 environmentId: entry.environmentId,
191 input: {
192 projectId: entry.projectId,
193 host: entry.host,
194 repository: entry.repository,
195 number: entry.number,
196 action: "close",
197 },
198 });
199 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
200 closed++;
201 onClosed(entry);
202 } catch (failure) {
203 failures.push(
204 `#${entry.number}: ${readableFailure(failure, ACTION_FAILURE_HINTS.close)}`,
205 );
206 } finally {
207 pending.current.delete(pullRequestEntryKey(entry));
208 setClosingKeys(new Set(pending.current));
209 }
210 }),
211 );
212 toastManager.add({
213 type: failures.length > 0 ? "error" : "success",
214 title:
215 failures.length > 0
216 ? `Closed ${closed} of ${batch.length} pull requests`
217 : `Closed ${closed} pull request${closed === 1 ? "" : "s"}`,
218 ...(failures.length > 0 ? { description: failures.slice(0, 3).join("\n") } : {}),
219 });
220 },
221 [onClosed, runAction],
222 );
223 return { close, closingKeys };
225​
226export interface PullRequestThreadTask {
227 prompt: string;
228 reviewComments?: ReadonlyArray<ReviewCommentContext>;
230​
231export type PullRequestHandoffDetail = Pick<
232 PullRequestDetail,
233 "projectId" | "workspaceRoot" | "url"
234>;
235​
236const lastHandoffPromptByDraft = new Map<DraftId, string>();
237​
238export function usePullRequestHandoffs({
239 environmentId,
240 detail,
241}: {
242 environmentId: EnvironmentId;
243 detail: PullRequestHandoffDetail | null;
244}) {
245 const newThread = useNewThreadHandler();
246 const prepareThread = usePreparePullRequestThreadAction({
247 environmentId,
248 cwd: detail?.workspaceRoot ?? null,
249 });
250 // One at a time whatever the key: they all check the same pull request out.
251 const [handoff, setHandoff] = useState<string | null>(null);
252​
253 /**
254 * Nothing is checked out: asking a question is not a reason to move somebody's working tree
255 * or to make a worktree they did not ask for.
256 */
257 const openThreadWithTask = async (
258 projectRef: ReturnType<typeof scopeProjectRef>,
259 task: PullRequestThreadTask | null,
260 opened?: { draftId: DraftId },
261 ): Promise<{ draftId: DraftId } | null> => {
262 const session =
263 opened ??
264 (await newThread(projectRef).then(
265 (result) => result,
266 () => null,
267 ));
268 if (session === null) return null;
269 const store = useComposerDraftStore.getState();
270 if (task === null) return session;
271 const draft = store.getComposerDraft(session.draftId);
272 const existingComments = draft?.reviewComments ?? [];
273 const prompt = handoffPrompt(
274 {
275 prompt: draft?.prompt ?? "",
276 lastHandoffPrompt: lastHandoffPromptByDraft.get(session.draftId),
277 },
278 task.prompt,
279 );
280 // Remember the hand-off's own contribution, not the merged prompt: only that sentence is
281 // this session's to take back next time, and the reader's text around it is not.
282 lastHandoffPromptByDraft.set(session.draftId, task.prompt);
283 store.setPrompt(session.draftId, prompt);
284 store.setReviewComments(
285 session.draftId,
286 handoffReviewComments(existingComments, task.reviewComments ?? []),
287 );
288 return session;
289 };
290​
291 const startAsk = async (kind: string, task: PullRequestThreadTask) => {
292 if (!detail || handoff !== null) return;
293 setHandoff(kind);
294 const projectRef = scopeProjectRef(environmentId, detail.projectId);
295 const opened = await openThreadWithTask(projectRef, task);
296 setHandoff(null);
297 if (opened === null) {
298 toastManager.add({
299 type: "error",
300 title: "Could not open a thread",
301 description: "Try again from the project, or open a thread first.",
302 });
303 return;
304 }
305 toastManager.add({
306 type: "success",
307 title: "Asked in a thread",
308 description:
309 task.prompt.length > 0
310 ? "The question is in the composer — read it over, then send."
311 : "The pull request is in the composer — type your question, then send.",
312 });
313 };
314​
315 const startHandoff = async (
316 kind: string,
317 task: PullRequestThreadTask | null,
318 mode: "worktree" | "local" = "worktree",
319 ) => {
320 if (!detail || handoff !== null) return;
321 setHandoff(kind);
322 // It carries no timeout of its own: a loading toast never expires, and an explicit one
323 // would survive the update and pin the result on screen.
324 const toastId = toastManager.add({
325 type: "loading",
326 title: "Preparing the pull request checkout...",
327 });
328 const projectRef = scopeProjectRef(environmentId, detail.projectId);
329 // The thread is opened before the checkout rather than after it, because the project's setup
330 // script only runs for a checkout that knows which thread it is for — and a worktree with no
331 // dependencies installed is not something anyone can test.
332 const opened = await newThread(projectRef).then(
333 (session) => session,
334 () => null,
335 );
336 if (opened === null) {
337 setHandoff(null);
338 toastManager.update(toastId, {
339 type: "error",
340 title: "Could not open a thread for the checkout",
341 description: "Try again from the project, or open a thread first.",
342 });
343 return;
344 }
345 const prepared = await prepareThread.run({
346 reference: detail.url,
347 mode,
348 threadId: opened.threadId,
349 });
350 if (prepared._tag === "Failure") {
351 setHandoff(null);
352 const detailMessage =
353 prepareThread.error instanceof Error ? prepareThread.error.message : null;
354 toastManager.update(toastId, {
355 type: "error",
356 title: "Could not prepare the pull request checkout",
357 ...(detailMessage ? { description: detailMessage } : {}),
358 });
359 return;
360 }
361 const pointed = await newThread(projectRef, {
362 branch: prepared.value.branch,
363 worktreePath: prepared.value.worktreePath,
364 envMode: prepared.value.worktreePath === null ? "local" : "worktree",
365 }).then(
366 (session) => session !== null,
367 () => false,
368 );
369 if (!pointed) {
370 setHandoff(null);
371 toastManager.update(toastId, {
372 type: "error",
373 title: "Checked out, but the thread stayed where it was",
374 description: `The checkout is ready on \`${prepared.value.branch}\`. Point a thread at it from the branch picker, then ask again.`,
375 });
376 return;
377 }
378 setHandoff(null);
379 const staleCheckoutToast = {
380 type: "warning",
381 title: "Checked out, but not on the latest commits",
382 description:
383 "The checkout could not be moved onto the pull request's latest commits, so the code there is older than the pull request. Uncommitted work or local commits keep it where it is.",
384 } as const;
385 if (task === null) {
386 toastManager.update(
387 toastId,
388 prepared.value.isOnPullRequestHead
389 ? {
390 type: "success",
391 title: mode === "local" ? "Checked out here" : "Checked out",
392 description:
393 mode === "local"
394 ? "This repository is on the pull request's branch, with a thread open on it."
395 : "The pull request is in its own worktree, with a thread open on it.",
396 }
397 : staleCheckoutToast,
398 );
399 return;
400 }
401 await openThreadWithTask(projectRef, task, opened);
402 toastManager.update(
403 toastId,
404 prepared.value.isOnPullRequestHead
405 ? {
406 type: "success",
407 title: "Checkout ready",
408 description: "The task is in the composer — read it over, then send.",
409 }
410 : staleCheckoutToast,
411 );
412 };
413​
414 return { handoff, startAsk, startHandoff };