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