Open History to see the last commit
1import { changeRequestTermKind, type ChangeRequestTermKind } from "./pullRequest/changeRequestTerm";
2import {
3 scopeProjectRef,
4 scopedThreadKey,
5 scopeThreadRef,
6} from "@t3tools/client-runtime/environment";
7import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests";
8import { useStableCallback } from "~/hooks/useStableCallback";
9
10import { pullRequestDetailToVcsStatus } from "@t3tools/client-runtime/state/pull-requests";
11import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
12import {
13 resolveEnvironmentMachineKind,
14 type EnvironmentId,
15 type ProjectId,
16 type PullRequestSummary,
17 type ScopedThreadRef,
18 type ThreadLinkedPullRequest,
19 type ThreadPullRequestLink,
20 type VcsStatusResult,
21} from "@t3tools/contracts";
22import { msg, T, useGT, useMessages, Var, plural, part, select } from "gt-react";
23import { FolderGit2Icon, TerminalIcon } from "lucide-react";
24import { m, type MessageResolver } from "../i18n/messages";
25import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments";
26import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
27import { useProject } from "../state/entities";
28import {
29 isThreadPullRequestDismissed,
30 pullRequestListLines,
31 resolveThreadCurrentPullRequestLink,
32 resolveThreadPullRequestChains,
33 type ThreadPullRequestBadge,
34} from "@t3tools/client-runtime/thread-pull-requests";
35import { useRender } from "@base-ui/react/use-render";
36import {
37 type ComponentType,
38 type ReactNode,
39 type AnimationEvent,
40 type MouseEvent,
41 type ReactElement,
42} from "react";
43import { cn } from "../lib/utils";
44import { Button } from "./ui/button";
45import { revealThreadTerminal } from "../lib/revealThreadTerminal";
46
47import { useEnvironmentQuery } from "../state/query";
48import {
49 linkedPullRequestDetailAtom,
50 useLinkedThreadPullRequestSummary,
51 useSharedPullRequestSummary,
52 useSharedThreadPullRequestBadge,
53} from "../state/pullRequests";
54import { useThreadRunningTerminalIds } from "../state/terminalSessions";
55import { vcsEnvironment } from "../state/vcs";
56import { useUiStateStore } from "../uiStateStore";
57import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
58import {
59 pullRequestMatchesSearchQuery,
60 resolveThreadLastVisitedAt,
61 resolveThreadStatusPill,
62 type ThreadStatusPill,
63 useRetainedValue,
64 useSidebarRowSubscriptionLease,
65} from "./Sidebar.logic";
66
67import type { SidebarThreadSummary } from "../types";
68import { formatWorktreePathForDisplay } from "../worktreeCleanup";
69import { SharedTooltipTrigger } from "./ui/shared-tooltip";
70import {
71 PULL_REQUEST_STATE_PRESENTATION,
72 PullRequestGlyph,
73 type PullRequestGlyphIcon,
74} from "./pullRequest/pullRequestIcons";
75import { resolvePullRequestState } from "./pullRequest/pullRequestPresentation";
76
77export interface PrStatusIndicator {
78 label: string;
79 colorClass: string;
80 Icon: PullRequestGlyphIcon;
81 tooltip: string;
82 tooltipLead: string;
83 tooltipTitle: string;
84 url: string;
85}
86
87export interface TerminalStatusIndicator {
88 label: string;
89 colorClass: string;
90 pulse: boolean;
91}
92
93export type ThreadPr = VcsStatusResult["pr"];
94
95export interface LinkedThreadPullRequestStatus {
96 readonly pr: NonNullable<ThreadPr>;
97 readonly sourceControlProvider: NonNullable<VcsStatusResult["sourceControlProvider"]>;
98}
99
100export function useLinkedThreadPullRequestWithSupport(
101 environmentId: EnvironmentId | null,
102 linkedPullRequest: ThreadLinkedPullRequest | null | undefined,
103 enabled: boolean,
104 pullRequests: ReadonlyArray<ThreadPullRequestLink> | undefined,
105 branchPullRequest: ThreadLinkedPullRequest | null | undefined,
106 projectId: ProjectId | undefined,
107 supportsLinks: boolean,
108): LinkedThreadPullRequestStatus | null {
109 const current = supportsLinks ? resolveThreadCurrentPullRequestLink(pullRequests ?? []) : null;
110 const currentStatus = useLinkedPullRequestStatus(environmentId, projectId ?? null, current);
111 const fallback =
112 current === null ? ((!supportsLinks ? linkedPullRequest : null) ?? branchPullRequest) : null;
113 // Preserve reference identity so sidebar renders do not touch the summary cache.
114 const reference = fallback == null ? null : linkedPullRequestReference(fallback);
115 // Mounted for its answers, which land in the shared summary read below.
116 useEnvironmentQuery(
117 !enabled || environmentId === null || reference === null
118 ? null
119 : linkedPullRequestDetailAtom({ environmentId, input: reference }),
120 );
121 const detail = useSharedPullRequestSummary(environmentId, reference);
122 return currentStatus ?? (detail === null ? null : summaryStatus(detail));
123}
124
125export function useLinkedThreadPullRequest(
126 environmentId: EnvironmentId | null,
127 linkedPullRequest: ThreadLinkedPullRequest | null | undefined,
128 enabled = true,
129 pullRequests?: ReadonlyArray<ThreadPullRequestLink>,
130 branchPullRequest?: ThreadLinkedPullRequest | null,
131 projectId?: ProjectId,
132): LinkedThreadPullRequestStatus | null {
133 const supportsLinks = useSupportsMultiplePullRequests(environmentId);
134 return useLinkedThreadPullRequestWithSupport(
135 environmentId,
136 linkedPullRequest,
137 enabled,
138 pullRequests,
139 branchPullRequest,
140 projectId,
141 supportsLinks,
142 );
143}
144
145function summaryStatus(detail: PullRequestSummary): LinkedThreadPullRequestStatus {
146 return {
147 pr: pullRequestDetailToVcsStatus(detail),
148 sourceControlProvider: {
149 kind: detail.provider,
150 name: sourceControlClients.get(detail.provider).label,
151 baseUrl: "",
152 },
153 };
154}
155
156export function useLinkedPullRequestStatus(
157 environmentId: EnvironmentId | null,
158 projectId: ProjectId | null,
159 link: ThreadPullRequestLink | null,
160): LinkedThreadPullRequestStatus | null {
161 const summary = useLinkedThreadPullRequestSummary(environmentId, projectId, link);
162 return summary === null
163 ? link === null
164 ? null
165 : linkedPullRequestSnapshotStatus(link)
166 : summaryStatus(summary);
167}
168
169/** The pull request a thread shows: its current link, else the one found for its branch. */
170export function useThreadDisplayedPullRequest(
171 environmentId: EnvironmentId,
172 thread: Pick<
173 EnvironmentThreadShell,
174 "projectId" | "pullRequests" | "linkedPullRequest" | "branchPullRequest"
175 > | null,
176 branchPr: ThreadPr = null,
177 branchSourceControlProvider?: VcsStatusResult["sourceControlProvider"],
178) {
179 const m = useMessages();
180 const supportsLinks = useSupportsMultiplePullRequests(environmentId);
181 const linkedStatus = useLinkedThreadPullRequest(
182 environmentId,
183 thread?.linkedPullRequest,
184 true,
185 thread?.pullRequests,
186 thread?.branchPullRequest,
187 thread?.projectId,
188 );
189 const currentLink = supportsLinks
190 ? resolveThreadCurrentPullRequestLink(thread?.pullRequests ?? [])
191 : null;
192 const pr = linkedStatus?.pr ?? (currentLink === null ? branchPr : null);
193 const badge = useSharedThreadPullRequestBadge(
194 environmentId,
195 thread?.projectId,
196 supportsLinks ? thread?.pullRequests : undefined,
197 );
198 return {
199 currentLink,
200 badge,
201 pr,
202 status: prStatusIndicator(
203 pr,
204 linkedStatus?.sourceControlProvider ?? branchSourceControlProvider,
205 m,
206 ),
207 number: currentLink?.number ?? pr?.number,
208 url: currentLink?.url ?? pr?.url,
209 };
210}
211
212function linkedPullRequestReference(fallback: ThreadLinkedPullRequest) {
213 const host = sourceControlClients.parseChangeRequestUrl(fallback.url)?.link.host;
214 return { ...fallback, ...(host === undefined ? {} : { host }) };
215}
216
217function changeRequestTerminologyForUrl(url: string | undefined) {
218 const host = url === undefined ? null : sourceControlClients.findByChangeRequestUrl(url);
219 return (host ?? sourceControlClients.get(undefined)).changeRequest;
220}
221
222function linkedPullRequestSnapshotStatus(
223 link: ThreadPullRequestLink,
224): LinkedThreadPullRequestStatus | null {
225 const snapshot = link.snapshot;
226 if (snapshot === null) return null;
227 const kind = (
228 sourceControlClients.findByChangeRequestUrl(link.url) ?? sourceControlClients.get(undefined)
229 ).kind;
230 return {
231 pr: {
232 number: link.number,
233 url: link.url,
234 title: snapshot.title,
235 state: snapshot.state,
236 isDraft: snapshot.isDraft,
237 headRef: snapshot.headBranch,
238 baseRef: snapshot.baseBranch,
239 ...(snapshot.updatedAt === null ? {} : { updatedAt: snapshot.updatedAt }),
240 },
241 sourceControlProvider: { kind, name: kind, baseUrl: "" },
242 };
243}
244
245export interface ThreadPullRequestBadgePresentation {
246 readonly Icon: PullRequestGlyphIcon;
247 readonly toneClassName: string;
248 readonly label: string;
249 readonly text: string | number;
250}
251
252type PullRequestBadgeState = ThreadPullRequestBadge["state"];
253
254function stackBadgeLabel(
255 state: PullRequestBadgeState,
256 count: number,
257 term: ChangeRequestTermKind,
258 resolve: MessageResolver,
259): string {
260 switch (state) {
261 case "open":
262 return resolve(
263 msg`${plural(
264 { count },
265 {
266 one: part`Stack of ${{ count }} ${select(
267 { term },
268 {
269 mr: "merge requests",
270 cr: "change requests",
271 other: "pull requests",
272 },
273 )}, open`,
274 other: part`Stack of ${{ count }} ${select(
275 { term },
276 {
277 mr: "merge requests",
278 cr: "change requests",
279 other: "pull requests",
280 },
281 )}, open`,
282 },
283 )}`,
284 );
285 case "draft":
286 return resolve(
287 msg`${plural(
288 { count },
289 {
290 one: part`Stack of ${{ count }} ${select(
291 { term },
292 {
293 mr: "merge requests",
294 cr: "change requests",
295 other: "pull requests",
296 },
297 )}, draft`,
298 other: part`Stack of ${{ count }} ${select(
299 { term },
300 {
301 mr: "merge requests",
302 cr: "change requests",
303 other: "pull requests",
304 },
305 )}, draft`,
306 },
307 )}`,
308 );
309 case "closed":
310 return resolve(
311 msg`${plural(
312 { count },
313 {
314 one: part`Stack of ${{ count }} ${select(
315 { term },
316 {
317 mr: "merge requests",
318 cr: "change requests",
319 other: "pull requests",
320 },
321 )}, closed`,
322 other: part`Stack of ${{ count }} ${select(
323 { term },
324 {
325 mr: "merge requests",
326 cr: "change requests",
327 other: "pull requests",
328 },
329 )}, closed`,
330 },
331 )}`,
332 );
333 case "merged":
334 return resolve(
335 msg`${plural(
336 { count },
337 {
338 one: part`Stack of ${{ count }} ${select(
339 { term },
340 {
341 mr: "merge requests",
342 cr: "change requests",
343 other: "pull requests",
344 },
345 )}, merged`,
346 other: part`Stack of ${{ count }} ${select(
347 { term },
348 {
349 mr: "merge requests",
350 cr: "change requests",
351 other: "pull requests",
352 },
353 )}, merged`,
354 },
355 )}`,
356 );
357 }
358}
359
360function moreLinkedBadgeLabel(
361 state: PullRequestBadgeState,
362 tooltip: string,
363 others: number,
364 resolve: MessageResolver,
365): string {
366 switch (state) {
367 case "open":
368 return resolve(
369 msg`${plural(
370 { others },
371 {
372 one: part`${{ tooltip }}, and ${{ others }} more linked; overall open`,
373 other: part`${{ tooltip }}, and ${{ others }} more linked; overall open`,
374 },
375 )}`,
376 );
377 case "draft":
378 return resolve(
379 msg`${plural(
380 { others },
381 {
382 one: part`${{ tooltip }}, and ${{ others }} more linked; overall draft`,
383 other: part`${{ tooltip }}, and ${{ others }} more linked; overall draft`,
384 },
385 )}`,
386 );
387 case "closed":
388 return resolve(
389 msg`${plural(
390 { others },
391 {
392 one: part`${{ tooltip }}, and ${{ others }} more linked; overall closed`,
393 other: part`${{ tooltip }}, and ${{ others }} more linked; overall closed`,
394 },
395 )}`,
396 );
397 case "merged":
398 return resolve(
399 msg`${plural(
400 { others },
401 {
402 one: part`${{ tooltip }}, and ${{ others }} more linked; overall merged`,
403 other: part`${{ tooltip }}, and ${{ others }} more linked; overall merged`,
404 },
405 )}`,
406 );
407 }
408}
409
410function prStatusLabels(
411 state: PullRequestBadgeState,
412 term: ChangeRequestTermKind,
413 number: number,
414 resolve: MessageResolver,
415): { readonly label: string; readonly tooltipLead: string } {
416 switch (state) {
417 case "open":
418 return {
419 label: resolve(
420 msg`${select({ term }, { mr: "MR", cr: "change request", other: "PR" })} open`,
421 ),
422 tooltipLead: resolve(
423 msg`${select({ term }, { mr: "MR", cr: "change request", other: "PR" })} #${{ number }} - Open`,
424 ),
425 };
426 case "draft":
427 return {
428 label: resolve(
429 msg`${select({ term }, { mr: "MR", cr: "change request", other: "PR" })} draft`,
430 ),
431 tooltipLead: resolve(
432 msg`${select({ term }, { mr: "MR", cr: "change request", other: "PR" })} #${{ number }} - Draft`,
433 ),
434 };
435 case "closed":
436 return {
437 label: resolve(
438 msg`${select({ term }, { mr: "MR", cr: "change request", other: "PR" })} closed`,
439 ),
440 tooltipLead: resolve(
441 msg`${select({ term }, { mr: "MR", cr: "change request", other: "PR" })} #${{ number }} - Closed`,
442 ),
443 };
444 case "merged":
445 return {
446 label: resolve(
447 msg`${select({ term }, { mr: "MR", cr: "change request", other: "PR" })} merged`,
448 ),
449 tooltipLead: resolve(
450 msg`${select({ term }, { mr: "MR", cr: "change request", other: "PR" })} #${{ number }} - Merged`,
451 ),
452 };
453 }
454}
455
456function resolveThreadPullRequestBadgePresentation(
457 {
458 badge,
459 number,
460 url,
461 status,
462 }: {
463 readonly badge: ThreadPullRequestBadge | null;
464 readonly number?: number | undefined;
465 readonly url?: string | undefined;
466 readonly status: PrStatusIndicator | null;
467 },
468 resolve: MessageResolver = m,
469): ThreadPullRequestBadgePresentation | null {
470 const terminology = changeRequestTerminologyForUrl(url);
471 if (badge?.kind === "stack") {
472 const aggregate = PULL_REQUEST_STATE_PRESENTATION[badge.state];
473 return {
474 Icon: PullRequestGlyph.stack,
475 toneClassName: aggregate.toneClassName,
476 label: stackBadgeLabel(
477 badge.state,
478 badge.layers,
479 changeRequestTermKind(terminology),
480 resolve,
481 ),
482 text: badge.layers,
483 };
484 }
485 if (number === undefined || url === undefined) return null;
486
487 const tooltip =
488 status?.tooltip ??
489 resolve(
490 msg`${select(
491 { term: changeRequestTermKind(terminology) },
492 {
493 mr: "MR",
494 cr: "change request",
495 other: "PR",
496 },
497 )} #${{ number }}, status pending`,
498 );
499 if (badge?.kind === "pull-request" && badge.others > 0) {
500 const aggregate = PULL_REQUEST_STATE_PRESENTATION[badge.state];
501 return {
502 Icon: aggregate.Icon,
503 toneClassName: aggregate.toneClassName,
504 label: moreLinkedBadgeLabel(badge.state, tooltip, badge.others, resolve),
505 text: `+${badge.others + 1}`,
506 };
507 }
508 return {
509 Icon: status?.Icon ?? PullRequestGlyph.pullRequest,
510 toneClassName: status?.colorClass ?? "text-muted-foreground",
511 label: tooltip,
512 text: number,
513 };
514}
515
516export function ThreadPullRequestBadgeControl({
517 render,
518 badge,
519 environmentId,
520 projectId,
521 pullRequests,
522 number,
523 url,
524 status,
525 onOpenList,
526 onOpenPullRequest,
527 side,
528}: {
529 render: ReactElement<{ render?: useRender.RenderProp }>;
530 badge: ThreadPullRequestBadge | null;
531 environmentId: EnvironmentId;
532 projectId: ProjectId | null;
533 pullRequests: ReadonlyArray<ThreadPullRequestLink>;
534 number?: number | undefined;
535 url?: string | undefined;
536 status: PrStatusIndicator | null;
537 onOpenList: () => void;
538 onOpenPullRequest: (event: MouseEvent<HTMLElement>, url?: string) => void;
539 side?: ThreadLinkBadgeSide | undefined;
540}) {
541 const m = useMessages();
542 const presentation = resolveThreadPullRequestBadgePresentation({ badge, number, url, status }, m);
543 if (presentation === null) return null;
544 return (
545 <PullRequestBadge
546 render={render}
547 presentation={presentation}
548 opensList={badge !== null && (badge.kind === "stack" || badge.others > 0)}
549 url={url}
550 number={number}
551 status={status}
552 environmentId={environmentId}
553 projectId={projectId}
554 pullRequests={pullRequests}
555 onOpenList={onOpenList}
556 onOpenPullRequest={onOpenPullRequest}
557 side={side}
558 />
559 );
560}
561
562function PullRequestBadge({
563 render,
564 presentation,
565 opensList,
566 url,
567 number,
568 status,
569 environmentId,
570 projectId,
571 pullRequests,
572 onOpenList,
573 onOpenPullRequest,
574 side,
575}: {
576 render: ReactElement<{ render?: useRender.RenderProp }>;
577 presentation: NonNullable<ReturnType<typeof resolveThreadPullRequestBadgePresentation>>;
578 opensList: boolean;
579 url: string | undefined;
580 number: number | undefined;
581 status: PrStatusIndicator | null;
582 environmentId: EnvironmentId;
583 projectId: ProjectId | null;
584 pullRequests: ReadonlyArray<ThreadPullRequestLink>;
585 onOpenList: () => void;
586 onOpenPullRequest: (event: MouseEvent<HTMLElement>, url?: string) => void;
587 side: ThreadLinkBadgeSide | undefined;
588}) {
589 const onClick = opensList
590 ? (event: MouseEvent<HTMLElement>) => {
591 event.preventDefault();
592 event.stopPropagation();
593 onOpenList();
594 }
595 : onOpenPullRequest;
596 const element = opensList ? (
597 <button type="button" />
598 ) : (
599 <a href={url} target="_blank" rel="noopener noreferrer" />
600 );
601 const control = useRender({
602 render,
603 props: {
604 render: element,
605 "aria-label": presentation.label,
606 onPointerDown: (event: MouseEvent<HTMLElement>) => event.stopPropagation(),
607 onClick,
608 },
609 });
610 return (
611 <ThreadLinkBadge
612 key={opensList ? "list" : "link"}
613 control={control}
614 Icon={presentation.Icon}
615 toneClassName={presentation.toneClassName}
616 text={presentation.text}
617 side={side}
618 >
619 {pullRequests.some((link) => link.source !== "stack-dismissed") ? (
620 <ThreadPullRequestsMiniList
621 environmentId={environmentId}
622 projectId={projectId}
623 pullRequests={pullRequests}
624 onOpenPullRequest={onOpenPullRequest}
625 onShowAll={onOpenList}
626 />
627 ) : number !== undefined && url !== undefined ? (
628 <ul className="flex flex-col gap-1">
629 <ThreadPullRequestMiniListItem
630 number={number}
631 url={url}
632 title={status?.tooltipTitle ?? presentation.label}
633 presentation={presentation}
634 onOpenPullRequest={onOpenPullRequest}
635 />
636 </ul>
637 ) : null}
638 </ThreadLinkBadge>
639 );
640}
641
642type ThreadLinkBadgeSide = "top" | "right";
643
644export function ThreadLinkBadge({
645 control,
646 Icon,
647 toneClassName,
648 text,
649 side = "top",
650 children,
651}: {
652 control: ReactElement;
653 Icon: ComponentType<{ className?: string; "aria-hidden"?: boolean }>;
654 toneClassName: string;
655 text: string | number;
656 side?: ThreadLinkBadgeSide | undefined;
657 children: ReactNode;
658}) {
659 return (
660 // The shared popup renders at the app root, so a right-click in it never reaches the row.
661 <SharedTooltipTrigger
662 render={control}
663 side={side}
664 {...(side === "right" ? { align: "start" as const } : {})}
665 sideOffset={0}
666 variant="glass"
667 className="w-80 max-w-[calc(100vw-2rem)] text-left whitespace-normal"
668 label={
669 <div className="-mx-1 max-h-[calc(var(--available-height)-0.5rem-2px)] overflow-y-auto overscroll-contain">
670 {children}
671 </div>
672 }
673 >
674 <span className={cn("contents font-normal text-xs tabular-nums", toneClassName)}>
675 <Icon aria-hidden className="size-3 shrink-0" />
676 <span className="max-w-16 truncate">{text}</span>
677 </span>
678 </SharedTooltipTrigger>
679 );
680}
681
682// Hover previews stay short: rendering hundreds of rows froze the page and
683// filled the screen. The full list lives in the Linked items tab.
684export const LINKED_ITEMS_PREVIEW_LIMIT = 8;
685
686export function LinkedItemsOverflow({
687 hidden,
688 onShowAll,
689}: {
690 hidden: number;
691 onShowAll?: (() => void) | undefined;
692}) {
693 if (hidden <= 0) return null;
694 if (!onShowAll) {
695 return (
696 <div className="px-1 pt-1 text-muted-foreground">
697 <T>
698 +<Var>{hidden}</Var> more
699 </T>
700 </div>
701 );
702 }
703 return (
704 <Button
705 variant="ghost-muted"
706 size="xs"
707 className="mt-1 w-full justify-start"
708 onPointerDown={(event) => event.stopPropagation()}
709 onClick={(event) => {
710 event.preventDefault();
711 event.stopPropagation();
712 onShowAll();
713 }}
714 >
715 <T>
716 +<Var>{hidden}</Var> more in Linked items
717 </T>
718 </Button>
719 );
720}
721
722export function ThreadPullRequestsMiniList({
723 environmentId,
724 projectId,
725 pullRequests,
726 onOpenPullRequest,
727 onShowAll,
728}: {
729 environmentId: EnvironmentId;
730 projectId: ProjectId | null;
731 pullRequests: ReadonlyArray<ThreadPullRequestLink>;
732 onOpenPullRequest?: (event: MouseEvent<HTMLAnchorElement>, url: string) => void;
733 onShowAll?: (() => void) | undefined;
734}) {
735 const lines = pullRequestListLines(resolveThreadPullRequestChains(pullRequests));
736 if (lines.length === 0) return null;
737 return (
738 <>
739 <ul className="flex flex-col gap-1">
740 {lines.slice(0, LINKED_ITEMS_PREVIEW_LIMIT).map((line) => (
741 <LinkedPullRequestMiniListItem
742 key={`${line.link.host}/${line.link.repository}#${line.link.number}`}
743 environmentId={environmentId}
744 projectId={projectId}
745 line={line}
746 onOpenPullRequest={onOpenPullRequest}
747 />
748 ))}
749 </ul>
750 <LinkedItemsOverflow
751 hidden={lines.length - LINKED_ITEMS_PREVIEW_LIMIT}
752 onShowAll={onShowAll}
753 />
754 </>
755 );
756}
757
758function LinkedPullRequestMiniListItem({
759 environmentId,
760 projectId,
761 line,
762 onOpenPullRequest,
763}: {
764 environmentId: EnvironmentId;
765 projectId: ProjectId | null;
766 line: ReturnType<typeof pullRequestListLines>[number];
767 onOpenPullRequest: ((event: MouseEvent<HTMLAnchorElement>, url: string) => void) | undefined;
768}) {
769 const pr = useLinkedPullRequestStatus(environmentId, projectId, line.link)?.pr ?? null;
770 return (
771 <ThreadPullRequestMiniListItem
772 number={line.link.number}
773 url={line.link.url}
774 title={pr?.title ?? line.link.repository}
775 presentation={
776 pr === null
777 ? null
778 : resolvePullRequestState({ state: pr.state, isDraft: pr.isDraft ?? false })
779 }
780 depth={line.depth}
781 onOpenPullRequest={onOpenPullRequest}
782 >
783 {line.stack ? (
784 <span className="ml-auto shrink-0 pl-1 text-3xs">
785 {line.stack.kind === "native" ? (
786 <T context="a native stack of pull requests">stack</T>
787 ) : (
788 <T context="a chain of pull requests based on each other">chain</T>
789 )}{" "}
790 · {line.stack.size}
791 </span>
792 ) : null}
793 </ThreadPullRequestMiniListItem>
794 );
795}
796
797function ThreadPullRequestMiniListItem({
798 number,
799 url,
800 title,
801 presentation,
802 depth = 0,
803 onOpenPullRequest,
804 children,
805}: {
806 number: number;
807 url: string;
808 title: string;
809 presentation: Pick<ThreadPullRequestBadgePresentation, "Icon" | "toneClassName"> | null;
810 depth?: number;
811 onOpenPullRequest?: ((event: MouseEvent<HTMLAnchorElement>, url: string) => void) | undefined;
812 children?: ReactNode;
813}) {
814 const Icon = presentation?.Icon ?? PullRequestGlyph.pullRequest;
815 const content = (
816 <>
817 <Icon
818 aria-hidden
819 className={cn("size-3 shrink-0", presentation?.toneClassName ?? "stroke-muted-foreground")}
820 />
821 <span className="shrink-0 font-mono tabular-nums">#{number}</span>
822 <span className="min-w-0 truncate text-foreground/75">{title}</span>
823 {children}
824 </>
825 );
826 return (
827 <li style={{ paddingLeft: `${Math.min(depth, 3) * 0.75}rem` }}>
828 {onOpenPullRequest ? (
829 <a
830 href={url}
831 target="_blank"
832 rel="noopener noreferrer"
833 className="flex min-w-0 items-center gap-2 rounded-sm px-1 py-1 hover:bg-accent focus-visible:bg-accent focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring"
834 onPointerDown={(event) => event.stopPropagation()}
835 onClick={(event) => onOpenPullRequest(event, url)}
836 >
837 {content}
838 </a>
839 ) : (
840 <div className="flex min-w-0 items-center gap-2">{content}</div>
841 )}
842 </li>
843 );
844}
845
846export function prStatusIndicator(
847 pr: ThreadPr,
848 provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
849 resolve: MessageResolver = m,
850): PrStatusIndicator | null {
851 if (!pr) return null;
852 const term = changeRequestTermKind(sourceControlClients.get(provider?.kind).changeRequest);
853 const state = resolvePullRequestState({ state: pr.state, isDraft: pr.isDraft === true }, resolve);
854 const { label, tooltipLead } = prStatusLabels(
855 pr.state === "open" && pr.isDraft === true ? "draft" : pr.state,
856 term,
857 pr.number,
858 resolve,
859 );
860 return {
861 label,
862 colorClass: state.toneClassName,
863 Icon: state.Icon,
864 tooltip: resolve(msg`${{ tooltipLead }}: ${{ title: pr.title }}`),
865 tooltipLead,
866 tooltipTitle: pr.title,
867 url: pr.url,
868 };
869}
870
871export function ChangeRequestStatusIcon({
872 state,
873 isDraft = false,
874 className,
875}: Pick<NonNullable<ThreadPr>, "state"> & {
876 readonly isDraft?: boolean | undefined;
877 readonly className?: string | undefined;
878}) {
879 const presentation = resolvePullRequestState({ state, isDraft });
880 return <presentation.Icon className={className} />;
881}
882
883function PrStatusTooltipContent({ status }: { status: PrStatusIndicator }) {
884 return (
885 <span className="flex max-w-[min(34rem,calc(100vw-2rem))] items-stretch overflow-hidden whitespace-nowrap">
886 <span className="shrink-0 pr-2 font-medium">{status.tooltipLead}</span>
887 <span className="min-h-4 shrink-0 border-border/70 border-l" aria-hidden="true" />
888 <span className="min-w-0 truncate pl-2">{status.tooltipTitle}</span>
889 </span>
890 );
891}
892
893export function resolveDisplayedThreadPr(input: {
894 threadBranch: string | null;
895 gitStatus: VcsStatusResult | null;
896 linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
897 linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
898 pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
899}): ThreadPr | null {
900 const { threadBranch, gitStatus, linkedPullRequest, linkedPullRequestStatus } = input;
901 if (linkedPullRequest != null) {
902 return linkedPullRequestStatus?.pr ?? null;
903 }
904 if (
905 threadBranch !== null &&
906 gitStatus !== null &&
907 gitStatus.refName === threadBranch &&
908 gitStatus.pr?.state === "open" &&
909 !isThreadPullRequestDismissed(input.pullRequests ?? [], gitStatus.pr.url)
910 ) {
911 return gitStatus.pr;
912 }
913
914 return null;
915}
916
917export function resolveDisplayedThreadPrProvider(input: {
918 threadBranch: string | null;
919 gitStatus: VcsStatusResult | null;
920 linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
921 linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
922}): VcsStatusResult["sourceControlProvider"] | undefined {
923 const { gitStatus, linkedPullRequest, linkedPullRequestStatus } = input;
924 if (linkedPullRequest != null) {
925 return linkedPullRequestStatus?.sourceControlProvider;
926 }
927 if (resolveDisplayedThreadPr(input) !== null) {
928 return gitStatus?.sourceControlProvider;
929 }
930
931 return undefined;
932}
933
934export function terminalStatusFromRunningIds(
935 runningTerminalIds: ReadonlyArray<string>,
936 resolve: MessageResolver = m,
937): TerminalStatusIndicator | null {
938 if (runningTerminalIds.length === 0) {
939 return null;
940 }
941 return {
942 label: resolve(msg("Terminal process running")),
943 colorClass: "text-teal-600 dark:text-teal-300/90",
944 pulse: true,
945 };
946}
947
948function synchronizeTerminalPulse(event: AnimationEvent<SVGSVGElement>) {
949 if (event.animationName !== "status-pulse") return;
950
951 for (const animation of event.currentTarget.getAnimations()) {
952 if ("animationName" in animation && animation.animationName === "status-pulse") {
953 animation.startTime = 0;
954 }
955 }
956}
957
958export function ThreadTerminalStatusButton({
959 threadRef,
960 terminalIds,
961 onThreadActivate,
962}: {
963 threadRef: ScopedThreadRef;
964 terminalIds: readonly string[];
965 onThreadActivate: (threadRef: ScopedThreadRef) => void;
966}) {
967 const gt = useGT();
968 const messages = useMessages();
969 const terminalId = terminalIds[0];
970 if (terminalId === undefined) return null;
971 const status = terminalStatusFromRunningIds(terminalIds, messages);
972 const label = gt`${plural(
973 { count: terminalIds.length },
974 {
975 one: part`${{ count: terminalIds.length }} terminal process running. Open terminal`,
976 other: part`${{ count: terminalIds.length }} terminal processes running. Open terminal`,
977 },
978 )}`;
979 return (
980 <SharedTooltipTrigger
981 render={
982 <button
983 type="button"
984 aria-label={label}
985 data-testid={`sidebar-terminal-status-${threadRef.threadId}`}
986 className={cn(
987 "inline-flex shrink-0 cursor-pointer items-center justify-center rounded-sm outline-none hover:opacity-80 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
988 status?.colorClass,
989 )}
990 onPointerDown={(event) => event.stopPropagation()}
991 onKeyDown={(event) => event.stopPropagation()}
992 onClick={(event) => {
993 event.preventDefault();
994 event.stopPropagation();
995 revealThreadTerminal(threadRef, terminalId);
996 onThreadActivate(threadRef);
997 }}
998 />
999 }
1000 label={label}
1001 >
1002 <TerminalIcon
1003 className="size-3.5 motion-safe:animate-status-pulse"
1004 onAnimationStart={synchronizeTerminalPulse}
1005 />
1006 </SharedTooltipTrigger>
1007 );
1008}
1009
1010export function ThreadWorktreeIndicator({
1011 thread,
1012}: {
1013 thread: Pick<SidebarThreadSummary, "id" | "branch" | "worktreePath">;
1014}) {
1015 const gt = useGT();
1016 const worktreePath = thread.worktreePath?.trim();
1017 if (!worktreePath) {
1018 return null;
1019 }
1020
1021 const displayPath = formatWorktreePathForDisplay(worktreePath);
1022 const tooltip = thread.branch
1023 ? gt`Worktree: ${{ path: displayPath }} (${{ branch: thread.branch }})`
1024 : gt`Worktree: ${{ path: displayPath }}`;
1025
1026 return (
1027 <SharedTooltipTrigger
1028 render={
1029 <span
1030 role="img"
1031 aria-label={tooltip}
1032 data-testid={`thread-worktree-${thread.id}`}
1033 className="inline-flex items-center justify-center"
1034 />
1035 }
1036 side="top"
1037 label={tooltip}
1038 >
1039 <FolderGit2Icon className="size-3.5 shrink-0 text-icon-muted" />
1040 </SharedTooltipTrigger>
1041 );
1042}
1043
1044function ThreadStatusLabel({
1045 status,
1046 compact = false,
1047}: {
1048 status: ThreadStatusPill;
1049 compact?: boolean;
1050}) {
1051 const m = useMessages();
1052 const label = m(status.label);
1053 if (compact) {
1054 return (
1055 <SharedTooltipTrigger
1056 render={
1057 <span
1058 role="img"
1059 aria-label={label}
1060 className={`inline-flex size-3.5 shrink-0 items-center justify-center ${status.colorClass}`}
1061 />
1062 }
1063 label={label}
1064 >
1065 <span
1066 className={`size-[9px] rounded-full ${status.dotClass} ${
1067 status.pulse ? "motion-safe:animate-status-pulse" : ""
1068 }`}
1069 />
1070 </SharedTooltipTrigger>
1071 );
1072 }
1073
1074 return (
1075 <SharedTooltipTrigger
1076 render={
1077 <span
1078 role="img"
1079 aria-label={label}
1080 className={`inline-flex items-center gap-1 text-3xs ${status.colorClass}`}
1081 />
1082 }
1083 label={label}
1084 >
1085 <span
1086 className={`h-1.5 w-1.5 rounded-full ${status.dotClass} ${
1087 status.pulse ? "motion-safe:animate-status-pulse" : ""
1088 }`}
1089 />
1090 <span className="hidden md:inline">{label}</span>
1091 </SharedTooltipTrigger>
1092 );
1093}
1094
1095export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummary }) {
1096 const gt = useGT();
1097 const m = useMessages();
1098 const { leaseLiveStatus, rowRef } = useSidebarRowSubscriptionLease(false);
1099 // A new ref callback would detach and reattach the row, and each reattach sets lease state.
1100 const statusRef = useStableCallback((node: HTMLSpanElement | null) =>
1101 rowRef(node?.parentElement ?? null),
1102 );
1103 const threadRef = scopeThreadRef(thread.environmentId, thread.id);
1104 const localLastVisitedAt = useUiStateStore(
1105 (state) => state.threadLastVisitedAtById[scopedThreadKey(threadRef)],
1106 );
1107 const lastVisitedAt = resolveThreadLastVisitedAt(thread.lastVisitedAt, localLastVisitedAt);
1108 const threadProject = useProject(scopeProjectRef(thread.environmentId, thread.projectId));
1109 const threadProjectCwd = threadProject?.workspaceRoot ?? null;
1110 const gitCwd = thread.worktreePath ?? threadProjectCwd;
1111 const linkedPullRequest = useLinkedThreadPullRequest(
1112 thread.environmentId,
1113 thread.linkedPullRequest,
1114 leaseLiveStatus,
1115 thread.pullRequests,
1116 thread.branchPullRequest,
1117 thread.projectId,
1118 );
1119 const gitStatus = useEnvironmentQuery(
1120 leaseLiveStatus &&
1121 thread.linkedPullRequest == null &&
1122 (thread.branch != null || thread.worktreePath !== null) &&
1123 gitCwd !== null
1124 ? vcsEnvironment.status({
1125 environmentId: thread.environmentId,
1126 input: { cwd: gitCwd, includeRemote: false },
1127 })
1128 : null,
1129 );
1130 const visibleGitStatus = useRetainedValue(
1131 JSON.stringify([thread.environmentId, gitCwd]),
1132 gitStatus.data,
1133 );
1134 const displayedPrInput = {
1135 threadBranch: thread.branch,
1136 gitStatus: visibleGitStatus,
1137 linkedPullRequest: thread.linkedPullRequest,
1138 linkedPullRequestStatus: linkedPullRequest,
1139 pullRequests: thread.pullRequests,
1140 };
1141 const pr = linkedPullRequest?.pr ?? resolveDisplayedThreadPr(displayedPrInput);
1142 const prStatus = prStatusIndicator(
1143 pr,
1144 linkedPullRequest?.sourceControlProvider ?? resolveDisplayedThreadPrProvider(displayedPrInput),
1145 m,
1146 );
1147 const threadStatus = resolveThreadStatusPill({
1148 thread: {
1149 ...thread,
1150 lastVisitedAt,
1151 },
1152 });
1153
1154 const supportsMultiplePullRequests = useSupportsMultiplePullRequests(thread.environmentId);
1155 const pendingLink =
1156 pr === null && supportsMultiplePullRequests
1157 ? resolveThreadCurrentPullRequestLink(thread.pullRequests)
1158 : null;
1159
1160 return (
1161 <span
1162 ref={statusRef}
1163 className={
1164 prStatus || threadStatus ? "inline-flex shrink-0 items-center gap-1.5" : "contents"
1165 }
1166 >
1167 {prStatus && pr ? (
1168 <SharedTooltipTrigger
1169 render={
1170 <span
1171 aria-label={prStatus.tooltip}
1172 className={`inline-flex items-center justify-center ${prStatus.colorClass}`}
1173 />
1174 }
1175 label={
1176 <>
1177 <PrStatusTooltipContent status={prStatus} />
1178 </>
1179 }
1180 >
1181 <ChangeRequestStatusIcon state={pr.state} isDraft={pr.isDraft} className="size-3" />
1182 </SharedTooltipTrigger>
1183 ) : null}
1184 {pendingLink ? (
1185 <PullRequestGlyph.pullRequest
1186 className="size-3 text-muted-foreground"
1187 aria-label={gt`${select(
1188 { term: changeRequestTermKind(changeRequestTerminologyForUrl(pendingLink.url)) },
1189 {
1190 mr: "MR",
1191 cr: "change request",
1192 other: "PR",
1193 },
1194 )} #${{ number: pendingLink.number }}, status pending`}
1195 />
1196 ) : null}
1197 {threadStatus ? <ThreadStatusLabel status={threadStatus} /> : null}
1198 </span>
1199 );
1200}
1201
1202export function ThreadRowTrailingStatus({ thread }: { thread: SidebarThreadSummary }) {
1203 const gt = useGT();
1204 const m = useMessages();
1205 const runningTerminalIds = useThreadRunningTerminalIds({
1206 environmentId: thread.environmentId,
1207 threadId: thread.id,
1208 });
1209 const environment = useEnvironment(thread.environmentId);
1210 const primaryEnvironmentId = usePrimaryEnvironmentId();
1211 const isRemoteThread = thread.environmentId !== primaryEnvironmentId;
1212 const remoteEnvLabel = environment?.label ?? null;
1213 const threadEnvironmentLabel = isRemoteThread
1214 ? (remoteEnvLabel ?? gt({ context: "machine location" })`Remote`)
1215 : null;
1216 const remoteMachine = resolveEnvironmentMachineKind(environment?.serverConfig ?? null);
1217 const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds, m);
1218
1219 if (!terminalStatus && !isRemoteThread) {
1220 return null;
1221 }
1222
1223 return (
1224 <span className="inline-flex shrink-0 items-center gap-1.5">
1225 {terminalStatus ? (
1226 <SharedTooltipTrigger
1227 render={
1228 <span
1229 role="img"
1230 aria-label={terminalStatus.label}
1231 className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
1232 />
1233 }
1234 label={terminalStatus.label}
1235 >
1236 <TerminalIcon
1237 className={`size-3 ${terminalStatus.pulse ? "motion-safe:animate-status-pulse" : ""}`}
1238 onAnimationStart={synchronizeTerminalPulse}
1239 />
1240 </SharedTooltipTrigger>
1241 ) : null}
1242 {isRemoteThread ? (
1243 <SharedTooltipTrigger
1244 render={
1245 <span
1246 aria-label={threadEnvironmentLabel ?? gt({ context: "machine location" })`Remote`}
1247 className="inline-flex items-center justify-center"
1248 />
1249 }
1250 label={threadEnvironmentLabel}
1251 >
1252 <EnvironmentMachineIcon
1253 kind={remoteMachine}
1254 className="size-3 text-muted-foreground/60"
1255 />
1256 </SharedTooltipTrigger>
1257 ) : null}
1258 </span>
1259 );
1260}
1261
1262function settledPrHoverColorClass(state: ThreadPullRequestBadge["state"]): string {
1263 switch (state) {
1264 case "draft":
1265 return "group-hover/sidebar-row:text-zinc-500 dark:group-hover/sidebar-row:text-zinc-400/80";
1266 case "open":
1267 return "group-hover/sidebar-row:text-emerald-600 dark:group-hover/sidebar-row:text-emerald-300/90";
1268 case "merged":
1269 return "group-hover/sidebar-row:text-violet-600 dark:group-hover/sidebar-row:text-violet-300/90";
1270 case "closed":
1271 return "group-hover/sidebar-row:text-red-600 dark:group-hover/sidebar-row:text-red-300/90";
1272 }
1273}
1274
1275// Search rows are already buttons, so this renders the sidebar badge's look without its controls.
1276export function ThreadSearchPullRequestNumber({
1277 thread,
1278 query,
1279 enabled = true,
1280 settled = false,
1281}: {
1282 thread: SidebarThreadSummary;
1283 query: string;
1284 enabled?: boolean;
1285 settled?: boolean;
1286}) {
1287 const matched = pullRequestMatchesSearchQuery(thread, query);
1288 const supportsMultiplePullRequests = useSupportsMultiplePullRequests(thread.environmentId);
1289 const linked = useLinkedThreadPullRequest(
1290 thread.environmentId,
1291 thread.linkedPullRequest,
1292 enabled && matched,
1293 thread.pullRequests,
1294 thread.branchPullRequest,
1295 thread.projectId,
1296 );
1297 const m = useMessages();
1298 const badge = useSharedThreadPullRequestBadge(
1299 thread.environmentId,
1300 thread.projectId,
1301 matched && supportsMultiplePullRequests ? thread.pullRequests : undefined,
1302 );
1303 if (!matched) return null;
1304 const current = supportsMultiplePullRequests
1305 ? resolveThreadCurrentPullRequestLink(thread.pullRequests)
1306 : null;
1307 const pr = linked?.pr ?? null;
1308 // Stored references already carry a number, so the badge shows before PR details load.
1309 const stored =
1310 current ??
1311 [thread.linkedPullRequest, thread.branchPullRequest].find(
1312 (reference) =>
1313 reference != null && pullRequestMatchesSearchQuery({ linkedPullRequest: reference }, query),
1314 );
1315 const presentation = resolveThreadPullRequestBadgePresentation(
1316 {
1317 badge,
1318 number: pr?.number ?? stored?.number,
1319 url: pr?.url ?? stored?.url,
1320 status: prStatusIndicator(pr, linked?.sourceControlProvider, m),
1321 },
1322 m,
1323 );
1324 if (presentation === null) return null;
1325 const aggregate = badge !== null && (badge.kind === "stack" || badge.others > 0);
1326 const state = aggregate
1327 ? badge.state
1328 : pr === null
1329 ? null
1330 : pr.state === "open" && pr.isDraft
1331 ? "draft"
1332 : pr.state;
1333 return (
1334 <span
1335 aria-label={presentation.label}
1336 className={cn(
1337 "inline-flex shrink-0 items-center gap-0.5 text-xs tabular-nums",
1338 settled
1339 ? cn("text-secondary-label transition-colors", state && settledPrHoverColorClass(state))
1340 : presentation.toneClassName,
1341 )}
1342 >
1343 {/* text-current opts out of the command palette's muted icon color. */}
1344 <presentation.Icon aria-hidden className="size-3 shrink-0 text-current" />
1345 <span>{presentation.text}</span>
1346 </span>
1347 );
1348}