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