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