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

ThreadDetailsPrRow.tsx

624 lines22.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 } 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(
290 "{term, select, mr {Merge request} cr {Change request} other {Pull request}} #{number}, {state}: {title}",
291 { term, number, state: stateLabel, title },
292 )
293 : stateLabel
294 ? gt(
295 "{term, select, mr {Merge request} cr {Change request} other {Pull request}} #{number}, {state}",
296 { term, number, state: stateLabel },
297 )
298 : title
299 ? gt(
300 "{term, select, mr {Merge request} cr {Change request} other {Pull request}} #{number}: {title}",
301 { term, number, title },
302 )
303 : gt(
304 "{term, select, mr {Merge request} cr {Change request} other {Pull request}} #{number}",
305 { term, number },
306 );
307​
308 const rowTooltip =
309 detail === null || statePresentation === null ? (
310 <TooltipPopup side="top">
311 {status?.tooltip ??
312 gt(
313 "{term, select, mr {Merge request} cr {Change request} other {Pull request}} #{number}",
314 {
315 term,
316 number,
317 },
318 )}
319 </TooltipPopup>
320 ) : (
321 <TooltipPopup
322 side="top"
323 align="start"
324 sideOffset={4}
325 variant="glass"
326 className="max-w-80 text-left whitespace-normal"
327 >
328 <div className="flex min-w-0 max-w-80 flex-col gap-2 px-1 py-2">
329 <div className="flex min-w-0 items-baseline gap-1.5 text-xs leading-none">
330 <span className="min-w-0 truncate font-medium text-foreground">{detail.title}</span>
331 <span className="shrink-0 text-muted-foreground">#{detail.number}</span>
332 </div>
333 <div className="grid gap-1.5 pl-0.5 text-xs text-muted-foreground">
334 <div className="flex min-w-0 items-center gap-2">
335 <statePresentation.Icon
336 aria-hidden
337 className={cn("size-3 shrink-0", statePresentation.toneClassName)}
338 />
339 <div className="min-w-0 truncate text-foreground/75">{statePresentation.label}</div>
340 </div>
341 <div className="flex min-w-0 items-center gap-2">
342 <GitBranchIcon className="size-3 shrink-0 stroke-muted-foreground" />
343 <div className="min-w-0 truncate text-foreground/75">
344 {detail.baseBranch} ← {detail.headBranch}
345 </div>
346 </div>
347 {detail.state === "open" && checksState !== "none" ? (
348 <div className="flex min-w-0 items-center gap-2">
349 <PullRequestCheckStatusIcon
350 status={
351 checksState === "failing"
352 ? "failure"
353 : checksState === "pending"
354 ? "pending"
355 : "success"
356 }
357 />
358 <div className="min-w-0 truncate text-foreground/75">
359 {describePullRequestChecks(detail.checks, m)}
360 </div>
361 </div>
362 ) : null}
363 {detail.isDraft && conflicting ? (
364 <div className="flex min-w-0 items-start gap-2 text-destructive">
365 <TriangleAlertIcon aria-hidden className="mt-0.5 size-3 shrink-0 stroke-current" />
366 <div className="min-w-0 flex-1 wrap-break-word">
367 <T>
368 Merge conflicts with <Var>{detail.baseBranch}</Var>
369 </T>
370 </div>
371 </div>
372 ) : null}
373 <div className="flex min-w-0 items-center gap-2">
374 <FileDiffIcon className="size-3 shrink-0 stroke-muted-foreground" />
375 <div className="min-w-0 flex items-baseline gap-1 truncate text-foreground/75">
376 {gt("{count, plural, one {{formatted} file} other {{formatted} files}}", {
377 count: detail.changedFiles,
378 formatted: detail.changedFiles.toLocaleString(),
379 })}
380 <PullRequestDiffStat additions={detail.additions} deletions={detail.deletions} />
381 </div>
382 </div>
383 {reference !== null && (detail.additions > 0 || detail.deletions > 0) ? (
384 <PullRequestChangeBreakdownRows
385 environmentId={environmentId}
386 reference={reference}
387 className="pl-5 text-foreground/75"
388 />
389 ) : null}
390 </div>
391 </div>
392 </TooltipPopup>
393 );
394​
395 const newThreadSuffix =
396 composerTarget === undefined ? (
397 <ArrowUpRightIcon aria-hidden className="size-3 shrink-0" />
398 ) : null;
399 const trailingAction =
400 rowAction === "resolve"
401 ? {
402 label: gt("Resolve", { $context: "verb, resolves merge conflicts" }),
403 pendingLabel: gt("Preparing..."),
404 pending: handoff === "conflicts",
405 destructive: true,
406 suffix: newThreadSuffix,
407 tooltip:
408 composerTarget === undefined
409 ? gt("Check the branch out and resolve the conflicts in a new thread")
410 : gt("Resolve the conflicts in this thread"),
411 onClick: startResolveConflicts,
412 }
413 : rowAction === "ready"
414 ? {
415 label: gt("Ready", { $context: "verb, marks a draft pull request ready for review" }),
416 pendingLabel: gt("Marking..."),
417 pending: actionPending,
418 destructive: false,
419 suffix: null,
420 tooltip: gt(
421 "Mark this {term, select, mr {merge request} cr {change request} other {pull request}} as ready for review",
422 { term },
423 ),
424 onClick: () => void perform("ready"),
425 }
426 : rowAction === "fix"
427 ? {
428 label: gt("Fix", { $context: "verb, fixes failing checks" }),
429 pendingLabel: gt("Fix", { $context: "verb, fixes failing checks" }),
430 pending: handoff === "findings",
431 destructive: true,
432 suffix:
433 handoff === "findings" ? (
434 <Spinner size="xs" aria-label={gt("Preparing fix")} />
435 ) : (
436 newThreadSuffix
437 ),
438 tooltip:
439 composerTarget === undefined
440 ? gt("Fix the failing checks in a new thread")
441 : gt("Fix the failing checks in this thread"),
442 onClick: startFixChecks,
443 }
444 : rowAction === "merge"
445 ? {
446 label: gt("Merge", { $context: "verb, merges a pull request" }),
447 pendingLabel: gt("Merging..."),
448 pending: actionPending,
449 destructive: false,
450 suffix: null,
451 tooltip: gt(
452 "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}})",
453 {
454 term,
455 method: mergeMethodKey,
456 },
457 ),
458 onClick: () => {
459 setArmedMergeHead(detail?.headSha);
460 setConfirmingMerge(true);
461 },
462 }
463 : null;
464​
465 const watching =
466 onStopWatching !== undefined && (detail?.state ?? pr?.state ?? "open") === "open";
467 const watchControl = (part: "secondary" | "icon") =>
468 watching ? (
469 <SharedTooltipTrigger
470 render={
471 <ThreadDetailsControl
472 type="button"
473 variant="ghost"
474 size="sm"
475 part={part}
476 className="group/watch"
477 aria-label={gt("Stop watching #{number}", { number })}
478 onClick={onStopWatching}
479 />
480 }
481 label={
482 <>
483 <T>
484 Watching: the agent wakes when checks finish, someone comments, or the branch
485 conflicts. Click to stop.
486 </T>
487 </>
488 }
489 >
490 <EyeIcon
491 aria-hidden
492 className={cn(part === "icon" ? "size-3.5" : "size-4", "group-hover/watch:hidden")}
493 />
494 <EyeOffIcon
495 aria-hidden
496 className={cn(part === "icon" ? "size-3.5" : "size-4", "hidden group-hover/watch:block")}
497 />
498 </SharedTooltipTrigger>
499 ) : null;
500​
501 // The title row wraps to two lines; a conventional-commit prefix eats most of one line.
502 const openRow = (text: string, part: "row" | "primary", wrap = false) => (
503 <Tooltip>
504 <TooltipTrigger
505 render={
506 <ThreadDetailsControl
507 type="button"
508 variant="ghost"
509 size="sm"
510 part={wrap ? "title" : part}
511 aria-label={openAriaLabel}
512 onClick={onOpen}
513 onAuxClick={onOpen}
514 />
515 }
516 >
517 {icon}
518 <span
519 className={cn(
520 "min-w-0 flex-1 text-left",
521 wrap
522 ? "line-clamp-2 whitespace-normal leading-4.5"
523 : cn("truncate", THREAD_DETAILS_PANEL_LABEL_CLASS),
524 )}
525 >
526 {text}
527 </span>
528 </TooltipTrigger>
529 {rowTooltip}
530 </Tooltip>
531 );
532​
533 const showChecks = detail !== null && checksRollup !== null && !conflicting && !detail.isDraft;
534​
535 return (
536 <>
537 {detail !== null && (showChecks || trailingAction !== null || watching) ? (
538 <div className="pb-1.5">
539 {openRow(detail.title, "row", true)}
540 <div className="flex h-5 min-w-0 items-center gap-0.5 ps-9 pe-2.5 text-xs text-muted-foreground">
541 <span aria-hidden className="me-1 shrink-0 tabular-nums">
542 #{number}
543 </span>
544 {showChecks && checksRollup !== null ? (
545 <PullRequestChecksPopover
546 checksState={checksRollup}
547 checks={detail.checks}
548 variant="count"
549 render={<ThreadDetailsControl part="meta" className="min-w-0 shrink" />}
550 />
551 ) : null}
552 {watchControl("icon")}
553 <span className="flex-1" />
554 {trailingAction ? (
555 <SharedTooltipTrigger
556 render={
557 <ThreadDetailsControl
558 type="button"
559 variant="ghost"
560 size="sm"
561 part="meta"
562 tone={trailingAction.destructive ? "destructive" : "primary"}
563 disabled={actionPending || handoff !== null}
564 onClick={trailingAction.onClick}
565 />
566 }
567 label={trailingAction.tooltip}
568 >
569 {trailingAction.pending ? trailingAction.pendingLabel : trailingAction.label}
570 {trailingAction.suffix}
571 </SharedTooltipTrigger>
572 ) : null}
573 </div>
574 </div>
575 ) : watching ? (
576 <div className={THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS}>
577 {openRow(label, "primary")}
578 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
579 {watchControl("secondary")}
580 </div>
581 ) : (
582 openRow(label, "row")
583 )}
584 {rowAction === "merge" ? (
585 <AlertDialog open={confirmingMerge} onOpenChange={(open) => setConfirmingMerge(open)}>
586 <AlertDialogPopup>
587 <AlertDialogHeader>
588 <AlertDialogTitle>
589 {gt(
590 "Merge {term, select, mr {merge request} cr {change request} other {pull request}}?",
591 { term },
592 )}
593 </AlertDialogTitle>
594 <AlertDialogDescription>
595 {gt(
596 "This merges #{number} using {method, select, merge {merge} squash {squash} rebase {rebase} fastForward {fast-forward} other {merge}}.",
597 {
598 number,
599 method: mergeMethodKey,
600 },
601 )}
602 </AlertDialogDescription>
603 </AlertDialogHeader>
604 <AlertDialogFooter>
605 <AlertDialogClose render={<Button variant="outline" size="sm" />}>
606 <T>Cancel</T>
607 </AlertDialogClose>
608 <Button
609 size="sm"
610 disabled={actionPending}
611 onClick={() => {
612 setConfirmingMerge(false);
613 void perform("merge", selectedMergeMethod);
614 }}
615 >
616 <T context="verb, merges a pull request">Merge</T>
617 </Button>
618 </AlertDialogFooter>
619 </AlertDialogPopup>
620 </AlertDialog>
621 ) : null}
622 </>
623 );