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