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

usePullRequestActions.ts

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