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

ThreadDetailsPrRow.tsx

492 lines17.4 KB

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