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

usePullRequestActions.ts

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