Open History to see the last commit
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 detailQuery.refresh();
167 checksQuery.refresh();
168 onActed?.();
169 },
170 });
171 const { handoff, startHandoff } = usePullRequestHandoffs({ environmentId, detail });
172 const lastSelectedMergeMethod = useUiStateStore((state) => state.pullRequestMergeMethod);
173 const resolveProjectDefaultMergeMethod = usePullRequestDefaultMergeMethodResolver(
174 environmentId,
175 (project?.id as ProjectId | undefined) ?? null,
176 );
177 const [confirmingMerge, setConfirmingMerge] = useState(false);
178
179 const rowAction = resolveThreadPanelPullRequestAction(detail);
180 if (confirmingMerge && rowAction !== "merge") {
181 setConfirmingMerge(false);
182 }
183 const conflicting = isPullRequestConflicting(detail);
184 const checksState = detail === null ? "none" : classifyPullRequestChecks(detail.checks);
185 const checksRollup = detail === null ? null : pullRequestChecksState(detail.checks);
186 const selectedMergeMethod = resolvePullRequestMergeMethod(
187 allowedPullRequestMergeMethods(detail),
188 null,
189 resolveProjectDefaultMergeMethod(),
190 lastSelectedMergeMethod,
191 );
192
193 const startResolveConflicts = () => {
194 if (detail === null) return;
195 void startHandoff("conflicts", {
196 prompt: buildResolveConflictsPrompt({
197 number: detail.number,
198 url: detail.url,
199 headBranch: detail.headBranch,
200 baseBranch: detail.baseBranch,
201 }),
202 });
203 };
204
205 const startFixChecks = () => {
206 if (detail === null) return;
207 void startHandoff(
208 "findings",
209 buildFixFindingsHandoff({
210 number: detail.number,
211 title: detail.title,
212 url: detail.url,
213 headBranch: detail.headBranch,
214 baseBranch: detail.baseBranch,
215 reviewThreads: [],
216 comments: [],
217 checks: detail.checks,
218 commentsTruncated: false,
219 }),
220 );
221 };
222
223 const statePresentation =
224 detail === null
225 ? null
226 : resolvePullRequestState({
227 state: detail.state,
228 isDraft: detail.isDraft,
229 });
230 const icon = statePresentation ? (
231 <statePresentation.Icon
232 aria-hidden
233 className={cn("size-4 shrink-0", statePresentation.toneClassName)}
234 />
235 ) : pr && status ? (
236 <ChangeRequestStatusIcon
237 state={pr.state}
238 className={cn(THREAD_DETAILS_PANEL_ICON_CLASS, status.colorClass)}
239 />
240 ) : (
241 <PullRequestGlyph.pullRequest className={THREAD_DETAILS_PANEL_ICON_CLASS} />
242 );
243
244 const rowTooltip =
245 detail === null || statePresentation === null ? (
246 <TooltipPopup side="top">
247 {status?.tooltip ?? `${capitalizeTerm(terminology.singular)} #${number}`}
248 </TooltipPopup>
249 ) : (
250 <TooltipPopup
251 side="top"
252 align="start"
253 sideOffset={4}
254 variant="glass"
255 className="max-w-80 text-left whitespace-normal"
256 >
257 <div className="flex min-w-0 max-w-80 flex-col gap-2 px-1 py-2">
258 <div className="flex min-w-0 items-baseline gap-1.5 text-xs leading-none">
259 <span className="min-w-0 truncate font-medium text-foreground">{detail.title}</span>
260 <span className="shrink-0 text-muted-foreground">#{detail.number}</span>
261 </div>
262 <div className="grid gap-1.5 pl-0.5 text-xs text-muted-foreground">
263 <div className="flex min-w-0 items-center gap-2">
264 <statePresentation.Icon
265 aria-hidden
266 className={cn("size-3 shrink-0", statePresentation.toneClassName)}
267 />
268 <div className="min-w-0 truncate text-foreground/75">{statePresentation.label}</div>
269 </div>
270 <div className="flex min-w-0 items-center gap-2">
271 <GitBranchIcon className="size-3 shrink-0 stroke-muted-foreground" />
272 <div className="min-w-0 truncate text-foreground/75">
273 {detail.baseBranch} ← {detail.headBranch}
274 </div>
275 </div>
276 {detail.state === "open" && checksState !== "none" ? (
277 <div className="flex min-w-0 items-center gap-2">
278 <PullRequestCheckStatusIcon
279 status={
280 checksState === "failing"
281 ? "failure"
282 : checksState === "pending"
283 ? "pending"
284 : "success"
285 }
286 />
287 <div className="min-w-0 truncate text-foreground/75">
288 {describePullRequestChecks(detail.checks)}
289 </div>
290 </div>
291 ) : null}
292 {detail.isDraft && conflicting ? (
293 <div className="flex min-w-0 items-start gap-2 text-destructive">
294 <TriangleAlertIcon aria-hidden className="mt-0.5 size-3 shrink-0 stroke-current" />
295 <div className="min-w-0 flex-1 wrap-break-word">
296 Merge conflicts with {detail.baseBranch}
297 </div>
298 </div>
299 ) : null}
300 <div className="flex min-w-0 items-center gap-2">
301 <FileDiffIcon className="size-3 shrink-0 stroke-muted-foreground" />
302 <div className="min-w-0 flex items-baseline gap-1 truncate text-foreground/75">
303 {detail.changedFiles.toLocaleString()}{" "}
304 {detail.changedFiles === 1 ? "file" : "files"}
305 <PullRequestDiffStat additions={detail.additions} deletions={detail.deletions} />
306 </div>
307 </div>
308 {reference !== null && (detail.additions > 0 || detail.deletions > 0) ? (
309 <PullRequestChangeBreakdownRows
310 environmentId={environmentId}
311 reference={reference}
312 className="pl-5 text-foreground/75"
313 />
314 ) : null}
315 </div>
316 </div>
317 </TooltipPopup>
318 );
319
320 const trailingAction =
321 rowAction === "resolve"
322 ? {
323 label: "Resolve",
324 pendingLabel: "Preparing...",
325 pending: handoff === "conflicts",
326 destructive: true,
327 suffix: <ArrowUpRightIcon aria-hidden className="size-3 shrink-0" />,
328 tooltip: "Check the branch out and resolve the conflicts in a new thread",
329 onClick: startResolveConflicts,
330 }
331 : rowAction === "ready"
332 ? {
333 label: "Ready",
334 pendingLabel: "Marking...",
335 pending: actionPending,
336 destructive: false,
337 suffix: null,
338 tooltip: `Mark this ${terminology.singular} as ready for review`,
339 onClick: () => void perform("ready"),
340 }
341 : rowAction === "fix"
342 ? {
343 label: "Fix",
344 pendingLabel: "Preparing...",
345 pending: handoff === "findings",
346 destructive: true,
347 suffix: <ArrowUpRightIcon aria-hidden className="size-3 shrink-0" />,
348 tooltip: "Fix the failing checks in a new thread",
349 onClick: startFixChecks,
350 }
351 : rowAction === "merge"
352 ? {
353 label: "Merge",
354 pendingLabel: "Merging...",
355 pending: actionPending,
356 destructive: false,
357 suffix: null,
358 tooltip: `Merge this ${terminology.singular} (${selectedMergeMethod})`,
359 onClick: () => setConfirmingMerge(true),
360 }
361 : null;
362
363 const watching =
364 onStopWatching !== undefined && (detail?.state ?? pr?.state ?? "open") === "open";
365 const watchControl = (part: "secondary" | "icon") =>
366 watching ? (
367 <Tooltip>
368 <TooltipTrigger
369 render={
370 <ThreadDetailsControl
371 type="button"
372 variant="ghost"
373 size="sm"
374 part={part}
375 className="group/watch"
376 aria-label={`Stop watching #${number}`}
377 onClick={onStopWatching}
378 />
379 }
380 >
381 <EyeIcon
382 aria-hidden
383 className={cn(part === "icon" ? "size-3.5" : "size-4", "group-hover/watch:hidden")}
384 />
385 <EyeOffIcon
386 aria-hidden
387 className={cn(
388 part === "icon" ? "size-3.5" : "size-4",
389 "hidden group-hover/watch:block",
390 )}
391 />
392 </TooltipTrigger>
393 <TooltipPopup side="top">
394 Watching: the agent wakes when checks finish, someone comments, or the branch conflicts.
395 Click to stop.
396 </TooltipPopup>
397 </Tooltip>
398 ) : null;
399
400 // The title row wraps to two lines; a conventional-commit prefix eats most of one line.
401 const openRow = (text: string, part: "row" | "primary", wrap = false) => (
402 <Tooltip>
403 <TooltipTrigger
404 render={
405 <ThreadDetailsControl
406 type="button"
407 variant="ghost"
408 size="sm"
409 part={part}
410 multiline={wrap}
411 className={wrap ? "items-start [&>svg]:mt-0.5" : undefined}
412 aria-label={openAriaLabel}
413 onClick={onOpen}
414 onAuxClick={onOpen}
415 />
416 }
417 >
418 {icon}
419 <span
420 className={cn(
421 "min-w-0 flex-1 text-left",
422 wrap
423 ? "line-clamp-2 whitespace-normal leading-4.5"
424 : cn("truncate", THREAD_DETAILS_PANEL_LABEL_CLASS),
425 )}
426 >
427 {text}
428 </span>
429 </TooltipTrigger>
430 {rowTooltip}
431 </Tooltip>
432 );
433
434 const showChecks = detail !== null && checksRollup !== null && !conflicting && !detail.isDraft;
435
436 return (
437 <>
438 {detail !== null && (showChecks || trailingAction !== null || watching) ? (
439 <div className="pb-1.5">
440 {openRow(detail.title, "row", true)}
441 <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">
442 <span className="me-1 shrink-0 tabular-nums">#{number}</span>
443 {showChecks && checksRollup !== null ? (
444 <PullRequestChecksPopover
445 checksState={checksRollup}
446 checks={detail.checks}
447 variant="count"
448 render={<ThreadDetailsControl part="meta" />}
449 />
450 ) : null}
451 {watchControl("icon")}
452 <span className="flex-1" />
453 {trailingAction ? (
454 <Tooltip>
455 <TooltipTrigger
456 render={
457 <ThreadDetailsControl
458 type="button"
459 variant="ghost"
460 size="sm"
461 part="meta"
462 tone={trailingAction.destructive ? "destructive" : "primary"}
463 disabled={actionPending || handoff !== null}
464 onClick={trailingAction.onClick}
465 />
466 }
467 >
468 {trailingAction.pending ? trailingAction.pendingLabel : trailingAction.label}
469 {trailingAction.suffix}
470 </TooltipTrigger>
471 <TooltipPopup side="top">{trailingAction.tooltip}</TooltipPopup>
472 </Tooltip>
473 ) : null}
474 </div>
475 </div>
476 ) : watching ? (
477 <div className={THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS}>
478 {openRow(label, "primary")}
479 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
480 {watchControl("secondary")}
481 </div>
482 ) : (
483 openRow(label, "row")
484 )}
485 {rowAction === "merge" ? (
486 <AlertDialog open={confirmingMerge} onOpenChange={(open) => setConfirmingMerge(open)}>
487 <AlertDialogPopup>
488 <AlertDialogHeader>
489 <AlertDialogTitle>Merge {terminology.singular}?</AlertDialogTitle>
490 <AlertDialogDescription>
491 This merges #{number} using {selectedMergeMethod}.
492 </AlertDialogDescription>
493 </AlertDialogHeader>
494 <AlertDialogFooter>
495 <AlertDialogClose render={<Button variant="outline" size="sm" />}>
496 Cancel
497 </AlertDialogClose>
498 <Button
499 size="sm"
500 disabled={actionPending}
501 onClick={() => {
502 setConfirmingMerge(false);
503 void perform("merge", selectedMergeMethod);
504 }}
505 >
506 Merge
507 </Button>
508 </AlertDialogFooter>
509 </AlertDialogPopup>
510 </AlertDialog>
511 ) : null}
512 </>
513 );
514}