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

ThreadDetailsPrRow.tsx

465 lines16.0 KB

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