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

main
tsx 620 lines 22.4 KB
Raw
1 import { resolvePullRequestDetailChecks } from "@t3tools/client-runtime/pull-request-checks";
2 import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
3 import { changeRequestTermKind } from "../pullRequest/changeRequestTerm";
4 import { T, useGT, useMessages, Var } from "gt-react";
5 import { PullRequestChangeBreakdownRows } from "../pullRequest/PullRequestChangeBreakdownStat";
6 import { ThreadDetailsControl } from "./ThreadDetailsControl";
7 import { PullRequestGlyph } from "../pullRequest/pullRequestIcons";
8 import { selectEnvironmentQueryData } from "@t3tools/client-runtime/state/runtime";
9 import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
10 import type { EnvironmentId, ProjectId, PullRequestRef } from "@t3tools/contracts";
11 import {
12 ArrowUpRightIcon,
13 EyeIcon,
14 EyeOffIcon,
15 FileDiffIcon,
16 GitBranchIcon,
17 TriangleAlertIcon,
18 } from "lucide-react";
19 import { AsyncResult } from "effect/reactivity";
20 import { useState, type MouseEvent as ReactMouseEvent } from "react";
21
22 import type { ComposerThreadTarget } from "~/composerDraftStore";
23 import { useLiveRefresh } from "~/hooks/useLiveRefresh";
24 import { usePullRequestChecksRefresh } from "~/hooks/usePullRequestChecksRefresh";
25 import { cn } from "~/lib/utils";
26 import { useServerConfigs } from "~/state/entities";
27 import { pullRequestEnvironment } from "~/state/pullRequests";
28 import { useUiStateStore } from "~/uiStateStore";
29 import {
30 useEnvironmentQueryIsNewer,
31 useEnvironmentQueryRefresh,
32 useEnvironmentQuerySelector,
33 } from "~/state/query";
34
35 import {
36 buildFixFindingsHandoff,
37 buildResolveConflictsPrompt,
38 classifyPullRequestChecks,
39 describePullRequestChecks,
40 isPullRequestConflicting,
41 resolvePullRequestMergeMethod,
42 allowedPullRequestMergeMethods,
43 resolveThreadPanelPullRequestAction,
44 } from "../pullRequest/pullRequestDetail.logic";
45 import { PullRequestChecksPopover } from "../pullRequest/PullRequestChecksPopover";
46 import {
47 pullRequestChecksState,
48 PullRequestCheckStatusIcon,
49 PullRequestDiffStat,
50 resolvePullRequestState,
51 } from "../pullRequest/pullRequestPresentation";
52 import {
53 usePullRequestActionRunner,
54 usePullRequestDefaultMergeMethodResolver,
55 usePullRequestHandoffs,
56 writeHandoffToComposer,
57 type PullRequestThreadTask,
58 } from "../pullRequest/usePullRequestActions";
59 import {
60 ChangeRequestStatusIcon,
61 type PrStatusIndicator,
62 type ThreadPr,
63 } from "../ThreadStatusIndicators";
64 import {
65 AlertDialog,
66 AlertDialogClose,
67 AlertDialogDescription,
68 AlertDialogFooter,
69 AlertDialogHeader,
70 AlertDialogPopup,
71 AlertDialogTitle,
72 } from "../ui/alert-dialog";
73 import { Button } from "../ui/button";
74 import { Spinner } from "../ui/spinner";
75 import { toastManager } from "../ui/toast";
76 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
77 import {
78 THREAD_DETAILS_PANEL_ICON_CLASS,
79 THREAD_DETAILS_PANEL_LABEL_CLASS,
80 THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS,
81 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
82 } from "./threadDetailsPanelStyles";
83
84 // A null checks response is settled; polling cannot find checks.
85 const isSettledWithoutChecks = (result: AsyncResult.AsyncResult<unknown, unknown>) =>
86 result._tag === "Success" && result.value === null;
87
88 export function ThreadDetailsPrRow({
89 environmentId,
90 pr,
91 number,
92 reference: linkedReference,
93 status,
94 project,
95 label,
96 onOpen,
97 onActed,
98 onStopWatching,
99 composerTarget,
100 }: {
101 environmentId: EnvironmentId;
102 pr: ThreadPr;
103 number: number;
104 reference?: Pick<PullRequestRef, "host" | "repository" | "number"> | null;
105 status: PrStatusIndicator | null;
106 project: EnvironmentProject | null;
107 label: string;
108 onOpen: (event: ReactMouseEvent<HTMLElement>) => void;
109 onActed?: () => void;
110 onStopWatching?: (() => void) | undefined;
111 /** Fix and Resolve write here instead of checking the pull request out in a new thread. */
112 composerTarget?: ComposerThreadTarget | undefined;
113 }) {
114 const gt = useGT();
115 const m = useMessages();
116 const serverConfigs = useServerConfigs();
117 const supportsPullRequests = serverConfigs.get(environmentId) !== undefined;
118 const repository = sourceControlClients.repositorySelector(project?.repositoryIdentity);
119 const reference: PullRequestRef | null =
120 supportsPullRequests && project !== null
121 ? linkedReference
122 ? { ...linkedReference, projectId: project.id as ProjectId }
123 : repository !== null
124 ? { projectId: project.id as ProjectId, repository, number }
125 : null
126 : null;
127 const detailAtom =
128 reference === null
129 ? null
130 : pullRequestEnvironment.detail({
131 environmentId,
132 input: { ...reference, allowStale: false },
133 });
134 // Select query parts because polling rebuilds unchanged results.
135 const detailData = useEnvironmentQuerySelector(detailAtom, selectEnvironmentQueryData);
136 const detailQuery = useEnvironmentQueryRefresh(detailAtom);
137 const supportsChecks =
138 serverConfigs.get(environmentId)?.environment.capabilities.pullRequestChecks === true;
139 const checksAtom =
140 supportsChecks && reference !== null && detailData !== null
141 ? pullRequestEnvironment.checks({ environmentId, input: reference })
142 : null;
143 const checksData = useEnvironmentQuerySelector(checksAtom, selectEnvironmentQueryData);
144 const checksSettledEmpty = useEnvironmentQuerySelector(checksAtom, isSettledWithoutChecks);
145 const checksQuery = useEnvironmentQueryRefresh(checksAtom);
146 const checksAreNewer = useEnvironmentQueryIsNewer(checksAtom, detailAtom);
147 const detail = resolvePullRequestDetailChecks(detailData, checksData, checksAreNewer);
148 const terminology = sourceControlClients.get(
149 detail?.provider ?? project?.repositoryIdentity?.provider,
150 ).changeRequest;
151 const term = changeRequestTermKind(terminology);
152 const open = reference !== null && (detail?.state ?? pr?.state) === "open";
153 const refreshKey = `${environmentId}:${project?.id}:${reference?.host}:${reference?.repository}:${number}`;
154 useLiveRefresh(
155 () => {
156 if (!detailQuery.isPending()) detailQuery.refresh();
157 },
158 { enabled: open, key: `workspace-pr:${refreshKey}`, intervalMs: 10 * 60_000 },
159 );
160 usePullRequestChecksRefresh({
161 refresh: () => {
162 if (!checksQuery.isPending() && !detailQuery.isPending()) checksQuery.refresh();
163 },
164 enabled: open && supportsChecks && !checksSettledEmpty,
165 key: `workspace-pr-checks:${refreshKey}`,
166 checks: detail?.checks ?? [],
167 });
168
169 const { actionPending, pendingAction, perform } = usePullRequestActionRunner({
170 environmentId,
171 reference,
172 terminology,
173 onSuccess: () => {
174 checksQuery.refresh();
175 onActed?.();
176 },
177 });
178 const { handoff, startHandoff } = usePullRequestHandoffs({ environmentId, detail });
179 const lastSelectedMergeMethod = useUiStateStore((state) => state.pullRequestMergeMethod);
180 const resolveProjectDefaultMergeMethod = usePullRequestDefaultMergeMethodResolver(
181 environmentId,
182 (project?.id as ProjectId | undefined) ?? null,
183 );
184 const [confirmingMerge, setConfirmingMerge] = useState(false);
185
186 const rowAction =
187 pendingAction === "ready" || pendingAction === "merge"
188 ? pendingAction
189 : resolveThreadPanelPullRequestAction(detail);
190 if (confirmingMerge && rowAction !== "merge") {
191 setConfirmingMerge(false);
192 }
193 const conflicting = isPullRequestConflicting(detail);
194 const checksState = detail === null ? "none" : classifyPullRequestChecks(detail.checks);
195 const checksRollup = detail === null ? null : pullRequestChecksState(detail.checks);
196 const selectedMergeMethod = resolvePullRequestMergeMethod(
197 allowedPullRequestMergeMethods(detail),
198 null,
199 resolveProjectDefaultMergeMethod(),
200 lastSelectedMergeMethod,
201 );
202 const mergeMethodKey =
203 selectedMergeMethod === "fast-forward" ? "fastForward" : selectedMergeMethod;
204
205 const handOff = (kind: "conflicts" | "findings", task: PullRequestThreadTask) => {
206 if (composerTarget === undefined) {
207 void startHandoff(kind, task);
208 return;
209 }
210 writeHandoffToComposer(composerTarget, task);
211 toastManager.add({
212 type: "success",
213 title: gt("Added to the composer"),
214 description: gt("The task is in the composer. Read it over, then send."),
215 });
216 };
217
218 const startResolveConflicts = () => {
219 if (detail === null) return;
220 handOff("conflicts", {
221 prompt: buildResolveConflictsPrompt({
222 number: detail.number,
223 url: detail.url,
224 headBranch: detail.headBranch,
225 baseBranch: detail.baseBranch,
226 inThisThread: composerTarget !== undefined,
227 }),
228 });
229 };
230
231 const startFixChecks = () => {
232 if (detail === null) return;
233 handOff(
234 "findings",
235 buildFixFindingsHandoff({
236 number: detail.number,
237 title: detail.title,
238 url: detail.url,
239 headBranch: detail.headBranch,
240 baseBranch: detail.baseBranch,
241 state: detail.state,
242 isDraft: detail.isDraft,
243 reviewThreads: [],
244 comments: [],
245 checks: detail.checks,
246 commentsTruncated: false,
247 inThisThread: composerTarget !== undefined,
248 }),
249 );
250 };
251
252 const statePresentation =
253 detail === null
254 ? null
255 : resolvePullRequestState(
256 {
257 state: detail.state,
258 isDraft: detail.isDraft,
259 },
260 m,
261 );
262 const icon = statePresentation ? (
263 <statePresentation.Icon
264 aria-hidden
265 className={cn("size-4 shrink-0", statePresentation.toneClassName)}
266 />
267 ) : pr && status ? (
268 <ChangeRequestStatusIcon
269 state={pr.state}
270 className={cn(THREAD_DETAILS_PANEL_ICON_CLASS, status.colorClass)}
271 />
272 ) : (
273 <PullRequestGlyph.pullRequest className={THREAD_DETAILS_PANEL_ICON_CLASS} />
274 );
275
276 const stateLabel = (
277 statePresentation ??
278 (pr ? resolvePullRequestState({ state: pr.state, isDraft: pr.isDraft === true }, m) : null)
279 )?.label.toLowerCase();
280 const title = (detail?.title ?? pr?.title)?.trim();
281 const openAriaLabel =
282 stateLabel && title
283 ? gt(
284 "{term, select, mr {Merge request} cr {Change request} other {Pull request}} #{number}, {state}: {title}",
285 { term, number, state: stateLabel, title },
286 )
287 : stateLabel
288 ? gt(
289 "{term, select, mr {Merge request} cr {Change request} other {Pull request}} #{number}, {state}",
290 { term, number, state: stateLabel },
291 )
292 : title
293 ? gt(
294 "{term, select, mr {Merge request} cr {Change request} other {Pull request}} #{number}: {title}",
295 { term, number, title },
296 )
297 : gt(
298 "{term, select, mr {Merge request} cr {Change request} other {Pull request}} #{number}",
299 { term, number },
300 );
301
302 const rowTooltip =
303 detail === null || statePresentation === null ? (
304 <TooltipPopup side="top">
305 {status?.tooltip ??
306 gt(
307 "{term, select, mr {Merge request} cr {Change request} other {Pull request}} #{number}",
308 {
309 term,
310 number,
311 },
312 )}
313 </TooltipPopup>
314 ) : (
315 <TooltipPopup
316 side="top"
317 align="start"
318 sideOffset={4}
319 variant="glass"
320 className="max-w-80 text-left whitespace-normal"
321 >
322 <div className="flex min-w-0 max-w-80 flex-col gap-2 px-1 py-2">
323 <div className="flex min-w-0 items-baseline gap-1.5 text-xs leading-none">
324 <span className="min-w-0 truncate font-medium text-foreground">{detail.title}</span>
325 <span className="shrink-0 text-muted-foreground">#{detail.number}</span>
326 </div>
327 <div className="grid gap-1.5 pl-0.5 text-xs text-muted-foreground">
328 <div className="flex min-w-0 items-center gap-2">
329 <statePresentation.Icon
330 aria-hidden
331 className={cn("size-3 shrink-0", statePresentation.toneClassName)}
332 />
333 <div className="min-w-0 truncate text-foreground/75">{statePresentation.label}</div>
334 </div>
335 <div className="flex min-w-0 items-center gap-2">
336 <GitBranchIcon className="size-3 shrink-0 stroke-muted-foreground" />
337 <div className="min-w-0 truncate text-foreground/75">
338 {detail.baseBranch} ← {detail.headBranch}
339 </div>
340 </div>
341 {detail.state === "open" && checksState !== "none" ? (
342 <div className="flex min-w-0 items-center gap-2">
343 <PullRequestCheckStatusIcon
344 status={
345 checksState === "failing"
346 ? "failure"
347 : checksState === "pending"
348 ? "pending"
349 : "success"
350 }
351 />
352 <div className="min-w-0 truncate text-foreground/75">
353 {describePullRequestChecks(detail.checks, m)}
354 </div>
355 </div>
356 ) : null}
357 {detail.isDraft && conflicting ? (
358 <div className="flex min-w-0 items-start gap-2 text-destructive">
359 <TriangleAlertIcon aria-hidden className="mt-0.5 size-3 shrink-0 stroke-current" />
360 <div className="min-w-0 flex-1 wrap-break-word">
361 <T>
362 Merge conflicts with <Var>{detail.baseBranch}</Var>
363 </T>
364 </div>
365 </div>
366 ) : null}
367 <div className="flex min-w-0 items-center gap-2">
368 <FileDiffIcon className="size-3 shrink-0 stroke-muted-foreground" />
369 <div className="min-w-0 flex items-baseline gap-1 truncate text-foreground/75">
370 {gt("{count, plural, one {{formatted} file} other {{formatted} files}}", {
371 count: detail.changedFiles,
372 formatted: detail.changedFiles.toLocaleString(),
373 })}
374 <PullRequestDiffStat additions={detail.additions} deletions={detail.deletions} />
375 </div>
376 </div>
377 {reference !== null && (detail.additions > 0 || detail.deletions > 0) ? (
378 <PullRequestChangeBreakdownRows
379 environmentId={environmentId}
380 reference={reference}
381 className="pl-5 text-foreground/75"
382 />
383 ) : null}
384 </div>
385 </div>
386 </TooltipPopup>
387 );
388
389 const newThreadSuffix =
390 composerTarget === undefined ? (
391 <ArrowUpRightIcon aria-hidden className="size-3 shrink-0" />
392 ) : null;
393 const trailingAction =
394 rowAction === "resolve"
395 ? {
396 label: gt("Resolve", { $context: "verb, resolves merge conflicts" }),
397 pendingLabel: gt("Preparing..."),
398 pending: handoff === "conflicts",
399 destructive: true,
400 suffix: newThreadSuffix,
401 tooltip:
402 composerTarget === undefined
403 ? gt("Check the branch out and resolve the conflicts in a new thread")
404 : gt("Resolve the conflicts in this thread"),
405 onClick: startResolveConflicts,
406 }
407 : rowAction === "ready"
408 ? {
409 label: gt("Ready", { $context: "verb, marks a draft pull request ready for review" }),
410 pendingLabel: gt("Marking..."),
411 pending: actionPending,
412 destructive: false,
413 suffix: null,
414 tooltip: gt(
415 "Mark this {term, select, mr {merge request} cr {change request} other {pull request}} as ready for review",
416 { term },
417 ),
418 onClick: () => void perform("ready"),
419 }
420 : rowAction === "fix"
421 ? {
422 label: gt("Fix", { $context: "verb, fixes failing checks" }),
423 pendingLabel: gt("Fix", { $context: "verb, fixes failing checks" }),
424 pending: handoff === "findings",
425 destructive: true,
426 suffix:
427 handoff === "findings" ? (
428 <Spinner size="xs" aria-label={gt("Preparing fix")} />
429 ) : (
430 newThreadSuffix
431 ),
432 tooltip:
433 composerTarget === undefined
434 ? gt("Fix the failing checks in a new thread")
435 : gt("Fix the failing checks in this thread"),
436 onClick: startFixChecks,
437 }
438 : rowAction === "merge"
439 ? {
440 label: gt("Merge", { $context: "verb, merges a pull request" }),
441 pendingLabel: gt("Merging..."),
442 pending: actionPending,
443 destructive: false,
444 suffix: null,
445 tooltip: gt(
446 "Merge this {term, select, mr {merge request} cr {change request} other {pull request}} ({method, select, merge {merge} squash {squash} rebase {rebase} fastForward {fast-forward} other {merge}})",
447 {
448 term,
449 method: mergeMethodKey,
450 },
451 ),
452 onClick: () => setConfirmingMerge(true),
453 }
454 : null;
455
456 const watching =
457 onStopWatching !== undefined && (detail?.state ?? pr?.state ?? "open") === "open";
458 const watchControl = (part: "secondary" | "icon") =>
459 watching ? (
460 <Tooltip>
461 <TooltipTrigger
462 render={
463 <ThreadDetailsControl
464 type="button"
465 variant="ghost"
466 size="sm"
467 part={part}
468 className="group/watch"
469 aria-label={gt("Stop watching #{number}", { number })}
470 onClick={onStopWatching}
471 />
472 }
473 >
474 <EyeIcon
475 aria-hidden
476 className={cn(part === "icon" ? "size-3.5" : "size-4", "group-hover/watch:hidden")}
477 />
478 <EyeOffIcon
479 aria-hidden
480 className={cn(
481 part === "icon" ? "size-3.5" : "size-4",
482 "hidden group-hover/watch:block",
483 )}
484 />
485 </TooltipTrigger>
486 <TooltipPopup side="top">
487 <T>
488 Watching: the agent wakes when checks finish, someone comments, or the branch conflicts.
489 Click to stop.
490 </T>
491 </TooltipPopup>
492 </Tooltip>
493 ) : null;
494
495 // The title row wraps to two lines; a conventional-commit prefix eats most of one line.
496 const openRow = (text: string, part: "row" | "primary", wrap = false) => (
497 <Tooltip>
498 <TooltipTrigger
499 render={
500 <ThreadDetailsControl
501 type="button"
502 variant="ghost"
503 size="sm"
504 part={wrap ? "title" : part}
505 aria-label={openAriaLabel}
506 onClick={onOpen}
507 onAuxClick={onOpen}
508 />
509 }
510 >
511 {icon}
512 <span
513 className={cn(
514 "min-w-0 flex-1 text-left",
515 wrap
516 ? "line-clamp-2 whitespace-normal leading-4.5"
517 : cn("truncate", THREAD_DETAILS_PANEL_LABEL_CLASS),
518 )}
519 >
520 {text}
521 </span>
522 </TooltipTrigger>
523 {rowTooltip}
524 </Tooltip>
525 );
526
527 const showChecks = detail !== null && checksRollup !== null && !conflicting && !detail.isDraft;
528
529 return (
530 <>
531 {detail !== null && (showChecks || trailingAction !== null || watching) ? (
532 <div className="pb-1.5">
533 {openRow(detail.title, "row", true)}
534 <div className="flex h-5 min-w-0 items-center gap-0.5 ps-9 pe-2.5 text-xs text-muted-foreground">
535 <span aria-hidden className="me-1 shrink-0 tabular-nums">
536 #{number}
537 </span>
538 {showChecks && checksRollup !== null ? (
539 <PullRequestChecksPopover
540 checksState={checksRollup}
541 checks={detail.checks}
542 variant="count"
543 render={<ThreadDetailsControl part="meta" className="min-w-0 shrink" />}
544 />
545 ) : null}
546 {watchControl("icon")}
547 <span className="flex-1" />
548 {trailingAction ? (
549 <Tooltip>
550 <TooltipTrigger
551 render={
552 <ThreadDetailsControl
553 type="button"
554 variant="ghost"
555 size="sm"
556 part="meta"
557 tone={trailingAction.destructive ? "destructive" : "primary"}
558 disabled={actionPending || handoff !== null}
559 onClick={trailingAction.onClick}
560 />
561 }
562 >
563 {trailingAction.pending ? trailingAction.pendingLabel : trailingAction.label}
564 {trailingAction.suffix}
565 </TooltipTrigger>
566 <TooltipPopup side="top">{trailingAction.tooltip}</TooltipPopup>
567 </Tooltip>
568 ) : null}
569 </div>
570 </div>
571 ) : watching ? (
572 <div className={THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS}>
573 {openRow(label, "primary")}
574 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
575 {watchControl("secondary")}
576 </div>
577 ) : (
578 openRow(label, "row")
579 )}
580 {rowAction === "merge" ? (
581 <AlertDialog open={confirmingMerge} onOpenChange={(open) => setConfirmingMerge(open)}>
582 <AlertDialogPopup>
583 <AlertDialogHeader>
584 <AlertDialogTitle>
585 {gt(
586 "Merge {term, select, mr {merge request} cr {change request} other {pull request}}?",
587 { term },
588 )}
589 </AlertDialogTitle>
590 <AlertDialogDescription>
591 {gt(
592 "This merges #{number} using {method, select, merge {merge} squash {squash} rebase {rebase} fastForward {fast-forward} other {merge}}.",
593 {
594 number,
595 method: mergeMethodKey,
596 },
597 )}
598 </AlertDialogDescription>
599 </AlertDialogHeader>
600 <AlertDialogFooter>
601 <AlertDialogClose render={<Button variant="outline" size="sm" />}>
602 <T>Cancel</T>
603 </AlertDialogClose>
604 <Button
605 size="sm"
606 disabled={actionPending}
607 onClick={() => {
608 setConfirmingMerge(false);
609 void perform("merge", selectedMergeMethod);
610 }}
611 >
612 <T context="verb, merges a pull request">Merge</T>
613 </Button>
614 </AlertDialogFooter>
615 </AlertDialogPopup>
616 </AlertDialog>
617 ) : null}
618 </>
619 );
620 }