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

usePullRequestActions.ts

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