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