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

usePullRequestActions.ts

457 lines16.6 KB

1import { useAtomCommand } from "~/state/use-atom-command";
2import { scopeProjectRef } from "@t3tools/client-runtime/environment";
3import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
4import type {
5 EnvironmentId,
6 ProjectId,
7 PullRequestAction,
8 PullRequestDetail,
9 PullRequestMergeMethod,
10 PullRequestRef,
11} from "@t3tools/contracts";
12import { useRef, useState, useSyncExternalStore } from "react";
13import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
14import { useClientSettings, useEnvironmentSettings } from "~/hooks/useSettings";
15import {
16 deriveLogicalProjectKeyFromSettings,
17 derivePhysicalProjectKey,
18 selectProjectGroupingSettings,
19} from "~/logicalProject";
20import { buildPhysicalToLogicalProjectKeyMap } from "~/sidebarProjectGrouping";
21import { useProjects } from "~/state/entities";
22import { usePrimaryEnvironmentId } from "~/state/environments";
23​
24import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
25import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
26import { usePreparePullRequestThreadAction } from "~/lib/sourceControlActions";
27import type { ReviewCommentContext } from "~/reviewCommentContext";
28import { pullRequestEnvironment } from "~/state/pullRequests";
29​
30import { toastManager } from "../ui/toast";
31import { handoffPrompt, handoffReviewComments, readableFailure } from "./pullRequestDetail.logic";
32import { pullRequestEntryKey, type EnvironmentPullRequestEntry } from "./pullRequestList.logic";
33​
34export function usePullRequestDefaultMergeMethodResolver(
35 environmentId: EnvironmentId,
36 projectId: ProjectId,
37) {
38 const projectDefault = useEnvironmentSettings(
39 environmentId,
40 (settings) => resolveProjectSettings(settings, projectId).settings.pullRequestMergeMethod,
41 );
42 const legacyOverrides = useClientSettings((settings) => settings.pullRequestMergeMethodOverrides);
43 const grouping = useClientSettings(selectProjectGroupingSettings);
44 const projects = useProjects();
45 const primaryEnvironmentId = usePrimaryEnvironmentId();
46 return () => {
47 if (projectDefault != null) return projectDefault;
48 if (Object.keys(legacyOverrides).length === 0) return undefined;
49 const project = projects.find(
50 (candidate) => candidate.environmentId === environmentId && candidate.id === projectId,
51 );
52 if (!project) return undefined;
53 const key =
54 buildPhysicalToLogicalProjectKeyMap({
55 projects,
56 settings: grouping,
57 primaryEnvironmentId,
58 }).get(derivePhysicalProjectKey(project)) ??
59 deriveLogicalProjectKeyFromSettings(project, grouping);
60 return legacyOverrides[key];
61 };
63​
64const ACTION_SUCCESS_LABELS: Record<PullRequestAction, string> = {
65 merge: "Merge requested",
66 ready: "Marked ready for review",
67 draft: "Converted to draft",
68 close: "Pull request closed",
69 reopen: "Pull request reopened",
70 "update-branch": "Branch updated with the base branch",
71 "enable-auto-merge": "Auto-merge enabled",
72 "disable-auto-merge": "Auto-merge disabled",
73 revert: "Revert pull request opened",
74 "delete-branch": "Branch deleted",
75 "approve-workflows": "Workflows approved",
76};
77​
78const ACTION_FAILURE_LABELS: Record<PullRequestAction, string> = {
79 merge: "Could not merge this pull request",
80 ready: "Could not mark this ready for review",
81 draft: "Could not convert this to a draft",
82 close: "Could not close this pull request",
83 reopen: "Could not reopen this pull request",
84 "update-branch": "Could not update this branch",
85 "enable-auto-merge": "Could not enable auto-merge",
86 "disable-auto-merge": "Could not disable auto-merge",
87 revert: "Could not open a revert pull request",
88 "delete-branch": "Could not delete this branch",
89 "approve-workflows": "Could not approve workflows",
90};
91​
92const ACTION_FAILURE_HINTS: Record<PullRequestAction, string> = {
93 merge:
94 "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.",
95 ready: "The host refused it. Check that you have write access to this repository.",
96 draft: "The host refused it. Check that you have write access to this repository.",
97 close: "The host refused it. Check that you have write access, or that you opened it.",
98 reopen:
99 "The host refused it. Check that you have write access, and that the branch still exists.",
100 "update-branch":
101 "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.",
102 "enable-auto-merge":
103 "The host refused it. Check that auto-merge is enabled for this repository and that you have write access.",
104 "disable-auto-merge": "The host refused it. Check that you have write access to this repository.",
105 revert:
106 "The host refused it. Check that you have write access and that this pull request was merged on the host.",
107 "delete-branch":
108 "The host refused it. Check that you have write access to the source repository and that the branch has not moved since this page loaded.",
109 "approve-workflows":
110 "The host refused it. Check that you have Actions write access and that these workflow runs are still awaiting approval.",
111};
112​
113// Share pending actions across virtualized row remounts and other PR surfaces.
114const pendingActionKeys = new Set<string>();
115const pendingActionListeners = new Set<() => void>();
116​
117function setPullRequestActionPending(key: string, pending: boolean) {
118 if (pending) pendingActionKeys.add(key);
119 else pendingActionKeys.delete(key);
120 for (const listener of pendingActionListeners) listener();
122​
123function subscribePullRequestActionsPending(listener: () => void) {
124 pendingActionListeners.add(listener);
125 return () => {
126 pendingActionListeners.delete(listener);
127 };
129​
130async function withPendingAction(
131 key: string,
132 action: () => Promise<void>,
133 onFailure: (failure: unknown) => void,
134) {
135 setPullRequestActionPending(key, true);
136 try {
137 await action();
138 } catch (failure) {
139 onFailure(failure);
140 } finally {
141 setPullRequestActionPending(key, false);
142 }
144​
145/** Whether a host action is running against this pull request. */
146export function isPullRequestActionPending(key: string): boolean {
147 return pendingActionKeys.has(key);
149​
150/**
151 * Runs one host action against a pull request, with the toasts every surface should say the same
152 * way. `onSuccess` is where the caller re-reads whatever it is showing.
153 */
154export function usePullRequestActionRunner({
155 environmentId,
156 reference,
157 onSuccess,
158 resolveMergeMethod,
159}: {
160 environmentId: EnvironmentId;
161 reference: PullRequestRef | null;
162 onSuccess?: (action: PullRequestAction) => void;
163 /** Small surfaces resolve repository settings on the click, not for every visible row. */
164 resolveMergeMethod?: (detail: PullRequestDetail) => PullRequestMergeMethod;
165}) {
166 const runAction = useAtomCommand(pullRequestEnvironment.runAction, {
167 reportFailure: false,
168 });
169 const key =
170 reference === null
171 ? null
172 : pullRequestEntryKey({
173 environmentId,
174 host: reference.host ?? "",
175 repository: reference.repository,
176 number: reference.number,
177 });
178 const actionPending = useSyncExternalStore(
179 subscribePullRequestActionsPending,
180 () => key !== null && pendingActionKeys.has(key),
181 );
182​
183 const perform = async (action: PullRequestAction, method?: PullRequestMergeMethod) => {
184 if (reference === null || key === null || pendingActionKeys.has(key)) return;
185 await withPendingAction(
186 key,
187 async () => {
188 const result = await runAction({
189 environmentId,
190 input: {
191 ...reference,
192 action,
193 ...(method
194 ? { mergeMethod: method }
195 : resolveMergeMethod
196 ? { resolveMergeMethod }
197 : {}),
198 },
199 });
200 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
201 toastManager.add({ type: "success", title: ACTION_SUCCESS_LABELS[action] });
202 onSuccess?.(action);
203 },
204 (failure) => {
205 toastManager.add({
206 type: "error",
207 title: ACTION_FAILURE_LABELS[action],
208 description: readableFailure(failure, ACTION_FAILURE_HINTS[action]),
209 });
210 },
211 );
212 };
213​
214 return { actionPending, perform };
216​
217export function usePullRequestCloseBatch(onClosed: (entry: EnvironmentPullRequestEntry) => void) {
218 const runAction = useAtomCommand(pullRequestEnvironment.runAction, { reportFailure: false });
219 const pending = useRef(new Set<string>());
220 const [closingKeys, setClosingKeys] = useState<ReadonlySet<string>>(() => new Set());
221 const close = async (entries: readonly EnvironmentPullRequestEntry[]) => {
222 const batch = entries.filter((entry) => {
223 const key = pullRequestEntryKey(entry);
224 if (entry.state !== "open" || pending.current.has(key)) return false;
225 pending.current.add(key);
226 return true;
227 });
228 if (batch.length === 0) return;
229 setClosingKeys(new Set(pending.current));
230 const failures: string[] = [];
231 const outcomes = await Promise.all(
232 batch.map(async (entry) => {
233 const result = await runAction({
234 environmentId: entry.environmentId,
235 input: {
236 projectId: entry.projectId,
237 host: entry.host,
238 repository: entry.repository,
239 number: entry.number,
240 action: "close",
241 },
242 });
243 pending.current.delete(pullRequestEntryKey(entry));
244 setClosingKeys(new Set(pending.current));
245 if (result._tag === "Failure") {
246 failures.push(
247 `#${entry.number}: ${readableFailure(squashAtomCommandFailure(result), ACTION_FAILURE_HINTS.close)}`,
248 );
249 return;
250 }
251 onClosed(entry);
252 return true;
253 }),
254 );
255 const closed = outcomes.filter(Boolean).length;
256 toastManager.add({
257 type: failures.length > 0 ? "error" : "success",
258 title:
259 failures.length > 0
260 ? `Closed ${closed} of ${batch.length} pull requests`
261 : `Closed ${closed} pull request${closed === 1 ? "" : "s"}`,
262 ...(failures.length > 0 ? { description: failures.slice(0, 3).join("\n") } : {}),
263 });
264 };
265 return { close, closingKeys };
267​
268export interface PullRequestThreadTask {
269 prompt: string;
270 reviewComments?: ReadonlyArray<ReviewCommentContext>;
272​
273export type PullRequestHandoffDetail = Pick<
274 PullRequestDetail,
275 "projectId" | "workspaceRoot" | "url"
276>;
277​
278const lastHandoffPromptByDraft = new Map<DraftId, string>();
279​
280export function usePullRequestHandoffs({
281 environmentId,
282 detail,
283}: {
284 environmentId: EnvironmentId;
285 detail: PullRequestHandoffDetail | null;
286}) {
287 const newThread = useNewThreadHandler();
288 const prepareThread = usePreparePullRequestThreadAction({
289 environmentId,
290 cwd: detail?.workspaceRoot ?? null,
291 });
292 // One at a time whatever the key: they all check the same pull request out.
293 const [handoff, setHandoff] = useState<string | null>(null);
294​
295 /**
296 * Nothing is checked out: asking a question is not a reason to move somebody's working tree
297 * or to make a worktree they did not ask for.
298 */
299 const openThreadWithTask = async (
300 projectRef: ReturnType<typeof scopeProjectRef>,
301 task: PullRequestThreadTask | null,
302 opened?: { draftId: DraftId },
303 ): Promise<{ draftId: DraftId } | null> => {
304 const session =
305 opened ??
306 (await newThread(projectRef).then(
307 (result) => result,
308 () => null,
309 ));
310 if (session === null) return null;
311 const store = useComposerDraftStore.getState();
312 if (task === null) return session;
313 const draft = store.getComposerDraft(session.draftId);
314 const existingComments = draft?.reviewComments ?? [];
315 const prompt = handoffPrompt(
316 {
317 prompt: draft?.prompt ?? "",
318 lastHandoffPrompt: lastHandoffPromptByDraft.get(session.draftId),
319 },
320 task.prompt,
321 );
322 // Remember the hand-off's own contribution, not the merged prompt: only that sentence is
323 // this session's to take back next time, and the reader's text around it is not.
324 lastHandoffPromptByDraft.set(session.draftId, task.prompt);
325 store.setPrompt(session.draftId, prompt);
326 store.setReviewComments(
327 session.draftId,
328 handoffReviewComments(existingComments, task.reviewComments ?? []),
329 );
330 return session;
331 };
332​
333 const startAsk = async (kind: string, task: PullRequestThreadTask) => {
334 if (!detail || handoff !== null) return;
335 setHandoff(kind);
336 const projectRef = scopeProjectRef(environmentId, detail.projectId);
337 const opened = await openThreadWithTask(projectRef, task);
338 setHandoff(null);
339 if (opened === null) {
340 toastManager.add({
341 type: "error",
342 title: "Could not open a thread",
343 description: "Try again from the project, or open a thread first.",
344 });
345 return;
346 }
347 toastManager.add({
348 type: "success",
349 title: "Asked in a thread",
350 description:
351 task.prompt.length > 0
352 ? "The question is in the composer — read it over, then send."
353 : "The pull request is in the composer — type your question, then send.",
354 });
355 };
356​
357 const startHandoff = async (
358 kind: string,
359 task: PullRequestThreadTask | null,
360 mode: "worktree" | "local" = "worktree",
361 ) => {
362 if (!detail || handoff !== null) return;
363 setHandoff(kind);
364 // It carries no timeout of its own: a loading toast never expires, and an explicit one
365 // would survive the update and pin the result on screen.
366 const toastId = toastManager.add({
367 type: "loading",
368 title: "Preparing the pull request checkout...",
369 });
370 const projectRef = scopeProjectRef(environmentId, detail.projectId);
371 // The thread is opened before the checkout rather than after it, because the project's setup
372 // script only runs for a checkout that knows which thread it is for — and a worktree with no
373 // dependencies installed is not something anyone can test.
374 const opened = await newThread(projectRef).then(
375 (session) => session,
376 () => null,
377 );
378 if (opened === null) {
379 setHandoff(null);
380 toastManager.update(toastId, {
381 type: "error",
382 title: "Could not open a thread for the checkout",
383 description: "Try again from the project, or open a thread first.",
384 });
385 return;
386 }
387 const prepared = await prepareThread.run({
388 reference: detail.url,
389 mode,
390 threadId: opened.threadId,
391 });
392 if (prepared._tag === "Failure") {
393 setHandoff(null);
394 const detailMessage =
395 prepareThread.error instanceof Error ? prepareThread.error.message : null;
396 toastManager.update(toastId, {
397 type: "error",
398 title: "Could not prepare the pull request checkout",
399 ...(detailMessage ? { description: detailMessage } : {}),
400 });
401 return;
402 }
403 const pointed = await newThread(projectRef, {
404 branch: prepared.value.branch,
405 worktreePath: prepared.value.worktreePath,
406 envMode: prepared.value.worktreePath === null ? "local" : "worktree",
407 }).then(
408 (session) => session !== null,
409 () => false,
410 );
411 if (!pointed) {
412 setHandoff(null);
413 toastManager.update(toastId, {
414 type: "error",
415 title: "Checked out, but the thread stayed where it was",
416 description: `The checkout is ready on \`${prepared.value.branch}\`. Point a thread at it from the branch picker, then ask again.`,
417 });
418 return;
419 }
420 setHandoff(null);
421 const staleCheckoutToast = {
422 type: "warning",
423 title: "Checked out, but not on the latest commits",
424 description:
425 "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.",
426 } as const;
427 if (task === null) {
428 toastManager.update(
429 toastId,
430 prepared.value.isOnPullRequestHead
431 ? {
432 type: "success",
433 title: mode === "local" ? "Checked out here" : "Checked out",
434 description:
435 mode === "local"
436 ? "This repository is on the pull request's branch, with a thread open on it."
437 : "The pull request is in its own worktree, with a thread open on it.",
438 }
439 : staleCheckoutToast,
440 );
441 return;
442 }
443 await openThreadWithTask(projectRef, task, opened);
444 toastManager.update(
445 toastId,
446 prepared.value.isOnPullRequestHead
447 ? {
448 type: "success",
449 title: "Checkout ready",
450 description: "The task is in the composer — read it over, then send.",
451 }
452 : staleCheckoutToast,
453 );
454 };
455​
456 return { handoff, startAsk, startHandoff };