Open History to see the last commit
1import { ThreadDetailsControl } from "./ThreadDetailsControl";
2import { PullRequestGlyph } from "../pullRequest/pullRequestIcons";
3/**
4 * The thread details panel's pull request row: what the thread's pull request is, and the one
5 * thing worth doing to it right now.
6 *
7 * The row itself opens the pull request in the right panel, exactly as it always has. Around
8 * that, the host's richer answer collapses into a single trailing slot, ranked by what unblocks
9 * the merge next: "Resolve" on conflicts, "Ready" on a draft, "Fix" under failing checks, and
10 * "Merge" only once the branch is clean and its checks pass. While checks run the slot reports
11 * that instead — a merge offered mid-run would race the very runs that gate it. Everything else
12 * the host knows (title, state, checks tally, diff size) lives in the row's tooltip, so a hover
13 * answers what previously took opening the panel.
14 *
15 * Until the detail arrives — or where pull requests are not supported at all — the row renders
16 * from the linked snapshot or branch summary, or just the link when status is unavailable.
17 */
18import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
19import type { EnvironmentId, ProjectId, PullRequestRef } from "@t3tools/contracts";
20import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
21import {
22 ArrowUpRightIcon,
23 EyeIcon,
24 EyeOffIcon,
25 FileDiffIcon,
26 GitBranchIcon,
27 TriangleAlertIcon,
28} from "lucide-react";
29import { useState, type MouseEvent as ReactMouseEvent } from "react";
30
31import { useLiveRefresh } from "~/hooks/useLiveRefresh";
32import { usePullRequestChecksRefresh } from "~/hooks/usePullRequestChecksRefresh";
33import { cn } from "~/lib/utils";
34import { useServerConfigs } from "~/state/entities";
35import { pullRequestEnvironment } from "~/state/pullRequests";
36import { useEnvironmentQuery } from "~/state/query";
37
38import {
39 buildFixFindingsHandoff,
40 buildResolveConflictsPrompt,
41 classifyPullRequestChecks,
42 describePullRequestChecks,
43 isPullRequestConflicting,
44 resolveSelectedMergeMethod,
45 allowedPullRequestMergeMethods,
46 resolveThreadPanelPullRequestAction,
47} from "../pullRequest/pullRequestDetail.logic";
48import { PullRequestChecksPopover } from "../pullRequest/PullRequestChecksPopover";
49import {
50 pullRequestChecksState,
51 PullRequestCheckStatusIcon,
52 PullRequestDiffStat,
53 resolvePullRequestState,
54} from "../pullRequest/pullRequestPresentation";
55import {
56 usePullRequestActionRunner,
57 usePullRequestHandoffs,
58} from "../pullRequest/usePullRequestActions";
59import {
60 ChangeRequestStatusIcon,
61 type PrStatusIndicator,
62 type ThreadPr,
63} from "../ThreadStatusIndicators";
64import {
65 AlertDialog,
66 AlertDialogClose,
67 AlertDialogDescription,
68 AlertDialogFooter,
69 AlertDialogHeader,
70 AlertDialogPopup,
71 AlertDialogTitle,
72} from "../ui/alert-dialog";
73import { Button } from "../ui/button";
74import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
75import {
76 THREAD_DETAILS_PANEL_ICON_CLASS,
77 THREAD_DETAILS_PANEL_LINK_SPLIT_GROUP_CLASS,
78 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
79} from "./threadDetailsPanelStyles";
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 /** The thread's project, which is what the pull request is read through on the host. */
100 project: EnvironmentProject | null;
101 label: string;
102 openAriaLabel: string;
103 onOpen: (event: ReactMouseEvent<HTMLElement>) => void;
104 /** An action changed the pull request on the host, so the vcs status behind the row is stale. */
105 onActed?: () => void;
106 /** Set while the server watches this pull request for the thread; stops the watch. */
107 onStopWatching?: (() => void) | undefined;
108}) {
109 const serverConfigs = useServerConfigs();
110 const supportsPullRequests =
111 serverConfigs.get(environmentId)?.environment.capabilities.pullRequests === true;
112 const repository = sourceControlRepositorySelector(project?.repositoryIdentity);
113 const reference: PullRequestRef | null =
114 supportsPullRequests && project !== null
115 ? linkedReference
116 ? { ...linkedReference, projectId: project.id as ProjectId }
117 : repository !== null
118 ? { projectId: project.id as ProjectId, repository, number }
119 : null
120 : null;
121 const detailQuery = useEnvironmentQuery(
122 reference === null
123 ? null
124 : pullRequestEnvironment.detail({
125 environmentId,
126 input: { ...reference, allowStale: false },
127 }),
128 );
129 const supportsChecks =
130 serverConfigs.get(environmentId)?.environment.capabilities.pullRequestChecks === true;
131 const checksQuery = useEnvironmentQuery(
132 supportsChecks && reference !== null && detailQuery.data !== null
133 ? pullRequestEnvironment.checks({ environmentId, input: reference })
134 : null,
135 );
136 const detail =
137 detailQuery.data === null
138 ? null
139 : checksQuery.data !== null && checksQuery.dataUpdatedAt >= detailQuery.dataUpdatedAt
140 ? { ...detailQuery.data, ...checksQuery.data }
141 : detailQuery.data;
142 const open = reference !== null && (detail?.state ?? pr?.state) === "open";
143 const refreshKey = `${environmentId}:${project?.id}:${reference?.host}:${reference?.repository}:${number}`;
144 useLiveRefresh(detailQuery.isPending ? null : detailQuery.refresh, {
145 enabled: open,
146 key: `workspace-pr:${refreshKey}`,
147 intervalMs: 10 * 60_000,
148 });
149 usePullRequestChecksRefresh({
150 refresh: checksQuery.isPending || detailQuery.isPending ? null : checksQuery.refresh,
151 enabled: open && supportsChecks && !(checksQuery.isSuccess && checksQuery.data === null),
152 key: `workspace-pr-checks:${refreshKey}`,
153 checks: detail?.checks ?? [],
154 });
155
156 const { actionPending, perform } = usePullRequestActionRunner({
157 environmentId,
158 reference,
159 onSuccess: () => {
160 detailQuery.refresh();
161 checksQuery.refresh();
162 onActed?.();
163 },
164 });
165 const { handoff, startHandoff } = usePullRequestHandoffs({ environmentId, detail });
166 const [confirmingMerge, setConfirmingMerge] = useState(false);
167
168 const rowAction = resolveThreadPanelPullRequestAction(detail);
169 if (confirmingMerge && rowAction !== "merge") {
170 setConfirmingMerge(false);
171 }
172 const conflicting = isPullRequestConflicting(detail);
173 const checksState = detail === null ? "none" : classifyPullRequestChecks(detail.checks);
174 const checksRollup = detail === null ? null : pullRequestChecksState(detail.checks);
175 const selectedMergeMethod = resolveSelectedMergeMethod(
176 allowedPullRequestMergeMethods(detail),
177 "merge",
178 );
179
180 const startResolveConflicts = () => {
181 if (detail === null) return;
182 void startHandoff("conflicts", {
183 prompt: buildResolveConflictsPrompt({
184 number: detail.number,
185 url: detail.url,
186 headBranch: detail.headBranch,
187 baseBranch: detail.baseBranch,
188 }),
189 });
190 };
191
192 const startFixChecks = () => {
193 if (detail === null) return;
194 // The compact row fetches no conversation, so the handoff carries the failing checks alone;
195 // review threads keep arriving through the full panel's richer version of this action.
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 // Host details distinguish drafts; all panels share the same PR-state glyph.
213 const statePresentation =
214 detail === null
215 ? null
216 : resolvePullRequestState({
217 state: detail.state,
218 isDraft: detail.isDraft,
219 });
220 const icon = statePresentation ? (
221 <statePresentation.Icon
222 aria-hidden
223 className={cn("size-4 shrink-0", statePresentation.toneClassName)}
224 />
225 ) : pr && status ? (
226 <ChangeRequestStatusIcon
227 state={pr.state}
228 className={cn(THREAD_DETAILS_PANEL_ICON_CLASS, status.colorClass)}
229 />
230 ) : (
231 <PullRequestGlyph.pullRequest className={THREAD_DETAILS_PANEL_ICON_CLASS} />
232 );
233
234 // Everything the host reported, at a glance. The row stays one line; the tooltip is where the
235 // rest of the answer lives — styled like the sidebar's thread tooltip, title above icon-led
236 // detail rows, so the two read as one family.
237 const rowTooltip =
238 detail === null || statePresentation === null ? (
239 <TooltipPopup side="top">{status?.tooltip ?? `Pull request #${number}`}</TooltipPopup>
240 ) : (
241 <TooltipPopup
242 side="top"
243 align="start"
244 sideOffset={4}
245 variant="glass"
246 className="max-w-80 text-left whitespace-normal"
247 >
248 <div className="flex min-w-0 max-w-80 flex-col gap-2 px-1 py-2">
249 <div className="flex min-w-0 items-baseline gap-1.5 text-xs leading-none">
250 <span className="min-w-0 truncate font-medium text-foreground">{detail.title}</span>
251 <span className="shrink-0 text-muted-foreground">#{detail.number}</span>
252 </div>
253 <div className="grid gap-1.5 pl-0.5 text-xs text-muted-foreground">
254 <div className="flex min-w-0 items-center gap-2">
255 <statePresentation.Icon
256 aria-hidden
257 className={cn("size-3 shrink-0", statePresentation.toneClassName)}
258 />
259 <div className="min-w-0 truncate text-foreground/75">{statePresentation.label}</div>
260 </div>
261 <div className="flex min-w-0 items-center gap-2">
262 <GitBranchIcon className="size-3 shrink-0 stroke-muted-foreground" />
263 <div className="min-w-0 truncate text-foreground/75">
264 {detail.baseBranch} ← {detail.headBranch}
265 </div>
266 </div>
267 {detail.state === "open" && checksState !== "none" ? (
268 <div className="flex min-w-0 items-center gap-2">
269 <PullRequestCheckStatusIcon
270 status={
271 checksState === "failing"
272 ? "failure"
273 : checksState === "pending"
274 ? "pending"
275 : "success"
276 }
277 />
278 <div className="min-w-0 truncate text-foreground/75">
279 {describePullRequestChecks(detail.checks)}
280 </div>
281 </div>
282 ) : null}
283 {detail.isDraft && conflicting ? (
284 <div className="flex min-w-0 items-start gap-2 text-destructive">
285 <TriangleAlertIcon aria-hidden className="mt-0.5 size-3 shrink-0 stroke-current" />
286 <div className="min-w-0 flex-1 wrap-break-word leading-5">
287 Merge conflicts with {detail.baseBranch}
288 </div>
289 </div>
290 ) : null}
291 <div className="flex min-w-0 items-center gap-2">
292 <FileDiffIcon className="size-3 shrink-0 stroke-muted-foreground" />
293 <div className="min-w-0 flex items-baseline gap-1 truncate text-foreground/75">
294 {detail.changedFiles.toLocaleString()}{" "}
295 {detail.changedFiles === 1 ? "file" : "files"}
296 <PullRequestDiffStat additions={detail.additions} deletions={detail.deletions} />
297 </div>
298 </div>
299 </div>
300 </div>
301 </TooltipPopup>
302 );
303
304 const trailingAction =
305 rowAction === "resolve"
306 ? {
307 label: "Resolve",
308 pendingLabel: "Preparing...",
309 pending: handoff === "conflicts",
310 destructive: true,
311 suffix: <ArrowUpRightIcon aria-hidden className="size-3 shrink-0" />,
312 tooltip: "Check the branch out and resolve the conflicts in a new thread",
313 onClick: startResolveConflicts,
314 }
315 : rowAction === "ready"
316 ? {
317 label: "Ready",
318 pendingLabel: "Marking...",
319 pending: actionPending,
320 destructive: false,
321 suffix: null,
322 tooltip: "Mark this pull request as ready for review",
323 onClick: () => void perform("ready"),
324 }
325 : rowAction === "fix"
326 ? {
327 label: "Fix",
328 pendingLabel: "Preparing...",
329 pending: handoff === "findings",
330 destructive: true,
331 suffix: <ArrowUpRightIcon aria-hidden className="size-3 shrink-0" />,
332 tooltip: "Fix the failing checks in a new thread",
333 onClick: startFixChecks,
334 }
335 : rowAction === "merge"
336 ? {
337 label: "Merge",
338 pendingLabel: "Merging...",
339 pending: actionPending,
340 destructive: false,
341 suffix: null,
342 tooltip: `Merge this pull request (${selectedMergeMethod})`,
343 onClick: () => setConfirmingMerge(true),
344 }
345 : null;
346
347 const rowContent = (
348 <>
349 {icon}
350 <span className="min-w-0 flex-1 truncate text-left">{label}</span>
351 </>
352 );
353
354 // The server ends a watch when the pull request closes, so only an open one shows the eye.
355 // It takes the row's rounded end when nothing follows it.
356 const watchIsLast =
357 detail === null ||
358 ((checksRollup === null || conflicting || detail.isDraft) && trailingAction === null);
359 const watchSegment =
360 onStopWatching && (detail?.state ?? pr?.state ?? "open") === "open" ? (
361 <>
362 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
363 <Tooltip>
364 <TooltipTrigger
365 render={
366 <ThreadDetailsControl
367 type="button"
368 variant="ghost"
369 size="sm"
370 part={watchIsLast ? "secondary" : "checks"}
371 className="group/watch"
372 aria-label={`Stop watching #${number}`}
373 onClick={onStopWatching}
374 />
375 }
376 >
377 <EyeIcon aria-hidden className="size-4 group-hover/watch:hidden" />
378 <EyeOffIcon aria-hidden className="hidden size-4 group-hover/watch:block" />
379 </TooltipTrigger>
380 <TooltipPopup side="top">
381 Watching: the agent wakes when checks finish, someone comments, or the branch conflicts.
382 Click to stop.
383 </TooltipPopup>
384 </Tooltip>
385 </>
386 ) : null;
387
388 return (
389 <>
390 {detail ? (
391 <div className={THREAD_DETAILS_PANEL_LINK_SPLIT_GROUP_CLASS}>
392 <Tooltip>
393 <TooltipTrigger
394 render={
395 <ThreadDetailsControl
396 type="button"
397 variant="ghost"
398 size="sm"
399 part="link-primary"
400 aria-label={openAriaLabel}
401 onClick={onOpen}
402 />
403 }
404 >
405 {rowContent}
406 </TooltipTrigger>
407 {rowTooltip}
408 </Tooltip>
409 {watchSegment}
410 {checksRollup !== null && !conflicting && !detail.isDraft ? (
411 <>
412 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
413 <PullRequestChecksPopover
414 checksState={checksRollup}
415 checks={detail.checks}
416 variant="count"
417 render={<ThreadDetailsControl part="checks" />}
418 />
419 </>
420 ) : null}
421 {trailingAction ? (
422 <>
423 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
424 <Tooltip>
425 <TooltipTrigger
426 render={
427 <ThreadDetailsControl
428 type="button"
429 variant="ghost"
430 size="sm"
431 part="action"
432 tone={trailingAction.destructive ? "destructive" : "default"}
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 </>
444 ) : null}
445 </div>
446 ) : watchSegment ? (
447 <div className={THREAD_DETAILS_PANEL_LINK_SPLIT_GROUP_CLASS}>
448 <Tooltip>
449 <TooltipTrigger
450 render={
451 <ThreadDetailsControl
452 type="button"
453 variant="ghost"
454 size="sm"
455 part="link-primary"
456 aria-label={openAriaLabel}
457 onClick={onOpen}
458 />
459 }
460 >
461 {rowContent}
462 </TooltipTrigger>
463 {rowTooltip}
464 </Tooltip>
465 {watchSegment}
466 </div>
467 ) : (
468 <Tooltip>
469 <TooltipTrigger
470 render={
471 <ThreadDetailsControl
472 type="button"
473 variant="ghost"
474 size="sm"
475 part="row"
476 aria-label={openAriaLabel}
477 onClick={onOpen}
478 />
479 }
480 >
481 {rowContent}
482 </TooltipTrigger>
483 {rowTooltip}
484 </Tooltip>
485 )}
486 {rowAction === "merge" ? (
487 <AlertDialog open={confirmingMerge} onOpenChange={(open) => setConfirmingMerge(open)}>
488 <AlertDialogPopup>
489 <AlertDialogHeader>
490 <AlertDialogTitle>Merge pull request?</AlertDialogTitle>
491 <AlertDialogDescription>
492 This merges #{number} using {selectedMergeMethod}.
493 </AlertDialogDescription>
494 </AlertDialogHeader>
495 <AlertDialogFooter>
496 <AlertDialogClose render={<Button variant="outline" size="sm" />}>
497 Cancel
498 </AlertDialogClose>
499 <Button
500 size="sm"
501 disabled={actionPending}
502 onClick={() => {
503 setConfirmingMerge(false);
504 void perform("merge", selectedMergeMethod);
505 }}
506 >
507 Merge
508 </Button>
509 </AlertDialogFooter>
510 </AlertDialogPopup>
511 </AlertDialog>
512 ) : null}
513 </>
514 );
515}