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

ThreadDetailsPrRow.tsx

515 lines18.3 KB

1import { resolvePullRequestDetailChecks } from "@t3tools/client-runtime/pull-request-checks";
2import {
3 capitalizeTerm,
4 sourceControlClients,
5} from "@t3tools/client-runtime/source-control-clients";
6import { PullRequestChangeBreakdownRows } from "../pullRequest/PullRequestChangeBreakdownStat";
7import { ThreadDetailsControl } from "./ThreadDetailsControl";
8import { PullRequestGlyph } from "../pullRequest/pullRequestIcons";
9import { selectEnvironmentQueryData } from "@t3tools/client-runtime/state/runtime";
10import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
11import type { EnvironmentId, ProjectId, PullRequestRef } from "@t3tools/contracts";
12import {
13 ArrowUpRightIcon,
14 EyeIcon,
15 EyeOffIcon,
16 FileDiffIcon,
17 GitBranchIcon,
18 TriangleAlertIcon,
19} from "lucide-react";
20import { AsyncResult } from "effect/reactivity";
21import { useState, type MouseEvent as ReactMouseEvent } from "react";
22​
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} from "../pullRequest/usePullRequestActions";
57import {
58 ChangeRequestStatusIcon,
59 type PrStatusIndicator,
60 type ThreadPr,
61} from "../ThreadStatusIndicators";
62import {
63 AlertDialog,
64 AlertDialogClose,
65 AlertDialogDescription,
66 AlertDialogFooter,
67 AlertDialogHeader,
68 AlertDialogPopup,
69 AlertDialogTitle,
70} from "../ui/alert-dialog";
71import { Button } from "../ui/button";
72import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
73import {
74 THREAD_DETAILS_PANEL_ICON_CLASS,
75 THREAD_DETAILS_PANEL_LABEL_CLASS,
76 THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS,
77 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
78} from "./threadDetailsPanelStyles";
79​
80// A null checks response is settled; polling cannot find checks.
81const isSettledWithoutChecks = (result: AsyncResult.AsyncResult<unknown, unknown>) =>
82 result._tag === "Success" && result.value === null;
83​
84export function ThreadDetailsPrRow({
85 environmentId,
86 pr,
87 number,
88 reference: linkedReference,
89 status,
90 project,
91 label,
92 openAriaLabel,
93 onOpen,
94 onActed,
95 onStopWatching,
96}: {
97 environmentId: EnvironmentId;
98 pr: ThreadPr;
99 number: number;
100 reference?: Pick<PullRequestRef, "host" | "repository" | "number"> | null;
101 status: PrStatusIndicator | null;
102 project: EnvironmentProject | null;
103 label: string;
104 openAriaLabel: string;
105 onOpen: (event: ReactMouseEvent<HTMLElement>) => void;
106 onActed?: () => void;
107 onStopWatching?: (() => void) | undefined;
108}) {
109 const serverConfigs = useServerConfigs();
110 const supportsPullRequests = serverConfigs.get(environmentId) !== undefined;
111 const repository = sourceControlClients.repositorySelector(project?.repositoryIdentity);
112 const reference: PullRequestRef | null =
113 supportsPullRequests && project !== null
114 ? linkedReference
115 ? { ...linkedReference, projectId: project.id as ProjectId }
116 : repository !== null
117 ? { projectId: project.id as ProjectId, repository, number }
118 : null
119 : null;
120 const detailAtom =
121 reference === null
122 ? null
123 : pullRequestEnvironment.detail({
124 environmentId,
125 input: { ...reference, allowStale: false },
126 });
127 // Select query parts because polling rebuilds unchanged results.
128 const detailData = useEnvironmentQuerySelector(detailAtom, selectEnvironmentQueryData);
129 const detailQuery = useEnvironmentQueryRefresh(detailAtom);
130 const supportsChecks =
131 serverConfigs.get(environmentId)?.environment.capabilities.pullRequestChecks === true;
132 const checksAtom =
133 supportsChecks && reference !== null && detailData !== null
134 ? pullRequestEnvironment.checks({ environmentId, input: reference })
135 : null;
136 const checksData = useEnvironmentQuerySelector(checksAtom, selectEnvironmentQueryData);
137 const checksSettledEmpty = useEnvironmentQuerySelector(checksAtom, isSettledWithoutChecks);
138 const checksQuery = useEnvironmentQueryRefresh(checksAtom);
139 const checksAreNewer = useEnvironmentQueryIsNewer(checksAtom, detailAtom);
140 const detail = resolvePullRequestDetailChecks(detailData, checksData, checksAreNewer);
141 const terminology = sourceControlClients.get(
142 detail?.provider ?? project?.repositoryIdentity?.provider,
143 ).changeRequest;
144 const open = reference !== null && (detail?.state ?? pr?.state) === "open";
145 const refreshKey = `${environmentId}:${project?.id}:${reference?.host}:${reference?.repository}:${number}`;
146 useLiveRefresh(
147 () => {
148 if (!detailQuery.isPending()) detailQuery.refresh();
149 },
150 { enabled: open, key: `workspace-pr:${refreshKey}`, intervalMs: 10 * 60_000 },
151 );
152 usePullRequestChecksRefresh({
153 refresh: () => {
154 if (!checksQuery.isPending() && !detailQuery.isPending()) checksQuery.refresh();
155 },
156 enabled: open && supportsChecks && !checksSettledEmpty,
157 key: `workspace-pr-checks:${refreshKey}`,
158 checks: detail?.checks ?? [],
159 });
160​
161 const { actionPending, perform } = usePullRequestActionRunner({
162 environmentId,
163 reference,
164 terminology,
165 onSuccess: () => {
166 checksQuery.refresh();
167 onActed?.();
168 },
169 });
170 const { handoff, startHandoff } = usePullRequestHandoffs({ environmentId, detail });
171 const lastSelectedMergeMethod = useUiStateStore((state) => state.pullRequestMergeMethod);
172 const resolveProjectDefaultMergeMethod = usePullRequestDefaultMergeMethodResolver(
173 environmentId,
174 (project?.id as ProjectId | undefined) ?? null,
175 );
176 const [confirmingMerge, setConfirmingMerge] = useState(false);
177​
178 const rowAction = resolveThreadPanelPullRequestAction(detail);
179 if (confirmingMerge && rowAction !== "merge") {
180 setConfirmingMerge(false);
181 }
182 const conflicting = isPullRequestConflicting(detail);
183 const checksState = detail === null ? "none" : classifyPullRequestChecks(detail.checks);
184 const checksRollup = detail === null ? null : pullRequestChecksState(detail.checks);
185 const selectedMergeMethod = resolvePullRequestMergeMethod(
186 allowedPullRequestMergeMethods(detail),
187 null,
188 resolveProjectDefaultMergeMethod(),
189 lastSelectedMergeMethod,
190 );
191​
192 const startResolveConflicts = () => {
193 if (detail === null) return;
194 void startHandoff("conflicts", {
195 prompt: buildResolveConflictsPrompt({
196 number: detail.number,
197 url: detail.url,
198 headBranch: detail.headBranch,
199 baseBranch: detail.baseBranch,
200 }),
201 });
202 };
203​
204 const startFixChecks = () => {
205 if (detail === null) return;
206 void startHandoff(
207 "findings",
208 buildFixFindingsHandoff({
209 number: detail.number,
210 title: detail.title,
211 url: detail.url,
212 headBranch: detail.headBranch,
213 baseBranch: detail.baseBranch,
214 state: detail.state,
215 isDraft: detail.isDraft,
216 reviewThreads: [],
217 comments: [],
218 checks: detail.checks,
219 commentsTruncated: false,
220 }),
221 );
222 };
223​
224 const statePresentation =
225 detail === null
226 ? null
227 : resolvePullRequestState({
228 state: detail.state,
229 isDraft: detail.isDraft,
230 });
231 const icon = statePresentation ? (
232 <statePresentation.Icon
233 aria-hidden
234 className={cn("size-4 shrink-0", statePresentation.toneClassName)}
235 />
236 ) : pr && status ? (
237 <ChangeRequestStatusIcon
238 state={pr.state}
239 className={cn(THREAD_DETAILS_PANEL_ICON_CLASS, status.colorClass)}
240 />
241 ) : (
242 <PullRequestGlyph.pullRequest className={THREAD_DETAILS_PANEL_ICON_CLASS} />
243 );
244​
245 const rowTooltip =
246 detail === null || statePresentation === null ? (
247 <TooltipPopup side="top">
248 {status?.tooltip ?? `${capitalizeTerm(terminology.singular)} #${number}`}
249 </TooltipPopup>
250 ) : (
251 <TooltipPopup
252 side="top"
253 align="start"
254 sideOffset={4}
255 variant="glass"
256 className="max-w-80 text-left whitespace-normal"
257 >
258 <div className="flex min-w-0 max-w-80 flex-col gap-2 px-1 py-2">
259 <div className="flex min-w-0 items-baseline gap-1.5 text-xs leading-none">
260 <span className="min-w-0 truncate font-medium text-foreground">{detail.title}</span>
261 <span className="shrink-0 text-muted-foreground">#{detail.number}</span>
262 </div>
263 <div className="grid gap-1.5 pl-0.5 text-xs text-muted-foreground">
264 <div className="flex min-w-0 items-center gap-2">
265 <statePresentation.Icon
266 aria-hidden
267 className={cn("size-3 shrink-0", statePresentation.toneClassName)}
268 />
269 <div className="min-w-0 truncate text-foreground/75">{statePresentation.label}</div>
270 </div>
271 <div className="flex min-w-0 items-center gap-2">
272 <GitBranchIcon className="size-3 shrink-0 stroke-muted-foreground" />
273 <div className="min-w-0 truncate text-foreground/75">
274 {detail.baseBranch} ← {detail.headBranch}
275 </div>
276 </div>
277 {detail.state === "open" && checksState !== "none" ? (
278 <div className="flex min-w-0 items-center gap-2">
279 <PullRequestCheckStatusIcon
280 status={
281 checksState === "failing"
282 ? "failure"
283 : checksState === "pending"
284 ? "pending"
285 : "success"
286 }
287 />
288 <div className="min-w-0 truncate text-foreground/75">
289 {describePullRequestChecks(detail.checks)}
290 </div>
291 </div>
292 ) : null}
293 {detail.isDraft && conflicting ? (
294 <div className="flex min-w-0 items-start gap-2 text-destructive">
295 <TriangleAlertIcon aria-hidden className="mt-0.5 size-3 shrink-0 stroke-current" />
296 <div className="min-w-0 flex-1 wrap-break-word">
297 Merge conflicts with {detail.baseBranch}
298 </div>
299 </div>
300 ) : null}
301 <div className="flex min-w-0 items-center gap-2">
302 <FileDiffIcon className="size-3 shrink-0 stroke-muted-foreground" />
303 <div className="min-w-0 flex items-baseline gap-1 truncate text-foreground/75">
304 {detail.changedFiles.toLocaleString()}{" "}
305 {detail.changedFiles === 1 ? "file" : "files"}
306 <PullRequestDiffStat additions={detail.additions} deletions={detail.deletions} />
307 </div>
308 </div>
309 {reference !== null && (detail.additions > 0 || detail.deletions > 0) ? (
310 <PullRequestChangeBreakdownRows
311 environmentId={environmentId}
312 reference={reference}
313 className="pl-5 text-foreground/75"
314 />
315 ) : null}
316 </div>
317 </div>
318 </TooltipPopup>
319 );
320​
321 const trailingAction =
322 rowAction === "resolve"
323 ? {
324 label: "Resolve",
325 pendingLabel: "Preparing...",
326 pending: handoff === "conflicts",
327 destructive: true,
328 suffix: <ArrowUpRightIcon aria-hidden className="size-3 shrink-0" />,
329 tooltip: "Check the branch out and resolve the conflicts in a new thread",
330 onClick: startResolveConflicts,
331 }
332 : rowAction === "ready"
333 ? {
334 label: "Ready",
335 pendingLabel: "Marking...",
336 pending: actionPending,
337 destructive: false,
338 suffix: null,
339 tooltip: `Mark this ${terminology.singular} as ready for review`,
340 onClick: () => void perform("ready"),
341 }
342 : rowAction === "fix"
343 ? {
344 label: "Fix",
345 pendingLabel: "Preparing...",
346 pending: handoff === "findings",
347 destructive: true,
348 suffix: <ArrowUpRightIcon aria-hidden className="size-3 shrink-0" />,
349 tooltip: "Fix the failing checks in a new thread",
350 onClick: startFixChecks,
351 }
352 : rowAction === "merge"
353 ? {
354 label: "Merge",
355 pendingLabel: "Merging...",
356 pending: actionPending,
357 destructive: false,
358 suffix: null,
359 tooltip: `Merge this ${terminology.singular} (${selectedMergeMethod})`,
360 onClick: () => setConfirmingMerge(true),
361 }
362 : null;
363​
364 const watching =
365 onStopWatching !== undefined && (detail?.state ?? pr?.state ?? "open") === "open";
366 const watchControl = (part: "secondary" | "icon") =>
367 watching ? (
368 <Tooltip>
369 <TooltipTrigger
370 render={
371 <ThreadDetailsControl
372 type="button"
373 variant="ghost"
374 size="sm"
375 part={part}
376 className="group/watch"
377 aria-label={`Stop watching #${number}`}
378 onClick={onStopWatching}
379 />
380 }
381 >
382 <EyeIcon
383 aria-hidden
384 className={cn(part === "icon" ? "size-3.5" : "size-4", "group-hover/watch:hidden")}
385 />
386 <EyeOffIcon
387 aria-hidden
388 className={cn(
389 part === "icon" ? "size-3.5" : "size-4",
390 "hidden group-hover/watch:block",
391 )}
392 />
393 </TooltipTrigger>
394 <TooltipPopup side="top">
395 Watching: the agent wakes when checks finish, someone comments, or the branch conflicts.
396 Click to stop.
397 </TooltipPopup>
398 </Tooltip>
399 ) : null;
400​
401 // The title row wraps to two lines; a conventional-commit prefix eats most of one line.
402 const openRow = (text: string, part: "row" | "primary", wrap = false) => (
403 <Tooltip>
404 <TooltipTrigger
405 render={
406 <ThreadDetailsControl
407 type="button"
408 variant="ghost"
409 size="sm"
410 part={part}
411 multiline={wrap}
412 className={wrap ? "items-start [&>svg]:mt-px" : undefined}
413 aria-label={openAriaLabel}
414 onClick={onOpen}
415 onAuxClick={onOpen}
416 />
417 }
418 >
419 {icon}
420 <span
421 className={cn(
422 "min-w-0 flex-1 text-left",
423 wrap
424 ? "line-clamp-2 whitespace-normal leading-4.5"
425 : cn("truncate", THREAD_DETAILS_PANEL_LABEL_CLASS),
426 )}
427 >
428 {text}
429 </span>
430 </TooltipTrigger>
431 {rowTooltip}
432 </Tooltip>
433 );
434​
435 const showChecks = detail !== null && checksRollup !== null && !conflicting && !detail.isDraft;
436​
437 return (
438 <>
439 {detail !== null && (showChecks || trailingAction !== null || watching) ? (
440 <div className="pb-1.5">
441 {openRow(detail.title, "row", true)}
442 <div className="mt-1.5 flex h-5 min-w-0 items-center gap-0.5 ps-9 pe-2.5 text-xs text-muted-foreground">
443 <span className="me-1 shrink-0 tabular-nums">#{number}</span>
444 {showChecks && checksRollup !== null ? (
445 <PullRequestChecksPopover
446 checksState={checksRollup}
447 checks={detail.checks}
448 variant="count"
449 render={<ThreadDetailsControl part="meta" />}
450 />
451 ) : null}
452 {watchControl("icon")}
453 <span className="flex-1" />
454 {trailingAction ? (
455 <Tooltip>
456 <TooltipTrigger
457 render={
458 <ThreadDetailsControl
459 type="button"
460 variant="ghost"
461 size="sm"
462 part="meta"
463 tone={trailingAction.destructive ? "destructive" : "primary"}
464 disabled={actionPending || handoff !== null}
465 onClick={trailingAction.onClick}
466 />
467 }
468 >
469 {trailingAction.pending ? trailingAction.pendingLabel : trailingAction.label}
470 {trailingAction.suffix}
471 </TooltipTrigger>
472 <TooltipPopup side="top">{trailingAction.tooltip}</TooltipPopup>
473 </Tooltip>
474 ) : null}
475 </div>
476 </div>
477 ) : watching ? (
478 <div className={THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS}>
479 {openRow(label, "primary")}
480 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
481 {watchControl("secondary")}
482 </div>
483 ) : (
484 openRow(label, "row")
485 )}
486 {rowAction === "merge" ? (
487 <AlertDialog open={confirmingMerge} onOpenChange={(open) => setConfirmingMerge(open)}>
488 <AlertDialogPopup>
489 <AlertDialogHeader>
490 <AlertDialogTitle>Merge {terminology.singular}?</AlertDialogTitle>
491 <AlertDialogDescription>
492 This merges #{number} using {selectedMergeMethod}.
493 </AlertDialogDescription>
494 </AlertDialogHeader>
495 <AlertDialogFooter>
496 <AlertDialogClose render={<Button variant="outline" size="sm" />}>
497 Cancel
498 </AlertDialogClose>
499 <Button
500 size="sm"
501 disabled={actionPending}
502 onClick={() => {
503 setConfirmingMerge(false);
504 void perform("merge", selectedMergeMethod);
505 }}
506 >
507 Merge
508 </Button>
509 </AlertDialogFooter>
510 </AlertDialogPopup>
511 </AlertDialog>
512 ) : null}
513 </>
514 );