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} from "@t3tools/contracts";
15import { useRef, useState } from "react";
16import {
17 capitalizeTerm,
18 sourceControlClients,
19 type ChangeRequestTerminology,
20} from "@t3tools/client-runtime/source-control-clients";
21import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
22import { useClientSettings, useEnvironmentSettings } from "~/hooks/useSettings";
23import {
24 deriveLogicalProjectKeyFromSettings,
25 derivePhysicalProjectKey,
26 selectProjectGroupingSettings,
27} from "~/logicalProject";
28import { buildPhysicalToLogicalProjectKeyMap } from "~/sidebarProjectGrouping";
29import { useProjects } from "~/state/entities";
30import { usePrimaryEnvironmentId } from "~/state/environments";
31
32import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
33import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
34import { usePreparePullRequestThreadAction } from "~/lib/sourceControlActions";
35import type { ReviewCommentContext } from "~/reviewCommentContext";
36import { pullRequestEnvironment } from "~/state/pullRequests";
37
38import { toastManager } from "../ui/toast";
39import { offHeadPullRequestCheckoutToast } from "./pullRequestCheckoutToast";
40import {
41 checkoutFailureDescription,
42 handoffPrompt,
43 handoffReviewComments,
44 readableFailure,
45} from "./pullRequestDetail.logic";
46import { pullRequestEntryKey, type EnvironmentPullRequestEntry } from "./pullRequestList.logic";
47
48export function usePullRequestDefaultMergeMethodResolver(
49 environmentId: EnvironmentId,
50 projectId: ProjectId | null,
51) {
52 const projectDefault = useEnvironmentSettings(
53 environmentId,
54 (settings) => resolveProjectSettings(settings, projectId).settings.pullRequestMergeMethod,
55 );
56 const legacyOverrides = useClientSettings((settings) => settings.pullRequestMergeMethodOverrides);
57 const grouping = useClientSettings(selectProjectGroupingSettings);
58 const projects = useProjects();
59 const primaryEnvironmentId = usePrimaryEnvironmentId();
60 return () => {
61 if (projectDefault != null) return projectDefault;
62 if (Object.keys(legacyOverrides).length === 0) return undefined;
63 const project = projects.find(
64 (candidate) => candidate.environmentId === environmentId && candidate.id === projectId,
65 );
66 if (!project) return undefined;
67 const key =
68 buildPhysicalToLogicalProjectKeyMap({
69 projects,
70 settings: grouping,
71 primaryEnvironmentId,
72 }).get(derivePhysicalProjectKey(project)) ??
73 deriveLogicalProjectKeyFromSettings(project, grouping);
74 return legacyOverrides[key];
75 };
76}
77
78const actionSuccessLabels = (term: string): Record<PullRequestAction, string> => ({
79 merge: "Merge requested",
80 ready: "Marked ready for review",
81 draft: "Converted to draft",
82 close: `${capitalizeTerm(term)} closed`,
83 reopen: `${capitalizeTerm(term)} reopened`,
84 "update-branch": "Branch updated with the base branch",
85 "enable-auto-merge": "Auto-merge enabled",
86 "disable-auto-merge": "Auto-merge disabled",
87 revert: `Revert ${term} opened`,
88 "delete-branch": "Branch deleted",
89 "approve-workflows": "Workflows approved",
90});
91
92const actionFailureLabels = (term: string): Record<PullRequestAction, string> => ({
93 merge: `Could not merge this ${term}`,
94 ready: "Could not mark this ready for review",
95 draft: "Could not convert this to a draft",
96 close: `Could not close this ${term}`,
97 reopen: `Could not reopen this ${term}`,
98 "update-branch": "Could not update this branch",
99 "enable-auto-merge": "Could not enable auto-merge",
100 "disable-auto-merge": "Could not disable auto-merge",
101 revert: `Could not open a revert ${term}`,
102 "delete-branch": "Could not delete this branch",
103 "approve-workflows": "Could not approve workflows",
104});
105
106const actionFailureHints = (term: string): Record<PullRequestAction, string> => ({
107 merge:
108 "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.",
109 ready: "The host refused it. Check that you have write access to this repository.",
110 draft: "The host refused it. Check that you have write access to this repository.",
111 close: "The host refused it. Check that you have write access, or that you opened it.",
112 reopen:
113 "The host refused it. Check that you have write access, and that the branch still exists.",
114 "update-branch":
115 "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.",
116 "enable-auto-merge":
117 "The host refused it. Check that auto-merge is enabled for this repository and that you have write access.",
118 "disable-auto-merge": "The host refused it. Check that you have write access to this repository.",
119 revert: `The host refused it. Check that you have write access and that this ${term} was merged on the host.`,
120 "delete-branch":
121 "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.",
122 "approve-workflows":
123 "The host refused it. Check that you have Actions write access and that these workflow runs are still awaiting approval.",
124});
125
126export function usePullRequestActionRunner({
127 environmentId,
128 reference,
129 terminology,
130 onSuccess,
131 resolveMergeMethod,
132}: {
133 environmentId: EnvironmentId;
134 reference: PullRequestRef | null;
135 terminology: ChangeRequestTerminology;
136 onSuccess?: (action: PullRequestAction) => void;
137 /** Resolve repository settings on click to avoid per-row reads. */
138 resolveMergeMethod?: (detail: PullRequestDetail) => PullRequestMergeMethod;
139}) {
140 const runAction = useAtomCommand(pullRequestEnvironment.runAction, {
141 reportFailure: false,
142 });
143 const [actionPending, setActionPending] = useState(false);
144 const pendingRef = useRef(false);
145
146 const perform = async (action: PullRequestAction, method?: PullRequestMergeMethod) => {
147 if (pendingRef.current || reference === null) return;
148 pendingRef.current = true;
149 setActionPending(true);
150 const result = await runAction({
151 environmentId,
152 input: {
153 ...reference,
154 action,
155 ...(method ? { mergeMethod: method } : resolveMergeMethod ? { resolveMergeMethod } : {}),
156 },
157 });
158 pendingRef.current = false;
159 setActionPending(false);
160 if (result._tag === "Failure") {
161 toastManager.add({
162 type: "error",
163 title: actionFailureLabels(terminology.singular)[action],
164 description: readableFailure(
165 squashAtomCommandFailure(result),
166 actionFailureHints(terminology.singular)[action],
167 ),
168 });
169 return;
170 }
171 toastManager.add({ type: "success", title: actionSuccessLabels(terminology.singular)[action] });
172 onSuccess?.(action);
173 };
174
175 return { actionPending, perform };
176}
177
178export function usePullRequestCloseBatch(onClosed: (entry: EnvironmentPullRequestEntry) => void) {
179 const runAction = useAtomCommand(pullRequestEnvironment.runAction, { reportFailure: false });
180 const pending = useRef(new Set<string>());
181 const [closingKeys, setClosingKeys] = useState<ReadonlySet<string>>(() => new Set());
182 const close = async (entries: readonly EnvironmentPullRequestEntry[]) => {
183 const batch = entries.filter((entry) => {
184 const key = pullRequestEntryKey(entry);
185 if (entry.state !== "open" || pending.current.has(key)) return false;
186 pending.current.add(key);
187 return true;
188 });
189 if (batch.length === 0) return;
190 setClosingKeys(new Set(pending.current));
191 const failures: string[] = [];
192 const outcomes = await Promise.all(
193 batch.map(async (entry) => {
194 const result = await runAction({
195 environmentId: entry.environmentId,
196 input: {
197 projectId: entry.projectId,
198 host: entry.host,
199 repository: entry.repository,
200 number: entry.number,
201 action: "close",
202 },
203 });
204 pending.current.delete(pullRequestEntryKey(entry));
205 setClosingKeys(new Set(pending.current));
206 if (result._tag === "Failure") {
207 failures.push(
208 `#${entry.number}: ${readableFailure(squashAtomCommandFailure(result), actionFailureHints(sourceControlClients.get(entry.provider).changeRequest.singular).close)}`,
209 );
210 return;
211 }
212 onClosed(entry);
213 return true;
214 }),
215 );
216 const closed = outcomes.filter(Boolean).length;
217 toastManager.add({
218 type: failures.length > 0 ? "error" : "success",
219 title:
220 failures.length > 0
221 ? `Closed ${closed} of ${batch.length} pull requests`
222 : `Closed ${closed} pull request${closed === 1 ? "" : "s"}`,
223 ...(failures.length > 0 ? { description: failures.slice(0, 3).join("\n") } : {}),
224 });
225 };
226 return { close, closingKeys };
227}
228
229export interface PullRequestThreadTask {
230 prompt: string;
231 reviewComments?: ReadonlyArray<ReviewCommentContext>;
232}
233
234export type PullRequestHandoffDetail = Pick<
235 PullRequestDetail,
236 "projectId" | "workspaceRoot" | "url"
237>;
238
239const lastHandoffPromptByDraft = new Map<DraftId, string>();
240
241export function usePullRequestHandoffs({
242 environmentId,
243 detail,
244}: {
245 environmentId: EnvironmentId;
246 detail: PullRequestHandoffDetail | null;
247}) {
248 const newThread = useNewThreadHandler();
249 const prepareThread = usePreparePullRequestThreadAction({
250 environmentId,
251 cwd: detail?.workspaceRoot ?? null,
252 });
253 // Serialize all handoffs because they check out the same pull request.
254 const [handoff, setHandoff] = useState<string | null>(null);
255 // Prompt links hand over a URL alone, so the URL is what names the host.
256 const terminology = (
257 (detail && sourceControlClients.findByChangeRequestUrl(detail.url)) ||
258 sourceControlClients.get(undefined)
259 ).changeRequest;
260
261 // Questions must not change checkouts or create worktrees.
262 const openThreadWithTask = async (
263 projectRef: ReturnType<typeof scopeProjectRef>,
264 task: PullRequestThreadTask | null,
265 opened?: { draftId: DraftId },
266 ): Promise<{ draftId: DraftId } | null> => {
267 const session =
268 opened ??
269 (await newThread(projectRef).then(
270 (result) => result,
271 () => null,
272 ));
273 if (session === null) return null;
274 const store = useComposerDraftStore.getState();
275 if (task === null) return session;
276 const draft = store.getComposerDraft(session.draftId);
277 const existingComments = draft?.reviewComments ?? [];
278 const prompt = handoffPrompt(
279 {
280 prompt: draft?.prompt ?? "",
281 lastHandoffPrompt: lastHandoffPromptByDraft.get(session.draftId),
282 },
283 task.prompt,
284 );
285 // Track only the handoff contribution so later handoffs preserve user text.
286 lastHandoffPromptByDraft.set(session.draftId, task.prompt);
287 store.setPrompt(session.draftId, prompt);
288 store.setReviewComments(
289 session.draftId,
290 handoffReviewComments(existingComments, task.reviewComments ?? []),
291 );
292 return session;
293 };
294
295 const startAsk = async (kind: string, task: PullRequestThreadTask) => {
296 if (!detail || handoff !== null) return;
297 setHandoff(kind);
298 const projectRef = scopeProjectRef(environmentId, detail.projectId);
299 const opened = await openThreadWithTask(projectRef, task);
300 setHandoff(null);
301 if (opened === null) {
302 toastManager.add({
303 type: "error",
304 title: "Could not open a thread",
305 description: "Try again from the project, or open a thread first.",
306 });
307 return;
308 }
309 toastManager.add({
310 type: "success",
311 title: "Asked in a thread",
312 description:
313 task.prompt.length > 0
314 ? "The question is in the composer. Read it over, then send."
315 : `The ${terminology.singular} is in the composer. Type your question, then send.`,
316 });
317 };
318
319 const startHandoff = async (
320 kind: string,
321 task: PullRequestThreadTask | null,
322 mode: "worktree" | "local" = "worktree",
323 ) => {
324 if (!detail || handoff !== null) return;
325 setHandoff(kind);
326 // Explicit timeouts survive toast updates and would pin the result after loading.
327 const toastId = toastManager.add({
328 type: "loading",
329 title: `Preparing the ${terminology.singular} checkout...`,
330 });
331 const projectRef = scopeProjectRef(environmentId, detail.projectId);
332 // Checkout setup requires the thread to exist first.
333 const opened = await newThread(projectRef).then(
334 (session) => session,
335 () => null,
336 );
337 if (opened === null) {
338 setHandoff(null);
339 toastManager.update(toastId, {
340 type: "error",
341 title: "Could not open a thread for the checkout",
342 description: "Try again from the project, or open a thread first.",
343 });
344 return;
345 }
346 const prepared = await prepareThread.run({
347 reference: detail.url,
348 mode,
349 threadId: opened.threadId,
350 });
351 if (prepared._tag === "Failure") {
352 setHandoff(null);
353 toastManager.update(toastId, {
354 type: "error",
355 title: `Could not prepare the ${terminology.singular} checkout`,
356 description: checkoutFailureDescription(
357 isAtomCommandInterrupted(prepared) ? undefined : squashAtomCommandFailure(prepared),
358 ),
359 });
360 return;
361 }
362 const pointed = await newThread(projectRef, {
363 branch: prepared.value.branch,
364 worktreePath: prepared.value.worktreePath,
365 envMode: prepared.value.worktreePath === null ? "local" : "worktree",
366 }).then(
367 (session) => session !== null,
368 () => false,
369 );
370 if (!pointed) {
371 setHandoff(null);
372 toastManager.update(toastId, {
373 type: "error",
374 title: "Checked out, but the thread stayed where it was",
375 description: `The checkout is ready on \`${prepared.value.branch}\`. Point a thread at it from the branch picker, then ask again.`,
376 });
377 return;
378 }
379 setHandoff(null);
380 if (task === null) {
381 toastManager.update(
382 toastId,
383 prepared.value.isOnPullRequestHead
384 ? {
385 type: "success",
386 title: mode === "local" ? "Checked out here" : "Checked out",
387 description:
388 mode === "local"
389 ? `This repository is on the ${terminology.singular}'s branch, with a thread open on it.`
390 : `The ${terminology.singular} is in its own worktree, with a thread open on it.`,
391 }
392 : offHeadPullRequestCheckoutToast(terminology),
393 );
394 return;
395 }
396 await openThreadWithTask(projectRef, task, opened);
397 toastManager.update(
398 toastId,
399 prepared.value.isOnPullRequestHead
400 ? {
401 type: "success",
402 title: "Checkout ready",
403 description: "The task is in the composer. Read it over, then send.",
404 }
405 : offHeadPullRequestCheckoutToast(terminology),
406 );
407 };
408
409 return { handoff, startAsk, startHandoff };
410}