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