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