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

ThreadDetailsPrRow.tsx

669 lines23.7 KB

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