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 mode: "local" | "worktree",
402 checkout: Promise<PreparedCheckout>,
403 signal?: AbortSignal,
404): Promise<DraftCheckoutResult> {
405 const { promise: result, resolve, reject } = Promise.withResolvers<DraftCheckoutResult>();
406 const onAbort = () => resolve({ _tag: "Cancelled" });
407 // A local checkout keeps moving the project's own ref, so its draft waits for it even when dismissed.
408 if (mode === "worktree") signal?.addEventListener("abort", onAbort, { once: true });
409 checkout
410 .then(
411 (prepared) => {
412 signal?.removeEventListener("abort", onAbort);
413 if (!isCurrent() || signal?.aborted) return resolve({ _tag: "Cancelled" });
414 if (prepared._tag === "Failure") return resolve(prepared);
415 const { branch, worktreePath, pullRequest } = prepared.value;
416 // A waiting send resumes right after this and must render the checkout first.
417 flushSync(() =>
418 useComposerDraftStore.getState().setDraftThreadContext(draftId, {
419 branch,
420 worktreePath,
421 envMode: worktreePath === null ? "local" : "worktree",
422 workspaceExplicit: true,
423 // The draft carries the pull request until its first send makes it a thread, which links it.
424 checkoutPullRequest: { url: pullRequest.url, branch },
425 }),
426 );
427 resolve(prepared);
428 },
429 (error) => {
430 signal?.removeEventListener("abort", onAbort);
431 if (!isCurrent() || signal?.aborted) return resolve({ _tag: "Cancelled" });
432 reject(error);
433 },
434 )
435 .catch(reject);
436 const isCurrent = trackPendingDraftCheckout(
437 draftId,
438 projectRef,
439 result.then((prepared) => prepared._tag === "Success"),
440 );
441 return result;
442}
443
444export type PullRequestHandoffDetail = Pick<
445 PullRequestDetail,
446 "projectId" | "workspaceRoot" | "url"
447>;
448
449export function usePullRequestHandoffs({
450 environmentId,
451 detail,
452}: {
453 environmentId: EnvironmentId;
454 detail: PullRequestHandoffDetail | null;
455}) {
456 const newThread = useNewThreadHandler();
457 const prepareThread = usePreparePullRequestThreadAction({
458 environmentId,
459 cwd: detail?.workspaceRoot ?? null,
460 });
461 // Serialize all handoffs because they check out the same pull request.
462 const [handoff, setHandoff] = useState<string | null>(null);
463 // Prompt links hand over a URL alone, so the URL is what names the host.
464 const terminology = (
465 (detail && sourceControlClients.findByChangeRequestUrl(detail.url)) ||
466 sourceControlClients.get(undefined)
467 ).changeRequest;
468
469 // Questions must not change checkouts or create worktrees.
470 const openThreadWithTask = async (
471 projectRef: ReturnType<typeof scopeProjectRef>,
472 task: PullRequestThreadTask | null,
473 opened?: { draftId: DraftId },
474 ): Promise<{ draftId: DraftId } | null> => {
475 const session =
476 opened ??
477 (await newThread(projectRef).then(
478 (result) => result,
479 () => null,
480 ));
481 if (session === null) return null;
482 if (task === null) return session;
483 writeHandoffToComposer(session.draftId, task);
484 return session;
485 };
486
487 const startAsk = async (kind: string, task: PullRequestThreadTask) => {
488 if (!detail || handoff !== null) return;
489 setHandoff(kind);
490 const projectRef = scopeProjectRef(environmentId, detail.projectId);
491 const opened = await openThreadWithTask(projectRef, task);
492 setHandoff(null);
493 if (opened === null) {
494 toastManager.add({
495 type: "error",
496 title: m(msg("Could not open a thread")),
497 description: m(msg("Try again from the project, or open a thread first.")),
498 });
499 return;
500 }
501 toastManager.add({
502 type: "success",
503 title: m(msg("Asked in a thread")),
504 description:
505 task.prompt.length > 0
506 ? m(msg("The question is in the composer. Read it over, then send."))
507 : m(
508 msg`The ${select(
509 { term: changeRequestTermKind(terminology) },
510 {
511 mr: "merge request",
512 cr: "change request",
513 other: "pull request",
514 },
515 )} is in the composer. Type your question, then send.`,
516 ),
517 });
518 };
519
520 const startHandoff = async (
521 kind: string,
522 task: PullRequestThreadTask | null,
523 mode: "worktree" | "local" = "worktree",
524 ) => {
525 if (!detail || handoff !== null) return;
526 setHandoff(kind);
527 // Dismissing the loading toast cancels the handoff before it touches a draft.
528 const cancel = new AbortController();
529 // Explicit timeouts survive toast updates and would pin the result after loading.
530 const toastId = toastManager.add({
531 type: "loading",
532 title: m(
533 msg`Preparing the ${select(
534 { term: changeRequestTermKind(terminology) },
535 {
536 mr: "merge request",
537 cr: "change request",
538 other: "pull request",
539 },
540 )} checkout...`,
541 ),
542 onClose: () => {
543 cancel.abort();
544 },
545 });
546 const projectRef = scopeProjectRef(environmentId, detail.projectId);
547 // Checkout setup requires the thread to exist first.
548 const opened = await newThread(projectRef).then(
549 (session) => session,
550 () => null,
551 );
552 if (cancel.signal.aborted) {
553 setHandoff(null);
554 return;
555 }
556 if (opened === null) {
557 setHandoff(null);
558 toastManager.update(toastId, {
559 type: "error",
560 title: m(msg("Could not open a thread for the checkout")),
561 description: m(msg("Try again from the project, or open a thread first.")),
562 });
563 return;
564 }
565 const checkout = prepareThread.run({
566 reference: detail.url,
567 mode,
568 threadId: opened.threadId,
569 });
570 const prepared = await prepareDraftCheckout(
571 opened.draftId,
572 projectRef,
573 mode,
574 checkout,
575 cancel.signal,
576 );
577 if (cancel.signal.aborted || prepared._tag === "Cancelled") {
578 if (!cancel.signal.aborted) toastManager.close(toastId);
579 // Dismissal frees the draft, but the server checkout runs on and a retry would race it.
580 void checkout.then(
581 () => setHandoff(null),
582 () => setHandoff(null),
583 );
584 return;
585 }
586 setHandoff(null);
587 if (prepared._tag === "Failure") {
588 toastManager.update(toastId, {
589 type: "error",
590 title: m(
591 msg`Could not prepare the ${select(
592 { term: changeRequestTermKind(terminology) },
593 {
594 mr: "merge request",
595 cr: "change request",
596 other: "pull request",
597 },
598 )} checkout`,
599 ),
600 description: checkoutFailureDescription(
601 isAtomCommandInterrupted(prepared) ? undefined : squashAtomCommandFailure(prepared),
602 ),
603 });
604 return;
605 }
606 if (task === null) {
607 toastManager.update(
608 toastId,
609 prepared.value.isOnPullRequestHead
610 ? {
611 type: "success",
612 title: mode === "local" ? m(msg("Checked out here")) : m(msg("Checked out")),
613 description:
614 mode === "local"
615 ? m(
616 msg`This repository is on the ${select(
617 { term: changeRequestTermKind(terminology) },
618 {
619 mr: "merge request",
620 cr: "change request",
621 other: "pull request",
622 },
623 )}'s branch, with a thread open on it.`,
624 )
625 : m(
626 msg`The ${select(
627 { term: changeRequestTermKind(terminology) },
628 {
629 mr: "merge request",
630 cr: "change request",
631 other: "pull request",
632 },
633 )} is in its own worktree, with a thread open on it.`,
634 ),
635 }
636 : offHeadPullRequestCheckoutToast(terminology),
637 );
638 return;
639 }
640 await openThreadWithTask(projectRef, task, opened);
641 toastManager.update(
642 toastId,
643 prepared.value.isOnPullRequestHead
644 ? {
645 type: "success",
646 title: m(msg("Checkout ready")),
647 description: m(msg("The task is in the composer. Read it over, then send.")),
648 }
649 : offHeadPullRequestCheckoutToast(terminology),
650 );
651 };
652
653 return { handoff, startAsk, startHandoff };
654}