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

usePullRequestActions.ts

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