Open History to see the last commit
1import { resolvePullRequestDetailChecks } from "@t3tools/client-runtime/pull-request-checks";
2import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
3import { changeRequestTermKind } from "../pullRequest/changeRequestTerm";
4import { T, useGT, useMessages, Var } from "gt-react";
5import { PullRequestChangeBreakdownRows } from "../pullRequest/PullRequestChangeBreakdownStat";
6import { ThreadDetailsControl } from "./ThreadDetailsControl";
7import { PullRequestGlyph } from "../pullRequest/pullRequestIcons";
8import { selectEnvironmentQueryData } from "@t3tools/client-runtime/state/runtime";
9import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
10import type { EnvironmentId, ProjectId, PullRequestRef } from "@t3tools/contracts";
11import {
12 ArrowUpRightIcon,
13 EyeIcon,
14 EyeOffIcon,
15 FileDiffIcon,
16 GitBranchIcon,
17 TriangleAlertIcon,
18} from "lucide-react";
19import { AsyncResult } from "effect/reactivity";
20import { useState, type MouseEvent as ReactMouseEvent } from "react";
21
22import type { ComposerThreadTarget } from "~/composerDraftStore";
23import { useLiveRefresh } from "~/hooks/useLiveRefresh";
24import { usePullRequestChecksRefresh } from "~/hooks/usePullRequestChecksRefresh";
25import { cn } from "~/lib/utils";
26import { useServerConfigs } from "~/state/entities";
27import { pullRequestEnvironment } from "~/state/pullRequests";
28import { useUiStateStore } from "~/uiStateStore";
29import {
30 useEnvironmentQueryIsNewer,
31 useEnvironmentQueryRefresh,
32 useEnvironmentQuerySelector,
33} from "~/state/query";
34
35import {
36 buildFixFindingsHandoff,
37 buildResolveConflictsPrompt,
38 classifyPullRequestChecks,
39 describePullRequestChecks,
40 isPullRequestConflicting,
41 resolvePullRequestMergeMethod,
42 allowedPullRequestMergeMethods,
43 resolveThreadPanelPullRequestAction,
44} from "../pullRequest/pullRequestDetail.logic";
45import { PullRequestChecksPopover } from "../pullRequest/PullRequestChecksPopover";
46import {
47 pullRequestChecksState,
48 PullRequestCheckStatusIcon,
49 PullRequestDiffStat,
50 resolvePullRequestState,
51} from "../pullRequest/pullRequestPresentation";
52import {
53 usePullRequestActionRunner,
54 usePullRequestDefaultMergeMethodResolver,
55 usePullRequestHandoffs,
56 writeHandoffToComposer,
57 type PullRequestThreadTask,
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 { Spinner } from "../ui/spinner";
75import { toastManager } from "../ui/toast";
76import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
77import {
78 THREAD_DETAILS_PANEL_ICON_CLASS,
79 THREAD_DETAILS_PANEL_LABEL_CLASS,
80 THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS,
81 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
82} from "./threadDetailsPanelStyles";
83
84// A null checks response is settled; polling cannot find checks.
85const isSettledWithoutChecks = (result: AsyncResult.AsyncResult<unknown, unknown>) =>
86 result._tag === "Success" && result.value === null;
87
88export function ThreadDetailsPrRow({
89 environmentId,
90 pr,
91 number,
92 reference: linkedReference,
93 status,
94 project,
95 label,
96 onOpen,
97 onActed,
98 onStopWatching,
99 composerTarget,
100}: {
101 environmentId: EnvironmentId;
102 pr: ThreadPr;
103 number: number;
104 reference?: Pick<PullRequestRef, "host" | "repository" | "number"> | null;
105 status: PrStatusIndicator | null;
106 project: EnvironmentProject | null;
107 label: string;
108 onOpen: (event: ReactMouseEvent<HTMLElement>) => void;
109 onActed?: () => void;
110 onStopWatching?: (() => void) | undefined;
111 /** Fix and Resolve write here instead of checking the pull request out in a new thread. */
112 composerTarget?: ComposerThreadTarget | undefined;
113}) {
114 const gt = useGT();
115 const m = useMessages();
116 const serverConfigs = useServerConfigs();
117 const supportsPullRequests = serverConfigs.get(environmentId) !== undefined;
118 const repository = sourceControlClients.repositorySelector(project?.repositoryIdentity);
119 const reference: PullRequestRef | null =
120 supportsPullRequests && project !== null
121 ? linkedReference
122 ? { ...linkedReference, projectId: project.id as ProjectId }
123 : repository !== null
124 ? { projectId: project.id as ProjectId, repository, number }
125 : null
126 : null;
127 const detailAtom =
128 reference === null
129 ? null
130 : pullRequestEnvironment.detail({
131 environmentId,
132 input: { ...reference, allowStale: false },
133 });
134 // Select query parts because polling rebuilds unchanged results.
135 const detailData = useEnvironmentQuerySelector(detailAtom, selectEnvironmentQueryData);
136 const detailQuery = useEnvironmentQueryRefresh(detailAtom);
137 const supportsChecks =
138 serverConfigs.get(environmentId)?.environment.capabilities.pullRequestChecks === true;
139 const checksAtom =
140 supportsChecks && reference !== null && detailData !== null
141 ? pullRequestEnvironment.checks({ environmentId, input: reference })
142 : null;
143 const checksData = useEnvironmentQuerySelector(checksAtom, selectEnvironmentQueryData);
144 const checksSettledEmpty = useEnvironmentQuerySelector(checksAtom, isSettledWithoutChecks);
145 const checksQuery = useEnvironmentQueryRefresh(checksAtom);
146 const checksAreNewer = useEnvironmentQueryIsNewer(checksAtom, detailAtom);
147 const detail = resolvePullRequestDetailChecks(detailData, checksData, checksAreNewer);
148 const terminology = sourceControlClients.get(
149 detail?.provider ?? project?.repositoryIdentity?.provider,
150 ).changeRequest;
151 const term = changeRequestTermKind(terminology);
152 const open = reference !== null && (detail?.state ?? pr?.state) === "open";
153 const refreshKey = `${environmentId}:${project?.id}:${reference?.host}:${reference?.repository}:${number}`;
154 useLiveRefresh(
155 () => {
156 if (!detailQuery.isPending()) detailQuery.refresh();
157 },
158 { enabled: open, key: `workspace-pr:${refreshKey}`, intervalMs: 10 * 60_000 },
159 );
160 usePullRequestChecksRefresh({
161 refresh: () => {
162 if (!checksQuery.isPending() && !detailQuery.isPending()) checksQuery.refresh();
163 },
164 enabled: open && supportsChecks && !checksSettledEmpty,
165 key: `workspace-pr-checks:${refreshKey}`,
166 checks: detail?.checks ?? [],
167 });
168
169 const [armedMergeHead, setArmedMergeHead] = useState<string>();
170 const { actionPending, pendingAction, perform } = usePullRequestActionRunner({
171 environmentId,
172 reference,
173 // The row shows no diff, so a merge lands the head it had when the confirmation opened.
174 headSha: armedMergeHead ?? detail?.headSha,
175 terminology,
176 onSuccess: () => {
177 checksQuery.refresh();
178 onActed?.();
179 },
180 // A refused merge usually means the row is stale, so show what the host has now.
181 onFailure: () => detailQuery.refresh(),
182 });
183 const { handoff, startHandoff } = usePullRequestHandoffs({ environmentId, detail });
184 const lastSelectedMergeMethod = useUiStateStore((state) => state.pullRequestMergeMethod);
185 const resolveProjectDefaultMergeMethod = usePullRequestDefaultMergeMethodResolver(
186 environmentId,
187 (project?.id as ProjectId | undefined) ?? null,
188 );
189 const [confirmingMerge, setConfirmingMerge] = useState(false);
190
191 const rowAction =
192 pendingAction === "ready" || pendingAction === "merge"
193 ? pendingAction
194 : resolveThreadPanelPullRequestAction(detail);
195 if (confirmingMerge && rowAction !== "merge") {
196 setConfirmingMerge(false);
197 }
198 const conflicting = isPullRequestConflicting(detail);
199 const checksState = detail === null ? "none" : classifyPullRequestChecks(detail.checks);
200 const checksRollup = detail === null ? null : pullRequestChecksState(detail.checks);
201 const selectedMergeMethod = resolvePullRequestMergeMethod(
202 allowedPullRequestMergeMethods(detail),
203 null,
204 resolveProjectDefaultMergeMethod(),
205 lastSelectedMergeMethod,
206 );
207 const mergeMethodKey =
208 selectedMergeMethod === "fast-forward" ? "fastForward" : selectedMergeMethod;
209
210 const handOff = (kind: "conflicts" | "findings", task: PullRequestThreadTask) => {
211 if (composerTarget === undefined) {
212 void startHandoff(kind, task);
213 return;
214 }
215 writeHandoffToComposer(composerTarget, task);
216 toastManager.add({
217 type: "success",
218 title: gt("Added to the composer"),
219 description: gt("The task is in the composer. Read it over, then send."),
220 });
221 };
222
223 const startResolveConflicts = () => {
224 if (detail === null) return;
225 handOff("conflicts", {
226 prompt: buildResolveConflictsPrompt({
227 number: detail.number,
228 url: detail.url,
229 headBranch: detail.headBranch,
230 baseBranch: detail.baseBranch,
231 inThisThread: composerTarget !== undefined,
232 }),
233 });
234 };
235
236 const startFixChecks = () => {
237 if (detail === null) return;
238 handOff(
239 "findings",
240 buildFixFindingsHandoff({
241 number: detail.number,
242 title: detail.title,
243 url: detail.url,
244 headBranch: detail.headBranch,
245 baseBranch: detail.baseBranch,
246 state: detail.state,
247 isDraft: detail.isDraft,
248 reviewThreads: [],
249 comments: [],
250 checks: detail.checks,
251 commentsTruncated: false,
252 inThisThread: composerTarget !== undefined,
253 }),
254 );
255 };
256
257 const statePresentation =
258 detail === null
259 ? null
260 : resolvePullRequestState(
261 {
262 state: detail.state,
263 isDraft: detail.isDraft,
264 },
265 m,
266 );
267 const icon = statePresentation ? (
268 <statePresentation.Icon
269 aria-hidden
270 className={cn("size-4 shrink-0", statePresentation.toneClassName)}
271 />
272 ) : pr && status ? (
273 <ChangeRequestStatusIcon
274 state={pr.state}
275 className={cn(THREAD_DETAILS_PANEL_ICON_CLASS, status.colorClass)}
276 />
277 ) : (
278 <PullRequestGlyph.pullRequest className={THREAD_DETAILS_PANEL_ICON_CLASS} />
279 );
280
281 const stateLabel = (
282 statePresentation ??
283 (pr ? resolvePullRequestState({ state: pr.state, isDraft: pr.isDraft === true }, m) : null)
284 )?.label.toLowerCase();
285 const title = (detail?.title ?? pr?.title)?.trim();
286 const openAriaLabel =
287 stateLabel && title
288 ? gt(
289 "{term, select, mr {Merge request} cr {Change request} other {Pull request}} #{number}, {state}: {title}",
290 { term, number, state: stateLabel, title },
291 )
292 : stateLabel
293 ? gt(
294 "{term, select, mr {Merge request} cr {Change request} other {Pull request}} #{number}, {state}",
295 { term, number, state: stateLabel },
296 )
297 : title
298 ? gt(
299 "{term, select, mr {Merge request} cr {Change request} other {Pull request}} #{number}: {title}",
300 { term, number, title },
301 )
302 : gt(
303 "{term, select, mr {Merge request} cr {Change request} other {Pull request}} #{number}",
304 { term, number },
305 );
306
307 const rowTooltip =
308 detail === null || statePresentation === null ? (
309 <TooltipPopup side="top">
310 {status?.tooltip ??
311 gt(
312 "{term, select, mr {Merge request} cr {Change request} other {Pull request}} #{number}",
313 {
314 term,
315 number,
316 },
317 )}
318 </TooltipPopup>
319 ) : (
320 <TooltipPopup
321 side="top"
322 align="start"
323 sideOffset={4}
324 variant="glass"
325 className="max-w-80 text-left whitespace-normal"
326 >
327 <div className="flex min-w-0 max-w-80 flex-col gap-2 px-1 py-2">
328 <div className="flex min-w-0 items-baseline gap-1.5 text-xs leading-none">
329 <span className="min-w-0 truncate font-medium text-foreground">{detail.title}</span>
330 <span className="shrink-0 text-muted-foreground">#{detail.number}</span>
331 </div>
332 <div className="grid gap-1.5 pl-0.5 text-xs text-muted-foreground">
333 <div className="flex min-w-0 items-center gap-2">
334 <statePresentation.Icon
335 aria-hidden
336 className={cn("size-3 shrink-0", statePresentation.toneClassName)}
337 />
338 <div className="min-w-0 truncate text-foreground/75">{statePresentation.label}</div>
339 </div>
340 <div className="flex min-w-0 items-center gap-2">
341 <GitBranchIcon className="size-3 shrink-0 stroke-muted-foreground" />
342 <div className="min-w-0 truncate text-foreground/75">
343 {detail.baseBranch} ← {detail.headBranch}
344 </div>
345 </div>
346 {detail.state === "open" && checksState !== "none" ? (
347 <div className="flex min-w-0 items-center gap-2">
348 <PullRequestCheckStatusIcon
349 status={
350 checksState === "failing"
351 ? "failure"
352 : checksState === "pending"
353 ? "pending"
354 : "success"
355 }
356 />
357 <div className="min-w-0 truncate text-foreground/75">
358 {describePullRequestChecks(detail.checks, m)}
359 </div>
360 </div>
361 ) : null}
362 {detail.isDraft && conflicting ? (
363 <div className="flex min-w-0 items-start gap-2 text-destructive">
364 <TriangleAlertIcon aria-hidden className="mt-0.5 size-3 shrink-0 stroke-current" />
365 <div className="min-w-0 flex-1 wrap-break-word">
366 <T>
367 Merge conflicts with <Var>{detail.baseBranch}</Var>
368 </T>
369 </div>
370 </div>
371 ) : null}
372 <div className="flex min-w-0 items-center gap-2">
373 <FileDiffIcon className="size-3 shrink-0 stroke-muted-foreground" />
374 <div className="min-w-0 flex items-baseline gap-1 truncate text-foreground/75">
375 {gt("{count, plural, one {{formatted} file} other {{formatted} files}}", {
376 count: detail.changedFiles,
377 formatted: detail.changedFiles.toLocaleString(),
378 })}
379 <PullRequestDiffStat additions={detail.additions} deletions={detail.deletions} />
380 </div>
381 </div>
382 {reference !== null && (detail.additions > 0 || detail.deletions > 0) ? (
383 <PullRequestChangeBreakdownRows
384 environmentId={environmentId}
385 reference={reference}
386 className="pl-5 text-foreground/75"
387 />
388 ) : null}
389 </div>
390 </div>
391 </TooltipPopup>
392 );
393
394 const newThreadSuffix =
395 composerTarget === undefined ? (
396 <ArrowUpRightIcon aria-hidden className="size-3 shrink-0" />
397 ) : null;
398 const trailingAction =
399 rowAction === "resolve"
400 ? {
401 label: gt("Resolve", { $context: "verb, resolves merge conflicts" }),
402 pendingLabel: gt("Preparing..."),
403 pending: handoff === "conflicts",
404 destructive: true,
405 suffix: newThreadSuffix,
406 tooltip:
407 composerTarget === undefined
408 ? gt("Check the branch out and resolve the conflicts in a new thread")
409 : gt("Resolve the conflicts in this thread"),
410 onClick: startResolveConflicts,
411 }
412 : rowAction === "ready"
413 ? {
414 label: gt("Ready", { $context: "verb, marks a draft pull request ready for review" }),
415 pendingLabel: gt("Marking..."),
416 pending: actionPending,
417 destructive: false,
418 suffix: null,
419 tooltip: gt(
420 "Mark this {term, select, mr {merge request} cr {change request} other {pull request}} as ready for review",
421 { term },
422 ),
423 onClick: () => void perform("ready"),
424 }
425 : rowAction === "fix"
426 ? {
427 label: gt("Fix", { $context: "verb, fixes failing checks" }),
428 pendingLabel: gt("Fix", { $context: "verb, fixes failing checks" }),
429 pending: handoff === "findings",
430 destructive: true,
431 suffix:
432 handoff === "findings" ? (
433 <Spinner size="xs" aria-label={gt("Preparing fix")} />
434 ) : (
435 newThreadSuffix
436 ),
437 tooltip:
438 composerTarget === undefined
439 ? gt("Fix the failing checks in a new thread")
440 : gt("Fix the failing checks in this thread"),
441 onClick: startFixChecks,
442 }
443 : rowAction === "merge"
444 ? {
445 label: gt("Merge", { $context: "verb, merges a pull request" }),
446 pendingLabel: gt("Merging..."),
447 pending: actionPending,
448 destructive: false,
449 suffix: null,
450 tooltip: gt(
451 "Merge this {term, select, mr {merge request} cr {change request} other {pull request}} ({method, select, merge {merge} squash {squash} rebase {rebase} fastForward {fast-forward} other {merge}})",
452 {
453 term,
454 method: mergeMethodKey,
455 },
456 ),
457 onClick: () => {
458 setArmedMergeHead(detail?.headSha);
459 setConfirmingMerge(true);
460 },
461 }
462 : null;
463
464 const watching =
465 onStopWatching !== undefined && (detail?.state ?? pr?.state ?? "open") === "open";
466 const watchControl = (part: "secondary" | "icon") =>
467 watching ? (
468 <Tooltip>
469 <TooltipTrigger
470 render={
471 <ThreadDetailsControl
472 type="button"
473 variant="ghost"
474 size="sm"
475 part={part}
476 className="group/watch"
477 aria-label={gt("Stop watching #{number}", { number })}
478 onClick={onStopWatching}
479 />
480 }
481 >
482 <EyeIcon
483 aria-hidden
484 className={cn(part === "icon" ? "size-3.5" : "size-4", "group-hover/watch:hidden")}
485 />
486 <EyeOffIcon
487 aria-hidden
488 className={cn(
489 part === "icon" ? "size-3.5" : "size-4",
490 "hidden group-hover/watch:block",
491 )}
492 />
493 </TooltipTrigger>
494 <TooltipPopup side="top">
495 <T>
496 Watching: the agent wakes when checks finish, someone comments, or the branch conflicts.
497 Click to stop.
498 </T>
499 </TooltipPopup>
500 </Tooltip>
501 ) : null;
502
503 // The title row wraps to two lines; a conventional-commit prefix eats most of one line.
504 const openRow = (text: string, part: "row" | "primary", wrap = false) => (
505 <Tooltip>
506 <TooltipTrigger
507 render={
508 <ThreadDetailsControl
509 type="button"
510 variant="ghost"
511 size="sm"
512 part={wrap ? "title" : part}
513 aria-label={openAriaLabel}
514 onClick={onOpen}
515 onAuxClick={onOpen}
516 />
517 }
518 >
519 {icon}
520 <span
521 className={cn(
522 "min-w-0 flex-1 text-left",
523 wrap
524 ? "line-clamp-2 whitespace-normal leading-4.5"
525 : cn("truncate", THREAD_DETAILS_PANEL_LABEL_CLASS),
526 )}
527 >
528 {text}
529 </span>
530 </TooltipTrigger>
531 {rowTooltip}
532 </Tooltip>
533 );
534
535 const showChecks = detail !== null && checksRollup !== null && !conflicting && !detail.isDraft;
536
537 return (
538 <>
539 {detail !== null && (showChecks || trailingAction !== null || watching) ? (
540 <div className="pb-1.5">
541 {openRow(detail.title, "row", true)}
542 <div className="flex h-5 min-w-0 items-center gap-0.5 ps-9 pe-2.5 text-xs text-muted-foreground">
543 <span aria-hidden className="me-1 shrink-0 tabular-nums">
544 #{number}
545 </span>
546 {showChecks && checksRollup !== null ? (
547 <PullRequestChecksPopover
548 checksState={checksRollup}
549 checks={detail.checks}
550 variant="count"
551 render={<ThreadDetailsControl part="meta" className="min-w-0 shrink" />}
552 />
553 ) : null}
554 {watchControl("icon")}
555 <span className="flex-1" />
556 {trailingAction ? (
557 <Tooltip>
558 <TooltipTrigger
559 render={
560 <ThreadDetailsControl
561 type="button"
562 variant="ghost"
563 size="sm"
564 part="meta"
565 tone={trailingAction.destructive ? "destructive" : "primary"}
566 disabled={actionPending || handoff !== null}
567 onClick={trailingAction.onClick}
568 />
569 }
570 >
571 {trailingAction.pending ? trailingAction.pendingLabel : trailingAction.label}
572 {trailingAction.suffix}
573 </TooltipTrigger>
574 <TooltipPopup side="top">{trailingAction.tooltip}</TooltipPopup>
575 </Tooltip>
576 ) : null}
577 </div>
578 </div>
579 ) : watching ? (
580 <div className={THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS}>
581 {openRow(label, "primary")}
582 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
583 {watchControl("secondary")}
584 </div>
585 ) : (
586 openRow(label, "row")
587 )}
588 {rowAction === "merge" ? (
589 <AlertDialog open={confirmingMerge} onOpenChange={(open) => setConfirmingMerge(open)}>
590 <AlertDialogPopup>
591 <AlertDialogHeader>
592 <AlertDialogTitle>
593 {gt(
594 "Merge {term, select, mr {merge request} cr {change request} other {pull request}}?",
595 { term },
596 )}
597 </AlertDialogTitle>
598 <AlertDialogDescription>
599 {gt(
600 "This merges #{number} using {method, select, merge {merge} squash {squash} rebase {rebase} fastForward {fast-forward} other {merge}}.",
601 {
602 number,
603 method: mergeMethodKey,
604 },
605 )}
606 </AlertDialogDescription>
607 </AlertDialogHeader>
608 <AlertDialogFooter>
609 <AlertDialogClose render={<Button variant="outline" size="sm" />}>
610 <T>Cancel</T>
611 </AlertDialogClose>
612 <Button
613 size="sm"
614 disabled={actionPending}
615 onClick={() => {
616 setConfirmingMerge(false);
617 void perform("merge", selectedMergeMethod);
618 }}
619 >
620 <T context="verb, merges a pull request">Merge</T>
621 </Button>
622 </AlertDialogFooter>
623 </AlertDialogPopup>
624 </AlertDialog>
625 ) : null}
626 </>
627 );
628}