Open History to see the last commit
1import { useAtomCommand } from "~/state/use-atom-command";
2import { scopeProjectRef } from "@t3tools/client-runtime/environment";
3import {
4 isAtomCommandInterrupted,
5 squashAtomCommandFailure,
6} from "@t3tools/client-runtime/state/runtime";
7import type {
8 EnvironmentId,
9 ProjectId,
10 PullRequestAction,
11 PullRequestDetail,
12 PullRequestMergeMethod,
13 PullRequestRef,
14} from "@t3tools/contracts";
15import { useRef, useState } from "react";
16import {
17 capitalizeTerm,
18 sourceControlClients,
19 type ChangeRequestTerminology,
20} from "@t3tools/client-runtime/source-control-clients";
21import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
22import { useClientSettings, useEnvironmentSettings } from "~/hooks/useSettings";
23import {
24 deriveLogicalProjectKeyFromSettings,
25 derivePhysicalProjectKey,
26 selectProjectGroupingSettings,
27} from "@t3tools/client-runtime/state/project-grouping";
28import { buildPhysicalToLogicalProjectKeyMap } from "~/sidebarProjectGrouping";
29import { useProjects } from "~/state/entities";
30import { usePrimaryEnvironmentId } from "~/state/environments";
31
32import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
33import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
34import { usePreparePullRequestThreadAction } from "~/state/sourceControlActions";
35import type { ReviewCommentContext } from "~/reviewCommentContext";
36import { pullRequestEnvironment } from "~/state/pullRequests";
37
38import { toastManager } from "../ui/toast";
39import { offHeadPullRequestCheckoutToast } from "./pullRequestCheckoutToast";
40import {
41 checkoutFailureDescription,
42 handoffPrompt,
43 handoffReviewComments,
44 readableFailure,
45} from "./pullRequestDetail.logic";
46import { pullRequestEntryKey, type EnvironmentPullRequestEntry } from "./pullRequestList.logic";
47
48export function usePullRequestDefaultMergeMethodResolver(
49 environmentId: EnvironmentId,
50 projectId: ProjectId | null,
51) {
52 const projectDefault = useEnvironmentSettings(
53 environmentId,
54 (settings) => resolveProjectSettings(settings, projectId).settings.pullRequestMergeMethod,
55 );
56 const legacyOverrides = useClientSettings((settings) => settings.pullRequestMergeMethodOverrides);
57 const grouping = useClientSettings(selectProjectGroupingSettings);
58 const projects = useProjects();
59 const primaryEnvironmentId = usePrimaryEnvironmentId();
60 return () => {
61 if (projectDefault != null) return projectDefault;
62 if (Object.keys(legacyOverrides).length === 0) return undefined;
63 const project = projects.find(
64 (candidate) => candidate.environmentId === environmentId && candidate.id === projectId,
65 );
66 if (!project) return undefined;
67 const key =
68 buildPhysicalToLogicalProjectKeyMap({
69 projects,
70 settings: grouping,
71 primaryEnvironmentId,
72 }).get(derivePhysicalProjectKey(project)) ??
73 deriveLogicalProjectKeyFromSettings(project, grouping);
74 return legacyOverrides[key];
75 };
76}
77
78const actionSuccessLabels = (term: string): Record<PullRequestAction, string> => ({
79 merge: "Merge requested",
80 ready: "Marked ready for review",
81 draft: "Converted to draft",
82 close: `${capitalizeTerm(term)} closed`,
83 reopen: `${capitalizeTerm(term)} reopened`,
84 "update-branch": "Branch updated with the base branch",
85 "enable-auto-merge": "Auto-merge enabled",
86 "disable-auto-merge": "Auto-merge disabled",
87 revert: `Revert ${term} opened`,
88 "delete-branch": "Branch deleted",
89 "approve-workflows": "Workflows approved",
90});
91
92const actionFailureLabels = (term: string): Record<PullRequestAction, string> => ({
93 merge: `Could not merge this ${term}`,
94 ready: "Could not mark this ready for review",
95 draft: "Could not convert this to a draft",
96 close: `Could not close this ${term}`,
97 reopen: `Could not reopen this ${term}`,
98 "update-branch": "Could not update this branch",
99 "enable-auto-merge": "Could not enable auto-merge",
100 "disable-auto-merge": "Could not disable auto-merge",
101 revert: `Could not open a revert ${term}`,
102 "delete-branch": "Could not delete this branch",
103 "approve-workflows": "Could not approve workflows",
104});
105
106const actionFailureHints = (term: string): Record<PullRequestAction, string> => ({
107 merge:
108 "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.",
109 ready: "The host refused it. Check that you have write access to this repository.",
110 draft: "The host refused it. Check that you have write access to this repository.",
111 close: "The host refused it. Check that you have write access, or that you opened it.",
112 reopen:
113 "The host refused it. Check that you have write access, and that the branch still exists.",
114 "update-branch":
115 "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.",
116 "enable-auto-merge":
117 "The host refused it. Check that auto-merge is enabled for this repository and that you have write access.",
118 "disable-auto-merge": "The host refused it. Check that you have write access to this repository.",
119 revert: `The host refused it. Check that you have write access and that this ${term} was merged on the host.`,
120 "delete-branch":
121 "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.",
122 "approve-workflows":
123 "The host refused it. Check that you have Actions write access and that these workflow runs are still awaiting approval.",
124});
125
126export function usePullRequestActionRunner({
127 environmentId,
128 reference,
129 terminology,
130 onSuccess,
131 resolveMergeMethod,
132}: {
133 environmentId: EnvironmentId;
134 reference: PullRequestRef | null;
135 terminology: ChangeRequestTerminology;
136 onSuccess?: (action: PullRequestAction) => void;
137 /** Resolve repository settings on click to avoid per-row reads. */
138 resolveMergeMethod?: (detail: PullRequestDetail) => PullRequestMergeMethod;
139}) {
140 const runAction = useAtomCommand(pullRequestEnvironment.runAction, {
141 reportFailure: false,
142 });
143 const pendingRef = useRef(new Set<string>());
144 const [pendingKeys, setPendingKeys] = useState<ReadonlySet<string>>(() => new Set());
145 const actionKey =
146 reference === null
147 ? null
148 : JSON.stringify([
149 environmentId,
150 reference.host ?? null,
151 reference.repository,
152 reference.number,
153 ]);
154 const actionPending = actionKey !== null && pendingKeys.has(actionKey);
155
156 const perform = async (action: PullRequestAction, method?: PullRequestMergeMethod) => {
157 if (actionKey === null || reference === null || pendingRef.current.has(actionKey)) return;
158 pendingRef.current.add(actionKey);
159 setPendingKeys(new Set(pendingRef.current));
160 const result = await runAction({
161 environmentId,
162 input: {
163 ...reference,
164 action,
165 ...(method ? { mergeMethod: method } : resolveMergeMethod ? { resolveMergeMethod } : {}),
166 },
167 });
168 pendingRef.current.delete(actionKey);
169 setPendingKeys(new Set(pendingRef.current));
170 if (result._tag === "Failure") {
171 toastManager.add({
172 type: "error",
173 title: actionFailureLabels(terminology.singular)[action],
174 description: readableFailure(
175 squashAtomCommandFailure(result),
176 actionFailureHints(terminology.singular)[action],
177 ),
178 });
179 return;
180 }
181 toastManager.add({ type: "success", title: actionSuccessLabels(terminology.singular)[action] });
182 onSuccess?.(action);
183 };
184
185 return { actionPending, perform };
186}
187
188export function usePullRequestCloseBatch(onClosed: (entry: EnvironmentPullRequestEntry) => void) {
189 const runAction = useAtomCommand(pullRequestEnvironment.runAction, { reportFailure: false });
190 const pending = useRef(new Set<string>());
191 const [closingKeys, setClosingKeys] = useState<ReadonlySet<string>>(() => new Set());
192 const close = async (entries: readonly EnvironmentPullRequestEntry[]) => {
193 const batch = entries.filter((entry) => {
194 const key = pullRequestEntryKey(entry);
195 if (entry.state !== "open" || pending.current.has(key)) return false;
196 pending.current.add(key);
197 return true;
198 });
199 if (batch.length === 0) return;
200 setClosingKeys(new Set(pending.current));
201 const failures: string[] = [];
202 const outcomes = await Promise.all(
203 batch.map(async (entry) => {
204 const result = await runAction({
205 environmentId: entry.environmentId,
206 input: {
207 projectId: entry.projectId,
208 host: entry.host,
209 repository: entry.repository,
210 number: entry.number,
211 action: "close",
212 },
213 });
214 pending.current.delete(pullRequestEntryKey(entry));
215 setClosingKeys(new Set(pending.current));
216 if (result._tag === "Failure") {
217 failures.push(
218 `#${entry.number}: ${readableFailure(squashAtomCommandFailure(result), actionFailureHints(sourceControlClients.get(entry.provider).changeRequest.singular).close)}`,
219 );
220 return;
221 }
222 onClosed(entry);
223 return true;
224 }),
225 );
226 const closed = outcomes.filter(Boolean).length;
227 toastManager.add({
228 type: failures.length > 0 ? "error" : "success",
229 title:
230 failures.length > 0
231 ? `Closed ${closed} of ${batch.length} pull requests`
232 : `Closed ${closed} pull request${closed === 1 ? "" : "s"}`,
233 ...(failures.length > 0 ? { description: failures.slice(0, 3).join("\n") } : {}),
234 });
235 };
236 return { close, closingKeys };
237}
238
239export interface PullRequestThreadTask {
240 prompt: string;
241 reviewComments?: ReadonlyArray<ReviewCommentContext>;
242}
243
244export type PullRequestHandoffDetail = Pick<
245 PullRequestDetail,
246 "projectId" | "workspaceRoot" | "url"
247>;
248
249const lastHandoffPromptByDraft = new Map<DraftId, string>();
250
251export function usePullRequestHandoffs({
252 environmentId,
253 detail,
254}: {
255 environmentId: EnvironmentId;
256 detail: PullRequestHandoffDetail | null;
257}) {
258 const newThread = useNewThreadHandler();
259 const prepareThread = usePreparePullRequestThreadAction({
260 environmentId,
261 cwd: detail?.workspaceRoot ?? null,
262 });
263 // Serialize all handoffs because they check out the same pull request.
264 const [handoff, setHandoff] = useState<string | null>(null);
265 // Prompt links hand over a URL alone, so the URL is what names the host.
266 const terminology = (
267 (detail && sourceControlClients.findByChangeRequestUrl(detail.url)) ||
268 sourceControlClients.get(undefined)
269 ).changeRequest;
270
271 // Questions must not change checkouts or create worktrees.
272 const openThreadWithTask = async (
273 projectRef: ReturnType<typeof scopeProjectRef>,
274 task: PullRequestThreadTask | null,
275 opened?: { draftId: DraftId },
276 ): Promise<{ draftId: DraftId } | null> => {
277 const session =
278 opened ??
279 (await newThread(projectRef).then(
280 (result) => result,
281 () => null,
282 ));
283 if (session === null) return null;
284 const store = useComposerDraftStore.getState();
285 if (task === null) return session;
286 const draft = store.getComposerDraft(session.draftId);
287 const existingComments = draft?.reviewComments ?? [];
288 const prompt = handoffPrompt(
289 {
290 prompt: draft?.prompt ?? "",
291 lastHandoffPrompt: lastHandoffPromptByDraft.get(session.draftId),
292 },
293 task.prompt,
294 );
295 // Track only the handoff contribution so later handoffs preserve user text.
296 lastHandoffPromptByDraft.set(session.draftId, task.prompt);
297 store.setPrompt(session.draftId, prompt);
298 store.setReviewComments(
299 session.draftId,
300 handoffReviewComments(existingComments, task.reviewComments ?? []),
301 );
302 return session;
303 };
304
305 const startAsk = async (kind: string, task: PullRequestThreadTask) => {
306 if (!detail || handoff !== null) return;
307 setHandoff(kind);
308 const projectRef = scopeProjectRef(environmentId, detail.projectId);
309 const opened = await openThreadWithTask(projectRef, task);
310 setHandoff(null);
311 if (opened === null) {
312 toastManager.add({
313 type: "error",
314 title: "Could not open a thread",
315 description: "Try again from the project, or open a thread first.",
316 });
317 return;
318 }
319 toastManager.add({
320 type: "success",
321 title: "Asked in a thread",
322 description:
323 task.prompt.length > 0
324 ? "The question is in the composer. Read it over, then send."
325 : `The ${terminology.singular} is in the composer. Type your question, then send.`,
326 });
327 };
328
329 const startHandoff = async (
330 kind: string,
331 task: PullRequestThreadTask | null,
332 mode: "worktree" | "local" = "worktree",
333 ) => {
334 if (!detail || handoff !== null) return;
335 setHandoff(kind);
336 // Explicit timeouts survive toast updates and would pin the result after loading.
337 const toastId = toastManager.add({
338 type: "loading",
339 title: `Preparing the ${terminology.singular} checkout...`,
340 });
341 const projectRef = scopeProjectRef(environmentId, detail.projectId);
342 // Checkout setup requires the thread to exist first.
343 const opened = await newThread(projectRef).then(
344 (session) => session,
345 () => null,
346 );
347 if (opened === null) {
348 setHandoff(null);
349 toastManager.update(toastId, {
350 type: "error",
351 title: "Could not open a thread for the checkout",
352 description: "Try again from the project, or open a thread first.",
353 });
354 return;
355 }
356 const prepared = await prepareThread.run({
357 reference: detail.url,
358 mode,
359 threadId: opened.threadId,
360 });
361 if (prepared._tag === "Failure") {
362 setHandoff(null);
363 toastManager.update(toastId, {
364 type: "error",
365 title: `Could not prepare the ${terminology.singular} checkout`,
366 description: checkoutFailureDescription(
367 isAtomCommandInterrupted(prepared) ? undefined : squashAtomCommandFailure(prepared),
368 ),
369 });
370 return;
371 }
372 const pointed = await newThread(projectRef, {
373 branch: prepared.value.branch,
374 worktreePath: prepared.value.worktreePath,
375 envMode: prepared.value.worktreePath === null ? "local" : "worktree",
376 }).then(
377 (session) => session !== null,
378 () => false,
379 );
380 if (!pointed) {
381 setHandoff(null);
382 toastManager.update(toastId, {
383 type: "error",
384 title: "Checked out, but the thread stayed where it was",
385 description: `The checkout is ready on \`${prepared.value.branch}\`. Point a thread at it from the branch picker, then ask again.`,
386 });
387 return;
388 }
389 setHandoff(null);
390 if (task === null) {
391 toastManager.update(
392 toastId,
393 prepared.value.isOnPullRequestHead
394 ? {
395 type: "success",
396 title: mode === "local" ? "Checked out here" : "Checked out",
397 description:
398 mode === "local"
399 ? `This repository is on the ${terminology.singular}'s branch, with a thread open on it.`
400 : `The ${terminology.singular} is in its own worktree, with a thread open on it.`,
401 }
402 : offHeadPullRequestCheckoutToast(terminology),
403 );
404 return;
405 }
406 await openThreadWithTask(projectRef, task, opened);
407 toastManager.update(
408 toastId,
409 prepared.value.isOnPullRequestHead
410 ? {
411 type: "success",
412 title: "Checkout ready",
413 description: "The task is in the composer. Read it over, then send.",
414 }
415 : offHeadPullRequestCheckoutToast(terminology),
416 );
417 };
418
419 return { handoff, startAsk, startHandoff };
420}