Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usePullRequestActions.ts

344 lines14.9 KB

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