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

usePullRequestActions.ts

411 lines15.0 KB

1import { useAtomCommand } from "~/state/use-atom-command";
2import { scopeProjectRef } from "@t3tools/client-runtime/environment";
3import {
4 isAtomCommandInterrupted,
5 squashAtomCommandFailure,
6} from "@t3tools/client-runtime/state/runtime";
7import type {
8 EnvironmentId,
9 ProjectId,
10 PullRequestAction,
11 PullRequestDetail,
12 PullRequestMergeMethod,
13 PullRequestRef,
14} from "@t3tools/contracts";
15import { useRef, useState } from "react";
16import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
17import { useClientSettings, useEnvironmentSettings } from "~/hooks/useSettings";
18import {
19 deriveLogicalProjectKeyFromSettings,
20 derivePhysicalProjectKey,
21 selectProjectGroupingSettings,
22} from "~/logicalProject";
23import { buildPhysicalToLogicalProjectKeyMap } from "~/sidebarProjectGrouping";
24import { useProjects } from "~/state/entities";
25import { usePrimaryEnvironmentId } from "~/state/environments";
26​
27import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
28import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
29import { usePreparePullRequestThreadAction } from "~/lib/sourceControlActions";
30import type { ReviewCommentContext } from "~/reviewCommentContext";
31import { pullRequestEnvironment } from "~/state/pullRequests";
32​
33import { toastManager } from "../ui/toast";
34import {
35 checkoutFailureDescription,
36 handoffPrompt,
37 handoffReviewComments,
38 readableFailure,
39} from "./pullRequestDetail.logic";
40import { pullRequestEntryKey, type EnvironmentPullRequestEntry } from "./pullRequestList.logic";
41​
42export function usePullRequestDefaultMergeMethodResolver(
43 environmentId: EnvironmentId,
44 projectId: ProjectId,
45) {
46 const projectDefault = useEnvironmentSettings(
47 environmentId,
48 (settings) => resolveProjectSettings(settings, projectId).settings.pullRequestMergeMethod,
49 );
50 const legacyOverrides = useClientSettings((settings) => settings.pullRequestMergeMethodOverrides);
51 const grouping = useClientSettings(selectProjectGroupingSettings);
52 const projects = useProjects();
53 const primaryEnvironmentId = usePrimaryEnvironmentId();
54 return () => {
55 if (projectDefault != null) return projectDefault;
56 if (Object.keys(legacyOverrides).length === 0) return undefined;
57 const project = projects.find(
58 (candidate) => candidate.environmentId === environmentId && candidate.id === projectId,
59 );
60 if (!project) return undefined;
61 const key =
62 buildPhysicalToLogicalProjectKeyMap({
63 projects,
64 settings: grouping,
65 primaryEnvironmentId,
66 }).get(derivePhysicalProjectKey(project)) ??
67 deriveLogicalProjectKeyFromSettings(project, grouping);
68 return legacyOverrides[key];
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 const result = await runAction({
144 environmentId,
145 input: {
146 ...reference,
147 action,
148 ...(method ? { mergeMethod: method } : resolveMergeMethod ? { resolveMergeMethod } : {}),
149 },
150 });
151 pendingRef.current = false;
152 setActionPending(false);
153 if (result._tag === "Failure") {
154 toastManager.add({
155 type: "error",
156 title: ACTION_FAILURE_LABELS[action],
157 description: readableFailure(
158 squashAtomCommandFailure(result),
159 ACTION_FAILURE_HINTS[action],
160 ),
161 });
162 return;
163 }
164 toastManager.add({ type: "success", title: ACTION_SUCCESS_LABELS[action] });
165 onSuccess?.(action);
166 };
167​
168 return { actionPending, perform };
170​
171export function usePullRequestCloseBatch(onClosed: (entry: EnvironmentPullRequestEntry) => void) {
172 const runAction = useAtomCommand(pullRequestEnvironment.runAction, { reportFailure: false });
173 const pending = useRef(new Set<string>());
174 const [closingKeys, setClosingKeys] = useState<ReadonlySet<string>>(() => new Set());
175 const close = 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 const failures: string[] = [];
185 const outcomes = await Promise.all(
186 batch.map(async (entry) => {
187 const result = await runAction({
188 environmentId: entry.environmentId,
189 input: {
190 projectId: entry.projectId,
191 host: entry.host,
192 repository: entry.repository,
193 number: entry.number,
194 action: "close",
195 },
196 });
197 pending.current.delete(pullRequestEntryKey(entry));
198 setClosingKeys(new Set(pending.current));
199 if (result._tag === "Failure") {
200 failures.push(
201 `#${entry.number}: ${readableFailure(squashAtomCommandFailure(result), ACTION_FAILURE_HINTS.close)}`,
202 );
203 return;
204 }
205 onClosed(entry);
206 return true;
207 }),
208 );
209 const closed = outcomes.filter(Boolean).length;
210 toastManager.add({
211 type: failures.length > 0 ? "error" : "success",
212 title:
213 failures.length > 0
214 ? `Closed ${closed} of ${batch.length} pull requests`
215 : `Closed ${closed} pull request${closed === 1 ? "" : "s"}`,
216 ...(failures.length > 0 ? { description: failures.slice(0, 3).join("\n") } : {}),
217 });
218 };
219 return { close, closingKeys };
221​
222export interface PullRequestThreadTask {
223 prompt: string;
224 reviewComments?: ReadonlyArray<ReviewCommentContext>;
226​
227export type PullRequestHandoffDetail = Pick<
228 PullRequestDetail,
229 "projectId" | "workspaceRoot" | "url"
230>;
231​
232const lastHandoffPromptByDraft = new Map<DraftId, string>();
233​
234export function usePullRequestHandoffs({
235 environmentId,
236 detail,
237}: {
238 environmentId: EnvironmentId;
239 detail: PullRequestHandoffDetail | null;
240}) {
241 const newThread = useNewThreadHandler();
242 const prepareThread = usePreparePullRequestThreadAction({
243 environmentId,
244 cwd: detail?.workspaceRoot ?? null,
245 });
246 // One at a time whatever the key: they all check the same pull request out.
247 const [handoff, setHandoff] = useState<string | null>(null);
248​
249 /**
250 * Nothing is checked out: asking a question is not a reason to move somebody's working tree
251 * or to make a worktree they did not ask for.
252 */
253 const openThreadWithTask = async (
254 projectRef: ReturnType<typeof scopeProjectRef>,
255 task: PullRequestThreadTask | null,
256 opened?: { draftId: DraftId },
257 ): Promise<{ draftId: DraftId } | null> => {
258 const session =
259 opened ??
260 (await newThread(projectRef).then(
261 (result) => result,
262 () => null,
263 ));
264 if (session === null) return null;
265 const store = useComposerDraftStore.getState();
266 if (task === null) return session;
267 const draft = store.getComposerDraft(session.draftId);
268 const existingComments = draft?.reviewComments ?? [];
269 const prompt = handoffPrompt(
270 {
271 prompt: draft?.prompt ?? "",
272 lastHandoffPrompt: lastHandoffPromptByDraft.get(session.draftId),
273 },
274 task.prompt,
275 );
276 // Remember the hand-off's own contribution, not the merged prompt: only that sentence is
277 // this session's to take back next time, and the reader's text around it is not.
278 lastHandoffPromptByDraft.set(session.draftId, task.prompt);
279 store.setPrompt(session.draftId, prompt);
280 store.setReviewComments(
281 session.draftId,
282 handoffReviewComments(existingComments, task.reviewComments ?? []),
283 );
284 return session;
285 };
286​
287 const startAsk = async (kind: string, task: PullRequestThreadTask) => {
288 if (!detail || handoff !== null) return;
289 setHandoff(kind);
290 const projectRef = scopeProjectRef(environmentId, detail.projectId);
291 const opened = await openThreadWithTask(projectRef, task);
292 setHandoff(null);
293 if (opened === null) {
294 toastManager.add({
295 type: "error",
296 title: "Could not open a thread",
297 description: "Try again from the project, or open a thread first.",
298 });
299 return;
300 }
301 toastManager.add({
302 type: "success",
303 title: "Asked in a thread",
304 description:
305 task.prompt.length > 0
306 ? "The question is in the composer — read it over, then send."
307 : "The pull request is in the composer — type your question, then send.",
308 });
309 };
310​
311 const startHandoff = async (
312 kind: string,
313 task: PullRequestThreadTask | null,
314 mode: "worktree" | "local" = "worktree",
315 ) => {
316 if (!detail || handoff !== null) return;
317 setHandoff(kind);
318 // It carries no timeout of its own: a loading toast never expires, and an explicit one
319 // would survive the update and pin the result on screen.
320 const toastId = toastManager.add({
321 type: "loading",
322 title: "Preparing the pull request checkout...",
323 });
324 const projectRef = scopeProjectRef(environmentId, detail.projectId);
325 // The thread is opened before the checkout rather than after it, because the project's setup
326 // script only runs for a checkout that knows which thread it is for — and a worktree with no
327 // dependencies installed is not something anyone can test.
328 const opened = await newThread(projectRef).then(
329 (session) => session,
330 () => null,
331 );
332 if (opened === null) {
333 setHandoff(null);
334 toastManager.update(toastId, {
335 type: "error",
336 title: "Could not open a thread for the checkout",
337 description: "Try again from the project, or open a thread first.",
338 });
339 return;
340 }
341 const prepared = await prepareThread.run({
342 reference: detail.url,
343 mode,
344 threadId: opened.threadId,
345 });
346 if (prepared._tag === "Failure") {
347 setHandoff(null);
348 toastManager.update(toastId, {
349 type: "error",
350 title: "Could not prepare the pull request checkout",
351 description: checkoutFailureDescription(
352 isAtomCommandInterrupted(prepared) ? undefined : squashAtomCommandFailure(prepared),
353 ),
354 });
355 return;
356 }
357 const pointed = await newThread(projectRef, {
358 branch: prepared.value.branch,
359 worktreePath: prepared.value.worktreePath,
360 envMode: prepared.value.worktreePath === null ? "local" : "worktree",
361 }).then(
362 (session) => session !== null,
363 () => false,
364 );
365 if (!pointed) {
366 setHandoff(null);
367 toastManager.update(toastId, {
368 type: "error",
369 title: "Checked out, but the thread stayed where it was",
370 description: `The checkout is ready on \`${prepared.value.branch}\`. Point a thread at it from the branch picker, then ask again.`,
371 });
372 return;
373 }
374 setHandoff(null);
375 const staleCheckoutToast = {
376 type: "warning",
377 title: "Checked out, but not on the latest commits",
378 description:
379 "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.",
380 } as const;
381 if (task === null) {
382 toastManager.update(
383 toastId,
384 prepared.value.isOnPullRequestHead
385 ? {
386 type: "success",
387 title: mode === "local" ? "Checked out here" : "Checked out",
388 description:
389 mode === "local"
390 ? "This repository is on the pull request's branch, with a thread open on it."
391 : "The pull request is in its own worktree, with a thread open on it.",
392 }
393 : staleCheckoutToast,
394 );
395 return;
396 }
397 await openThreadWithTask(projectRef, task, opened);
398 toastManager.update(
399 toastId,
400 prepared.value.isOnPullRequestHead
401 ? {
402 type: "success",
403 title: "Checkout ready",
404 description: "The task is in the composer — read it over, then send.",
405 }
406 : staleCheckoutToast,
407 );
408 };
409​
410 return { handoff, startAsk, startHandoff };