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