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