@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 555 lines 19.1 KB
Raw
1 import { useAtomCommand } from "~/state/use-atom-command";
2 import { scopeProjectRef } from "@t3tools/client-runtime/environment";
3 import {
4 isAtomCommandInterrupted,
5 squashAtomCommandFailure,
6 } from "@t3tools/client-runtime/state/runtime";
7 import type {
8 EnvironmentId,
9 ProjectId,
10 PullRequestAction,
11 PullRequestDetail,
12 PullRequestMergeMethod,
13 PullRequestRef,
14 PullRequestSummary,
15 ScopedThreadRef,
16 } from "@t3tools/contracts";
17 import { msg } from "gt-react";
18 import { useRef, useState } from "react";
19 import {
20 sourceControlClients,
21 type ChangeRequestTerminology,
22 } from "@t3tools/client-runtime/source-control-clients";
23 import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
24 import { useClientSettings, useEnvironmentSettings } from "~/hooks/useSettings";
25 import {
26 deriveLogicalProjectKeyFromSettings,
27 derivePhysicalProjectKey,
28 selectProjectGroupingSettings,
29 } from "@t3tools/client-runtime/state/project-grouping";
30 import { buildPhysicalToLogicalProjectKeyMap } from "~/sidebarProjectGrouping";
31 import { useProjects } from "~/state/entities";
32 import { usePrimaryEnvironmentId } from "~/state/environments";
33
34 import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
35 import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
36 import { usePreparePullRequestThreadAction } from "~/state/sourceControlActions";
37 import type { ReviewCommentContext } from "~/reviewCommentContext";
38 import { pullRequestEnvironment } from "~/state/pullRequests";
39
40 import { m } from "~/i18n/messages";
41
42 import { toastManager } from "../ui/toast";
43 import { offHeadPullRequestCheckoutToast } from "./pullRequestCheckoutToast";
44 import {
45 checkoutFailureDescription,
46 appendHandoff,
47 readableFailure,
48 } from "./pullRequestDetail.logic";
49 import { pullRequestEntryKey, type EnvironmentPullRequestEntry } from "./pullRequestList.logic";
50
51 import { changeRequestTermKind, type ChangeRequestTermKind } from "./changeRequestTerm";
52
53 export function usePullRequestDefaultMergeMethodResolver(
54 environmentId: EnvironmentId,
55 projectId: ProjectId | null,
56 ) {
57 const projectDefault = useEnvironmentSettings(
58 environmentId,
59 (settings) => resolveProjectSettings(settings, projectId).settings.pullRequestMergeMethod,
60 );
61 const legacyOverrides = useClientSettings((settings) => settings.pullRequestMergeMethodOverrides);
62 const grouping = useClientSettings(selectProjectGroupingSettings);
63 const projects = useProjects();
64 const primaryEnvironmentId = usePrimaryEnvironmentId();
65 return () => {
66 if (projectDefault != null) return projectDefault;
67 if (Object.keys(legacyOverrides).length === 0) return undefined;
68 const project = projects.find(
69 (candidate) => candidate.environmentId === environmentId && candidate.id === projectId,
70 );
71 if (!project) return undefined;
72 const key =
73 buildPhysicalToLogicalProjectKeyMap({
74 projects,
75 settings: grouping,
76 primaryEnvironmentId,
77 }).get(derivePhysicalProjectKey(project)) ??
78 deriveLogicalProjectKeyFromSettings(project, grouping);
79 return legacyOverrides[key];
80 };
81 }
82
83 const actionSuccessLabels = (term: ChangeRequestTermKind): Record<PullRequestAction, string> => ({
84 merge: m(msg("Merge requested")),
85 ready: m(msg("Marked ready for review")),
86 draft: m(msg("Converted to draft")),
87 close: m(
88 msg("{term, select, mr {Merge request} cr {Change request} other {Pull request}} closed", {
89 term,
90 }),
91 ),
92 reopen: m(
93 msg("{term, select, mr {Merge request} cr {Change request} other {Pull request}} reopened", {
94 term,
95 }),
96 ),
97 "update-branch": m(msg("Branch updated with the base branch")),
98 "enable-auto-merge": m(msg("Auto-merge enabled")),
99 "disable-auto-merge": m(msg("Auto-merge disabled")),
100 revert: m(
101 msg(
102 "Revert {term, select, mr {merge request} cr {change request} other {pull request}} opened",
103 { term },
104 ),
105 ),
106 "delete-branch": m(msg("Branch deleted")),
107 "approve-workflows": m(msg("Workflows approved")),
108 });
109
110 const actionFailureLabels = (term: ChangeRequestTermKind): Record<PullRequestAction, string> => ({
111 merge: m(
112 msg(
113 "Could not merge this {term, select, mr {merge request} cr {change request} other {pull request}}",
114 { term },
115 ),
116 ),
117 ready: m(msg("Could not mark this ready for review")),
118 draft: m(msg("Could not convert this to a draft")),
119 close: m(
120 msg(
121 "Could not close this {term, select, mr {merge request} cr {change request} other {pull request}}",
122 { term },
123 ),
124 ),
125 reopen: m(
126 msg(
127 "Could not reopen this {term, select, mr {merge request} cr {change request} other {pull request}}",
128 { term },
129 ),
130 ),
131 "update-branch": m(msg("Could not update this branch")),
132 "enable-auto-merge": m(msg("Could not enable auto-merge")),
133 "disable-auto-merge": m(msg("Could not disable auto-merge")),
134 revert: m(
135 msg(
136 "Could not open a revert {term, select, mr {merge request} cr {change request} other {pull request}}",
137 { term },
138 ),
139 ),
140 "delete-branch": m(msg("Could not delete this branch")),
141 "approve-workflows": m(msg("Could not approve workflows")),
142 });
143
144 const actionFailureHints = (term: ChangeRequestTermKind): Record<PullRequestAction, string> => ({
145 merge: m(
146 msg(
147 "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.",
148 ),
149 ),
150 ready: m(msg("The host refused it. Check that you have write access to this repository.")),
151 draft: m(msg("The host refused it. Check that you have write access to this repository.")),
152 close: m(msg("The host refused it. Check that you have write access, or that you opened it.")),
153 reopen: m(
154 msg("The host refused it. Check that you have write access, and that the branch still exists."),
155 ),
156 "update-branch": m(
157 msg(
158 "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.",
159 ),
160 ),
161 "enable-auto-merge": m(
162 msg(
163 "The host refused it. Check that auto-merge is enabled for this repository and that you have write access.",
164 ),
165 ),
166 "disable-auto-merge": m(
167 msg("The host refused it. Check that you have write access to this repository."),
168 ),
169 revert: m(
170 msg(
171 "The host refused it. Check that you have write access and that this {term, select, mr {merge request} cr {change request} other {pull request}} was merged on the host.",
172 { term },
173 ),
174 ),
175 "delete-branch": m(
176 msg(
177 "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.",
178 ),
179 ),
180 "approve-workflows": m(
181 msg(
182 "The host refused it. Check that you have Actions write access and that these workflow runs are still awaiting approval.",
183 ),
184 ),
185 });
186
187 export function usePullRequestActionRunner({
188 environmentId,
189 reference,
190 terminology,
191 onSuccess,
192 resolveMergeMethod,
193 }: {
194 environmentId: EnvironmentId;
195 reference: PullRequestRef | null;
196 terminology: ChangeRequestTerminology;
197 onSuccess?: (action: PullRequestAction, reply: PullRequestSummary | undefined) => void;
198 /** Resolve repository settings on click to avoid per-row reads. */
199 resolveMergeMethod?: (detail: PullRequestDetail) => PullRequestMergeMethod;
200 }) {
201 const runAction = useAtomCommand(pullRequestEnvironment.runAction, {
202 reportFailure: false,
203 });
204 const pendingRef = useRef(new Map<string, PullRequestAction>());
205 const [pendingActions, setPendingActions] = useState<ReadonlyMap<string, PullRequestAction>>(
206 () => new Map(),
207 );
208 const actionKey =
209 reference === null
210 ? null
211 : JSON.stringify([
212 environmentId,
213 reference.projectId,
214 reference.host ?? null,
215 reference.repository,
216 reference.number,
217 ]);
218 const pendingAction = actionKey === null ? null : (pendingActions.get(actionKey) ?? null);
219 const actionPending = pendingAction !== null;
220
221 const perform = async (action: PullRequestAction, method?: PullRequestMergeMethod) => {
222 if (actionKey === null || reference === null || pendingRef.current.has(actionKey)) return;
223 pendingRef.current.set(actionKey, action);
224 setPendingActions(new Map(pendingRef.current));
225 const result = await runAction({
226 environmentId,
227 input: {
228 ...reference,
229 action,
230 ...(method ? { mergeMethod: method } : resolveMergeMethod ? { resolveMergeMethod } : {}),
231 },
232 });
233 pendingRef.current.delete(actionKey);
234 setPendingActions(new Map(pendingRef.current));
235 if (result._tag === "Failure") {
236 toastManager.add({
237 type: "error",
238 title: actionFailureLabels(changeRequestTermKind(terminology))[action],
239 description: readableFailure(
240 squashAtomCommandFailure(result),
241 actionFailureHints(changeRequestTermKind(terminology))[action],
242 ),
243 });
244 return;
245 }
246 toastManager.add({
247 type: "success",
248 title: actionSuccessLabels(changeRequestTermKind(terminology))[action],
249 });
250 onSuccess?.(action, result.value);
251 };
252
253 return { actionPending, pendingAction, perform };
254 }
255
256 export function usePullRequestCloseBatch(
257 onClosed: (entry: EnvironmentPullRequestEntry, reply: PullRequestSummary | undefined) => void,
258 ) {
259 const runAction = useAtomCommand(pullRequestEnvironment.runAction, { reportFailure: false });
260 const pending = useRef(new Set<string>());
261 const [closingKeys, setClosingKeys] = useState<ReadonlySet<string>>(() => new Set());
262 const close = async (entries: readonly EnvironmentPullRequestEntry[]) => {
263 const batch = entries.filter((entry) => {
264 const key = pullRequestEntryKey(entry);
265 if (entry.state !== "open" || pending.current.has(key)) return false;
266 pending.current.add(key);
267 return true;
268 });
269 if (batch.length === 0) return;
270 setClosingKeys(new Set(pending.current));
271 const failures: string[] = [];
272 const outcomes = await Promise.all(
273 batch.map(async (entry) => {
274 const result = await runAction({
275 environmentId: entry.environmentId,
276 input: {
277 projectId: entry.projectId,
278 host: entry.host,
279 repository: entry.repository,
280 number: entry.number,
281 action: "close",
282 },
283 });
284 pending.current.delete(pullRequestEntryKey(entry));
285 setClosingKeys(new Set(pending.current));
286 if (result._tag === "Failure") {
287 failures.push(
288 `#${entry.number}: ${readableFailure(squashAtomCommandFailure(result), actionFailureHints(changeRequestTermKind(sourceControlClients.get(entry.provider).changeRequest)).close)}`,
289 );
290 return;
291 }
292 onClosed(entry, result.value);
293 return true;
294 }),
295 );
296 const closed = outcomes.filter(Boolean).length;
297 toastManager.add({
298 type: failures.length > 0 ? "error" : "success",
299 title:
300 failures.length > 0
301 ? m(msg("Closed {closed} of {total} pull requests", { closed, total: batch.length }))
302 : m(
303 msg(
304 "{closed, plural, one {Closed {closed} pull request} other {Closed {closed} pull requests}}",
305 { closed },
306 ),
307 ),
308 ...(failures.length > 0 ? { description: failures.slice(0, 3).join("\n") } : {}),
309 });
310 };
311 return { close, closingKeys };
312 }
313
314 export interface PullRequestThreadTask {
315 prompt: string;
316 reviewComments?: ReadonlyArray<ReviewCommentContext>;
317 }
318
319 export function writeHandoffToComposer(
320 target: ScopedThreadRef | DraftId,
321 task: PullRequestThreadTask,
322 ) {
323 const store = useComposerDraftStore.getState();
324 const draft = store.getComposerDraft(target);
325 const next = appendHandoff(
326 { prompt: draft?.prompt ?? "", reviewComments: draft?.reviewComments ?? [] },
327 task,
328 );
329 store.setPrompt(target, next.prompt);
330 store.setReviewComments(target, next.reviewComments);
331 }
332
333 export type PullRequestHandoffDetail = Pick<
334 PullRequestDetail,
335 "projectId" | "workspaceRoot" | "url"
336 >;
337
338 export function usePullRequestHandoffs({
339 environmentId,
340 detail,
341 }: {
342 environmentId: EnvironmentId;
343 detail: PullRequestHandoffDetail | null;
344 }) {
345 const newThread = useNewThreadHandler();
346 const prepareThread = usePreparePullRequestThreadAction({
347 environmentId,
348 cwd: detail?.workspaceRoot ?? null,
349 });
350 // Serialize all handoffs because they check out the same pull request.
351 const [handoff, setHandoff] = useState<string | null>(null);
352 // Prompt links hand over a URL alone, so the URL is what names the host.
353 const terminology = (
354 (detail && sourceControlClients.findByChangeRequestUrl(detail.url)) ||
355 sourceControlClients.get(undefined)
356 ).changeRequest;
357
358 // Questions must not change checkouts or create worktrees.
359 const openThreadWithTask = async (
360 projectRef: ReturnType<typeof scopeProjectRef>,
361 task: PullRequestThreadTask | null,
362 opened?: { draftId: DraftId },
363 ): Promise<{ draftId: DraftId } | null> => {
364 const session =
365 opened ??
366 (await newThread(projectRef).then(
367 (result) => result,
368 () => null,
369 ));
370 if (session === null) return null;
371 if (task === null) return session;
372 writeHandoffToComposer(session.draftId, task);
373 return session;
374 };
375
376 const startAsk = async (kind: string, task: PullRequestThreadTask) => {
377 if (!detail || handoff !== null) return;
378 setHandoff(kind);
379 const projectRef = scopeProjectRef(environmentId, detail.projectId);
380 const opened = await openThreadWithTask(projectRef, task);
381 setHandoff(null);
382 if (opened === null) {
383 toastManager.add({
384 type: "error",
385 title: m(msg("Could not open a thread")),
386 description: m(msg("Try again from the project, or open a thread first.")),
387 });
388 return;
389 }
390 toastManager.add({
391 type: "success",
392 title: m(msg("Asked in a thread")),
393 description:
394 task.prompt.length > 0
395 ? m(msg("The question is in the composer. Read it over, then send."))
396 : m(
397 msg(
398 "The {term, select, mr {merge request} cr {change request} other {pull request}} is in the composer. Type your question, then send.",
399 {
400 term: changeRequestTermKind(terminology),
401 },
402 ),
403 ),
404 });
405 };
406
407 const startHandoff = async (
408 kind: string,
409 task: PullRequestThreadTask | null,
410 mode: "worktree" | "local" = "worktree",
411 ) => {
412 if (!detail || handoff !== null) return;
413 setHandoff(kind);
414 // Dismissing the loading toast cancels the handoff before it touches a draft.
415 let cancelled = false;
416 // Explicit timeouts survive toast updates and would pin the result after loading.
417 const toastId = toastManager.add({
418 type: "loading",
419 title: m(
420 msg(
421 "Preparing the {term, select, mr {merge request} cr {change request} other {pull request}} checkout...",
422 { term: changeRequestTermKind(terminology) },
423 ),
424 ),
425 data: {
426 onClose: () => {
427 cancelled = true;
428 },
429 },
430 });
431 const projectRef = scopeProjectRef(environmentId, detail.projectId);
432 // Checkout setup requires the thread to exist first.
433 const opened = await newThread(projectRef).then(
434 (session) => session,
435 () => null,
436 );
437 if (cancelled) {
438 setHandoff(null);
439 return;
440 }
441 if (opened === null) {
442 setHandoff(null);
443 toastManager.update(toastId, {
444 type: "error",
445 title: m(msg("Could not open a thread for the checkout")),
446 description: m(msg("Try again from the project, or open a thread first.")),
447 });
448 return;
449 }
450 const prepared = await prepareThread.run({
451 reference: detail.url,
452 mode,
453 threadId: opened.threadId,
454 });
455 if (cancelled) {
456 setHandoff(null);
457 return;
458 }
459 if (prepared._tag === "Failure") {
460 setHandoff(null);
461 toastManager.update(toastId, {
462 type: "error",
463 title: m(
464 msg(
465 "Could not prepare the {term, select, mr {merge request} cr {change request} other {pull request}} checkout",
466 { term: changeRequestTermKind(terminology) },
467 ),
468 ),
469 description: checkoutFailureDescription(
470 isAtomCommandInterrupted(prepared) ? undefined : squashAtomCommandFailure(prepared),
471 ),
472 });
473 return;
474 }
475 const pointed = await newThread(projectRef, {
476 branch: prepared.value.branch,
477 worktreePath: prepared.value.worktreePath,
478 envMode: prepared.value.worktreePath === null ? "local" : "worktree",
479 }).then(
480 (session) => session,
481 () => null,
482 );
483 if (cancelled) {
484 setHandoff(null);
485 return;
486 }
487 if (pointed === null) {
488 setHandoff(null);
489 toastManager.update(toastId, {
490 type: "error",
491 title: m(msg("Checked out, but the thread stayed where it was")),
492 description: m(
493 msg(
494 "The checkout is ready on `{branch}`. Point a thread at it from the branch picker, then ask again.",
495 { branch: prepared.value.branch },
496 ),
497 ),
498 });
499 return;
500 }
501 // The draft carries the pull request until its first send makes it a thread, which links it.
502 useComposerDraftStore.getState().setDraftThreadContext(pointed.draftId, {
503 checkoutPullRequest: {
504 url: prepared.value.pullRequest.url,
505 branch: prepared.value.branch,
506 },
507 });
508 setHandoff(null);
509 if (task === null) {
510 toastManager.update(
511 toastId,
512 prepared.value.isOnPullRequestHead
513 ? {
514 type: "success",
515 title: mode === "local" ? m(msg("Checked out here")) : m(msg("Checked out")),
516 description:
517 mode === "local"
518 ? m(
519 msg(
520 "This repository is on the {term, select, mr {merge request} cr {change request} other {pull request}}'s branch, with a thread open on it.",
521 {
522 term: changeRequestTermKind(terminology),
523 },
524 ),
525 )
526 : m(
527 msg(
528 "The {term, select, mr {merge request} cr {change request} other {pull request}} is in its own worktree, with a thread open on it.",
529 {
530 term: changeRequestTermKind(terminology),
531 },
532 ),
533 ),
534 }
535 : offHeadPullRequestCheckoutToast(terminology),
536 );
537 return;
538 }
539 // The task goes on the checkout draft: if the user typed into `opened` while the
540 // checkout ran, that is no longer the draft the user is looking at.
541 await openThreadWithTask(projectRef, task, pointed);
542 toastManager.update(
543 toastId,
544 prepared.value.isOnPullRequestHead
545 ? {
546 type: "success",
547 title: m(msg("Checkout ready")),
548 description: m(msg("The task is in the composer. Read it over, then send.")),
549 }
550 : offHeadPullRequestCheckoutToast(terminology),
551 );
552 };
553
554 return { handoff, startAsk, startHandoff };
555 }