Open History to see the last commit
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 } 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 };
62}
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
113export function usePullRequestActionRunner({
114 environmentId,
115 reference,
116 onSuccess,
117 resolveMergeMethod,
118}: {
119 environmentId: EnvironmentId;
120 reference: PullRequestRef | null;
121 onSuccess?: (action: PullRequestAction) => void;
122 /** Small surfaces resolve repository settings on the click, not for every visible row. */
123 resolveMergeMethod?: (detail: PullRequestDetail) => PullRequestMergeMethod;
124}) {
125 const runAction = useAtomCommand(pullRequestEnvironment.runAction, {
126 reportFailure: false,
127 });
128 const [actionPending, setActionPending] = useState(false);
129 const pendingRef = useRef(false);
130
131 const perform = async (action: PullRequestAction, method?: PullRequestMergeMethod) => {
132 if (pendingRef.current || reference === null) return;
133 pendingRef.current = true;
134 setActionPending(true);
135 const result = await runAction({
136 environmentId,
137 input: {
138 ...reference,
139 action,
140 ...(method ? { mergeMethod: method } : resolveMergeMethod ? { resolveMergeMethod } : {}),
141 },
142 });
143 pendingRef.current = false;
144 setActionPending(false);
145 if (result._tag === "Failure") {
146 toastManager.add({
147 type: "error",
148 title: ACTION_FAILURE_LABELS[action],
149 description: readableFailure(
150 squashAtomCommandFailure(result),
151 ACTION_FAILURE_HINTS[action],
152 ),
153 });
154 return;
155 }
156 toastManager.add({ type: "success", title: ACTION_SUCCESS_LABELS[action] });
157 onSuccess?.(action);
158 };
159
160 return { actionPending, perform };
161}
162
163export function usePullRequestCloseBatch(onClosed: (entry: EnvironmentPullRequestEntry) => void) {
164 const runAction = useAtomCommand(pullRequestEnvironment.runAction, { reportFailure: false });
165 const pending = useRef(new Set<string>());
166 const [closingKeys, setClosingKeys] = useState<ReadonlySet<string>>(() => new Set());
167 const close = async (entries: readonly EnvironmentPullRequestEntry[]) => {
168 const batch = entries.filter((entry) => {
169 const key = pullRequestEntryKey(entry);
170 if (entry.state !== "open" || pending.current.has(key)) return false;
171 pending.current.add(key);
172 return true;
173 });
174 if (batch.length === 0) return;
175 setClosingKeys(new Set(pending.current));
176 const failures: string[] = [];
177 const outcomes = await Promise.all(
178 batch.map(async (entry) => {
179 const result = await runAction({
180 environmentId: entry.environmentId,
181 input: {
182 projectId: entry.projectId,
183 host: entry.host,
184 repository: entry.repository,
185 number: entry.number,
186 action: "close",
187 },
188 });
189 pending.current.delete(pullRequestEntryKey(entry));
190 setClosingKeys(new Set(pending.current));
191 if (result._tag === "Failure") {
192 failures.push(
193 `#${entry.number}: ${readableFailure(squashAtomCommandFailure(result), ACTION_FAILURE_HINTS.close)}`,
194 );
195 return;
196 }
197 onClosed(entry);
198 return true;
199 }),
200 );
201 const closed = outcomes.filter(Boolean).length;
202 toastManager.add({
203 type: failures.length > 0 ? "error" : "success",
204 title:
205 failures.length > 0
206 ? `Closed ${closed} of ${batch.length} pull requests`
207 : `Closed ${closed} pull request${closed === 1 ? "" : "s"}`,
208 ...(failures.length > 0 ? { description: failures.slice(0, 3).join("\n") } : {}),
209 });
210 };
211 return { close, closingKeys };
212}
213
214export interface PullRequestThreadTask {
215 prompt: string;
216 reviewComments?: ReadonlyArray<ReviewCommentContext>;
217}
218
219export type PullRequestHandoffDetail = Pick<
220 PullRequestDetail,
221 "projectId" | "workspaceRoot" | "url"
222>;
223
224const lastHandoffPromptByDraft = new Map<DraftId, string>();
225
226export function usePullRequestHandoffs({
227 environmentId,
228 detail,
229}: {
230 environmentId: EnvironmentId;
231 detail: PullRequestHandoffDetail | null;
232}) {
233 const newThread = useNewThreadHandler();
234 const prepareThread = usePreparePullRequestThreadAction({
235 environmentId,
236 cwd: detail?.workspaceRoot ?? null,
237 });
238 // One at a time whatever the key: they all check the same pull request out.
239 const [handoff, setHandoff] = useState<string | null>(null);
240
241 /**
242 * Nothing is checked out: asking a question is not a reason to move somebody's working tree
243 * or to make a worktree they did not ask for.
244 */
245 const openThreadWithTask = async (
246 projectRef: ReturnType<typeof scopeProjectRef>,
247 task: PullRequestThreadTask | null,
248 opened?: { draftId: DraftId },
249 ): Promise<{ draftId: DraftId } | null> => {
250 const session =
251 opened ??
252 (await newThread(projectRef).then(
253 (result) => result,
254 () => null,
255 ));
256 if (session === null) return null;
257 const store = useComposerDraftStore.getState();
258 if (task === null) return session;
259 const draft = store.getComposerDraft(session.draftId);
260 const existingComments = draft?.reviewComments ?? [];
261 const prompt = handoffPrompt(
262 {
263 prompt: draft?.prompt ?? "",
264 lastHandoffPrompt: lastHandoffPromptByDraft.get(session.draftId),
265 },
266 task.prompt,
267 );
268 // Remember the hand-off's own contribution, not the merged prompt: only that sentence is
269 // this session's to take back next time, and the reader's text around it is not.
270 lastHandoffPromptByDraft.set(session.draftId, task.prompt);
271 store.setPrompt(session.draftId, prompt);
272 store.setReviewComments(
273 session.draftId,
274 handoffReviewComments(existingComments, task.reviewComments ?? []),
275 );
276 return session;
277 };
278
279 const startAsk = async (kind: string, task: PullRequestThreadTask) => {
280 if (!detail || handoff !== null) return;
281 setHandoff(kind);
282 const projectRef = scopeProjectRef(environmentId, detail.projectId);
283 const opened = await openThreadWithTask(projectRef, task);
284 setHandoff(null);
285 if (opened === null) {
286 toastManager.add({
287 type: "error",
288 title: "Could not open a thread",
289 description: "Try again from the project, or open a thread first.",
290 });
291 return;
292 }
293 toastManager.add({
294 type: "success",
295 title: "Asked in a thread",
296 description:
297 task.prompt.length > 0
298 ? "The question is in the composer — read it over, then send."
299 : "The pull request is in the composer — type your question, then send.",
300 });
301 };
302
303 const startHandoff = async (
304 kind: string,
305 task: PullRequestThreadTask | null,
306 mode: "worktree" | "local" = "worktree",
307 ) => {
308 if (!detail || handoff !== null) return;
309 setHandoff(kind);
310 // It carries no timeout of its own: a loading toast never expires, and an explicit one
311 // would survive the update and pin the result on screen.
312 const toastId = toastManager.add({
313 type: "loading",
314 title: "Preparing the pull request checkout...",
315 });
316 const projectRef = scopeProjectRef(environmentId, detail.projectId);
317 // The thread is opened before the checkout rather than after it, because the project's setup
318 // script only runs for a checkout that knows which thread it is for — and a worktree with no
319 // dependencies installed is not something anyone can test.
320 const opened = await newThread(projectRef).then(
321 (session) => session,
322 () => null,
323 );
324 if (opened === null) {
325 setHandoff(null);
326 toastManager.update(toastId, {
327 type: "error",
328 title: "Could not open a thread for the checkout",
329 description: "Try again from the project, or open a thread first.",
330 });
331 return;
332 }
333 const prepared = await prepareThread.run({
334 reference: detail.url,
335 mode,
336 threadId: opened.threadId,
337 });
338 if (prepared._tag === "Failure") {
339 setHandoff(null);
340 const detailMessage =
341 prepareThread.error instanceof Error ? prepareThread.error.message : null;
342 toastManager.update(toastId, {
343 type: "error",
344 title: "Could not prepare the pull request checkout",
345 ...(detailMessage ? { description: detailMessage } : {}),
346 });
347 return;
348 }
349 const pointed = await newThread(projectRef, {
350 branch: prepared.value.branch,
351 worktreePath: prepared.value.worktreePath,
352 envMode: prepared.value.worktreePath === null ? "local" : "worktree",
353 }).then(
354 (session) => session !== null,
355 () => false,
356 );
357 if (!pointed) {
358 setHandoff(null);
359 toastManager.update(toastId, {
360 type: "error",
361 title: "Checked out, but the thread stayed where it was",
362 description: `The checkout is ready on \`${prepared.value.branch}\`. Point a thread at it from the branch picker, then ask again.`,
363 });
364 return;
365 }
366 setHandoff(null);
367 const staleCheckoutToast = {
368 type: "warning",
369 title: "Checked out, but not on the latest commits",
370 description:
371 "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.",
372 } as const;
373 if (task === null) {
374 toastManager.update(
375 toastId,
376 prepared.value.isOnPullRequestHead
377 ? {
378 type: "success",
379 title: mode === "local" ? "Checked out here" : "Checked out",
380 description:
381 mode === "local"
382 ? "This repository is on the pull request's branch, with a thread open on it."
383 : "The pull request is in its own worktree, with a thread open on it.",
384 }
385 : staleCheckoutToast,
386 );
387 return;
388 }
389 await openThreadWithTask(projectRef, task, opened);
390 toastManager.update(
391 toastId,
392 prepared.value.isOnPullRequestHead
393 ? {
394 type: "success",
395 title: "Checkout ready",
396 description: "The task is in the composer — read it over, then send.",
397 }
398 : staleCheckoutToast,
399 );
400 };
401
402 return { handoff, startAsk, startHandoff };
403}