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