Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadStatusIndicators.tsx

1,194 lines37.3 KB

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