Open History to see the last commit
1/**
2 * The actions a pull request offers, extracted from the detail panel so smaller surfaces — the
3 * thread details panel's pull request row — perform them through the very same code. Two callers
4 * running two copies of "merge" or "resolve in a thread" would drift apart one fix at a time;
5 * these hooks are where that behavior lives, and the panels are only where it is rendered.
6 */
7import { scopeProjectRef } from "@t3tools/client-runtime/environment";
8import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
9import type {
10 EnvironmentId,
11 ProjectId,
12 PullRequestAction,
13 PullRequestDetail,
14 PullRequestMergeMethod,
15 PullRequestRef,
16} from "@t3tools/contracts";
17import { useCallback, useRef, useState } from "react";
18import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
19import { useClientSettings, useEnvironmentSettings } from "~/hooks/useSettings";
20import {
21 deriveLogicalProjectKeyFromSettings,
22 derivePhysicalProjectKey,
23 selectProjectGroupingSettings,
24} from "~/logicalProject";
25import { buildPhysicalToLogicalProjectKeyMap } from "~/sidebarProjectGrouping";
26import { useProjects } from "~/state/entities";
27import { usePrimaryEnvironmentId } from "~/state/environments";
28
29import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
30import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
31import { usePreparePullRequestThreadAction } from "~/lib/sourceControlActions";
32import type { ReviewCommentContext } from "~/reviewCommentContext";
33import { pullRequestEnvironment } from "~/state/pullRequests";
34import { useAtomCommand } from "~/state/use-atom-command";
35
36import { toastManager } from "../ui/toast";
37import { handoffPrompt, handoffReviewComments, readableFailure } from "./pullRequestDetail.logic";
38import { pullRequestEntryKey, type EnvironmentPullRequestEntry } from "./pullRequestList.logic";
39
40/** Resolve on demand so hidden quick actions do not rebuild the legacy project grouping. */
41export function usePullRequestDefaultMergeMethodResolver(
42 environmentId: EnvironmentId,
43 projectId: ProjectId,
44) {
45 const projectDefault = useEnvironmentSettings(
46 environmentId,
47 (settings) => resolveProjectSettings(settings, projectId).settings.pullRequestMergeMethod,
48 );
49 const legacyOverrides = useClientSettings((settings) => settings.pullRequestMergeMethodOverrides);
50 const grouping = useClientSettings(selectProjectGroupingSettings);
51 const projects = useProjects();
52 const primaryEnvironmentId = usePrimaryEnvironmentId();
53 return useCallback(() => {
54 if (projectDefault != null) return projectDefault;
55 if (Object.keys(legacyOverrides).length === 0) return undefined;
56 const project = projects.find(
57 (candidate) => candidate.environmentId === environmentId && candidate.id === projectId,
58 );
59 if (!project) return undefined;
60 // Duplicate sidebar rows borrow their logical group key from their siblings.
61 const key =
62 buildPhysicalToLogicalProjectKeyMap({
63 projects,
64 settings: grouping,
65 primaryEnvironmentId,
66 }).get(derivePhysicalProjectKey(project)) ??
67 deriveLogicalProjectKeyFromSettings(project, grouping);
68 return legacyOverrides[key];
69 }, [
70 projectDefault,
71 projects,
72 environmentId,
73 projectId,
74 grouping,
75 primaryEnvironmentId,
76 legacyOverrides,
77 ]);
78}
79
80const ACTION_SUCCESS_LABELS: Record<PullRequestAction, string> = {
81 merge: "Merge requested",
82 ready: "Marked ready for review",
83 draft: "Converted to draft",
84 close: "Pull request closed",
85 reopen: "Pull request reopened",
86 "update-branch": "Branch updated with the base branch",
87 "enable-auto-merge": "Auto-merge enabled",
88 "disable-auto-merge": "Auto-merge disabled",
89 revert: "Revert pull request opened",
90 "approve-workflows": "Workflows approved",
91};
92
93/** Said as the thing that did not happen, rather than as the operation that returned an error. */
94const ACTION_FAILURE_LABELS: Record<PullRequestAction, string> = {
95 merge: "Could not merge this pull request",
96 ready: "Could not mark this ready for review",
97 draft: "Could not convert this to a draft",
98 close: "Could not close this pull request",
99 reopen: "Could not reopen this pull request",
100 "update-branch": "Could not update this branch",
101 "enable-auto-merge": "Could not enable auto-merge",
102 "disable-auto-merge": "Could not disable auto-merge",
103 revert: "Could not open a revert pull request",
104 "approve-workflows": "Could not approve workflows",
105};
106
107/** What to try, for the times the host says only that it refused. */
108const ACTION_FAILURE_HINTS: Record<PullRequestAction, string> = {
109 merge:
110 "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.",
111 ready: "The host refused it. Check that you have write access to this repository.",
112 draft: "The host refused it. Check that you have write access to this repository.",
113 close: "The host refused it. Check that you have write access, or that you opened it.",
114 reopen:
115 "The host refused it. Check that you have write access, and that the branch still exists.",
116 "update-branch":
117 "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.",
118 "enable-auto-merge":
119 "The host refused it. Check that auto-merge is enabled for this repository and that you have write access.",
120 "disable-auto-merge": "The host refused it. Check that you have write access to this repository.",
121 revert:
122 "The host refused it. Check that you have write access and that this pull request was merged on the host.",
123 "approve-workflows":
124 "The host refused it. Check that you have Actions write access and that these workflow runs are still awaiting approval.",
125};
126
127/**
128 * Runs one host action against a pull request, with the toasts every surface should say the same
129 * way. `onSuccess` is where the caller re-reads whatever it is showing.
130 */
131export function usePullRequestActionRunner({
132 environmentId,
133 reference,
134 onSuccess,
135 resolveMergeMethod,
136}: {
137 environmentId: EnvironmentId;
138 reference: PullRequestRef | null;
139 onSuccess?: (action: PullRequestAction) => void;
140 /** Small surfaces resolve repository settings on the click, not for every visible row. */
141 resolveMergeMethod?: (detail: PullRequestDetail) => PullRequestMergeMethod;
142}) {
143 const runAction = useAtomCommand(pullRequestEnvironment.runAction, { reportFailure: false });
144 const [actionPending, setActionPending] = useState(false);
145 const pendingRef = useRef(false);
146
147 const perform = async (action: PullRequestAction, method?: PullRequestMergeMethod) => {
148 if (pendingRef.current || reference === null) return;
149 pendingRef.current = true;
150 setActionPending(true);
151 try {
152 const result = await runAction({
153 environmentId,
154 input: {
155 ...reference,
156 action,
157 ...(method ? { mergeMethod: method } : resolveMergeMethod ? { resolveMergeMethod } : {}),
158 },
159 });
160 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
161 toastManager.add({ type: "success", title: ACTION_SUCCESS_LABELS[action] });
162 onSuccess?.(action);
163 } catch (failure) {
164 toastManager.add({
165 type: "error",
166 title: ACTION_FAILURE_LABELS[action],
167 description: readableFailure(failure, ACTION_FAILURE_HINTS[action]),
168 });
169 } finally {
170 pendingRef.current = false;
171 setActionPending(false);
172 }
173 };
174
175 return { actionPending, perform };
176}
177
178/** Queue a close sweep through the same environment lanes as individual actions. */
179export function usePullRequestCloseBatch(onClosed: (entry: EnvironmentPullRequestEntry) => void) {
180 const runAction = useAtomCommand(pullRequestEnvironment.runAction, { reportFailure: false });
181 const pending = useRef(new Set<string>());
182 const [closingKeys, setClosingKeys] = useState<ReadonlySet<string>>(() => new Set());
183 const close = useCallback(
184 async (entries: readonly EnvironmentPullRequestEntry[]) => {
185 const batch = entries.filter((entry) => {
186 const key = pullRequestEntryKey(entry);
187 if (entry.state !== "open" || entry.provider !== "github" || pending.current.has(key))
188 return false;
189 pending.current.add(key);
190 return true;
191 });
192 if (batch.length === 0) return;
193 setClosingKeys(new Set(pending.current));
194 let closed = 0;
195 const failures: string[] = [];
196 await Promise.all(
197 batch.map(async (entry) => {
198 try {
199 const result = await runAction({
200 environmentId: entry.environmentId,
201 input: {
202 projectId: entry.projectId,
203 host: entry.host,
204 repository: entry.repository,
205 number: entry.number,
206 action: "close",
207 },
208 });
209 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
210 closed++;
211 onClosed(entry);
212 } catch (failure) {
213 failures.push(
214 `#${entry.number}: ${readableFailure(failure, ACTION_FAILURE_HINTS.close)}`,
215 );
216 } finally {
217 pending.current.delete(pullRequestEntryKey(entry));
218 setClosingKeys(new Set(pending.current));
219 }
220 }),
221 );
222 toastManager.add({
223 type: failures.length > 0 ? "error" : "success",
224 title:
225 failures.length > 0
226 ? `Closed ${closed} of ${batch.length} pull requests`
227 : `Closed ${closed} pull request${closed === 1 ? "" : "s"}`,
228 ...(failures.length > 0 ? { description: failures.slice(0, 3).join("\n") } : {}),
229 });
230 },
231 [onClosed, runAction],
232 );
233 return { close, closingKeys };
234}
235
236export interface PullRequestThreadTask {
237 prompt: string;
238 reviewComments?: ReadonlyArray<ReviewCommentContext>;
239}
240
241/** What a hand-off needs to know about the pull request it is handing over. */
242export type PullRequestHandoffDetail = Pick<
243 PullRequestDetail,
244 "projectId" | "workspaceRoot" | "url"
245>;
246
247/**
248 * What the last hand-off wrote into each draft, kept outside React because the panel that wrote it
249 * is closed by the time the next one opens. It is how a prompt the reader has since edited is told
250 * apart from the one they were handed: only the sentence still exactly as written may be replaced.
251 */
252const lastHandoffPromptByDraft = new Map<DraftId, string>();
253
254/**
255 * The hand-offs from a pull request into a thread: a question that needs nothing checked out, and
256 * a task that needs the branch under the agent's feet first. One `handoff` key holds them all to
257 * one at a time, whatever surface pressed the button.
258 */
259export function usePullRequestHandoffs({
260 environmentId,
261 detail,
262}: {
263 environmentId: EnvironmentId;
264 detail: PullRequestHandoffDetail | null;
265}) {
266 const newThread = useNewThreadHandler();
267 const prepareThread = usePreparePullRequestThreadAction({
268 environmentId,
269 cwd: detail?.workspaceRoot ?? null,
270 });
271 // Which handoff is preparing, keyed so a per-finding button can say "Preparing..." on itself
272 // alone. One at a time whatever the key: they all check the same pull request out.
273 const [handoff, setHandoff] = useState<string | null>(null);
274
275 /**
276 * Opens a thread on this project and leaves the task in its composer for the reader to send.
277 *
278 * Nothing is checked out: asking a question is not a reason to move somebody's working tree or
279 * to make a worktree they did not ask for. The two hand-offs that do need the code call this
280 * after preparing it, so there is one path from "a task" to "a thread holding it".
281 */
282 const openThreadWithTask = async (
283 projectRef: ReturnType<typeof scopeProjectRef>,
284 task: PullRequestThreadTask | null,
285 opened?: { draftId: DraftId },
286 ): Promise<{ draftId: DraftId } | null> => {
287 const session =
288 opened ??
289 (await newThread(projectRef).then(
290 (result) => result,
291 () => null,
292 ));
293 if (session === null) return null;
294 const store = useComposerDraftStore.getState();
295 if (task === null) return session;
296 // The latest press is the ask: it takes over what an earlier hand-off left, prompt and chips
297 // both, rather than stacking a second one under the first. What the reader typed themselves
298 // survives — the composer they are handed is not always a fresh one, and a prompt they have
299 // since edited is theirs rather than the hand-off's.
300 const draft = store.getComposerDraft(session.draftId);
301 const existingComments = draft?.reviewComments ?? [];
302 const prompt = handoffPrompt(
303 {
304 prompt: draft?.prompt ?? "",
305 lastHandoffPrompt: lastHandoffPromptByDraft.get(session.draftId),
306 },
307 task.prompt,
308 );
309 // Remember the hand-off's own contribution, not the merged prompt: only that sentence is
310 // this session's to take back next time, and the reader's text around it is not.
311 lastHandoffPromptByDraft.set(session.draftId, task.prompt);
312 store.setPrompt(session.draftId, prompt);
313 store.setReviewComments(
314 session.draftId,
315 handoffReviewComments(existingComments, task.reviewComments ?? []),
316 );
317 return session;
318 };
319
320 /** A question about the change, which needs a thread and nothing else. */
321 const startAsk = async (kind: string, task: PullRequestThreadTask) => {
322 if (!detail || handoff !== null) return;
323 setHandoff(kind);
324 const projectRef = scopeProjectRef(environmentId, detail.projectId);
325 const opened = await openThreadWithTask(projectRef, task);
326 setHandoff(null);
327 if (opened === null) {
328 toastManager.add({
329 type: "error",
330 title: "Could not open a thread",
331 description: "Try again from the project, or open a thread first.",
332 });
333 return;
334 }
335 toastManager.add({
336 type: "success",
337 title: "Asked in a thread",
338 // "Ask" leaves the composer empty on purpose, so saying the question is in it would send
339 // the reader looking for something that is not there. The chips are what landed.
340 description:
341 task.prompt.length > 0
342 ? "The question is in the composer — read it over, then send."
343 : "The pull request is in the composer — type your question, then send.",
344 });
345 };
346
347 // Every handoff works the same way: check the pull request out into its own worktree, open a
348 // thread there, and — when it carries a task — put that in the composer for the user to read
349 // before sending. Checking out is the whole point of the ones that carry nothing.
350 const startHandoff = async (
351 kind: string,
352 task: PullRequestThreadTask | null,
353 // A worktree leaves whatever is open alone, which is why it is the default. Checking out in
354 // the repository itself is what you want when the point is to run the thing where you
355 // already work — and it moves the branch under everything else that is open there.
356 mode: "worktree" | "local" = "worktree",
357 ) => {
358 if (!detail || handoff !== null) return;
359 setHandoff(kind);
360 // The menu closes on the press and takes its "Preparing..." label with it, so this is the
361 // only thing answering for the checkout. It carries no timeout of its own: a loading toast
362 // never expires, and an explicit one would survive the update and pin the result on screen.
363 const toastId = toastManager.add({
364 type: "loading",
365 title: "Preparing the pull request checkout...",
366 });
367 const projectRef = scopeProjectRef(environmentId, detail.projectId);
368 // The thread is opened before the checkout rather than after it, because the project's setup
369 // script only runs for a checkout that knows which thread it is for — and a worktree with no
370 // dependencies installed is not something anyone can test.
371 const opened = await newThread(projectRef).then(
372 (session) => session,
373 () => null,
374 );
375 if (opened === null) {
376 setHandoff(null);
377 // Without a thread there is nowhere for the checkout to belong: its setup script would not
378 // run and its task would have no composer to land in. Better to stop before touching the
379 // working tree than to prepare a worktree nobody asked for.
380 toastManager.update(toastId, {
381 type: "error",
382 title: "Could not open a thread for the checkout",
383 description: "Try again from the project, or open a thread first.",
384 });
385 return;
386 }
387 const prepared = await prepareThread.run({
388 reference: detail.url,
389 mode,
390 threadId: opened.threadId,
391 });
392 if (prepared._tag === "Failure") {
393 setHandoff(null);
394 // The server says what to do about it — that the branch is already checked out in the main
395 // repository, say — and that sentence is the only way out of the failure.
396 const detailMessage =
397 prepareThread.error instanceof Error ? prepareThread.error.message : null;
398 toastManager.update(toastId, {
399 type: "error",
400 title: "Could not prepare the pull request checkout",
401 ...(detailMessage ? { description: detailMessage } : {}),
402 });
403 return;
404 }
405 // The same thread again, now that there is somewhere to point it at. A local checkout has
406 // no worktree of its own, so the thread runs where the repository already is.
407 const pointed = await newThread(projectRef, {
408 branch: prepared.value.branch,
409 worktreePath: prepared.value.worktreePath,
410 envMode: prepared.value.worktreePath === null ? "local" : "worktree",
411 }).then(
412 (session) => session !== null,
413 () => false,
414 );
415 if (!pointed) {
416 setHandoff(null);
417 // The checkout is on disk; only the thread failed to move onto it. Writing the task now
418 // would send the agent at whatever the thread was already open on — which is the one
419 // outcome worth stopping for, since it reads as success and is not.
420 toastManager.update(toastId, {
421 type: "error",
422 title: "Checked out, but the thread stayed where it was",
423 description: `The checkout is ready on \`${prepared.value.branch}\`. Point a thread at it from the branch picker, then ask again.`,
424 });
425 return;
426 }
427 // Released here whatever happened next: a loading toast never expires on its own, so leaving
428 // this set would spin forever and lock every handoff behind it until a reload.
429 setHandoff(null);
430 // A worktree that was already there and had been worked in keeps whatever it holds, so the
431 // thread opens on older code than the pull request carries. Said once, in place of the
432 // success, because everything else about the handoff did happen.
433 const staleCheckoutToast = {
434 type: "warning",
435 title: "Checked out, but not on the latest commits",
436 description:
437 "The checkout could not be moved onto the pull request's latest commits, so the code there is older than the pull request. Uncommitted work or local commits keep it where it is.",
438 } as const;
439 if (task === null) {
440 toastManager.update(
441 toastId,
442 prepared.value.isOnPullRequestHead
443 ? {
444 type: "success",
445 title: mode === "local" ? "Checked out here" : "Checked out",
446 description:
447 mode === "local"
448 ? "This repository is on the pull request's branch, with a thread open on it."
449 : "The pull request is in its own worktree, with a thread open on it.",
450 }
451 : staleCheckoutToast,
452 );
453 return;
454 }
455 await openThreadWithTask(projectRef, task, opened);
456 toastManager.update(
457 toastId,
458 prepared.value.isOnPullRequestHead
459 ? {
460 type: "success",
461 title: "Checkout ready",
462 description: "The task is in the composer — read it over, then send.",
463 }
464 : staleCheckoutToast,
465 );
466 };
467
468 return { handoff, startAsk, startHandoff };
469}