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