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

usePullRequestActions.ts

471 lines19.7 KB

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