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

ThreadDetailsPrRow.tsx

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