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

ThreadDetailsPrRow.tsx

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