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

ThreadDetailsPrRow.tsx

506 lines18.0 KB

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