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

ThreadStatusIndicators.tsx

885 lines28.7 KB

1import {
2 scopeProjectRef,
3 scopedThreadKey,
4 scopeThreadRef,
5} from "@t3tools/client-runtime/environment";
6import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests";
7import { useStableCallback } from "~/hooks/useStableCallback";
8​
9import { pullRequestDetailToVcsStatus } from "@t3tools/client-runtime/state/pull-requests";
10import {
11 resolveEnvironmentMachineKind,
12 type EnvironmentId,
13 type ScopedThreadRef,
14 type ThreadLinkedPullRequest,
15 type ThreadPullRequestLink,
16 type VcsStatusResult,
17} from "@t3tools/contracts";
18import { FolderGit2Icon, TerminalIcon } from "lucide-react";
19import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments";
20import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
21import { useProject } from "../state/entities";
22import {
23 pullRequestListLines,
24 resolveThreadCurrentPullRequestLink,
25 resolveThreadPullRequestBadge,
26 resolveThreadPullRequestChains,
27 type ThreadPullRequestBadge,
28 visibleThreadPullRequests,
29} from "@t3tools/client-runtime/thread-pull-requests";
30import { useRender } from "@base-ui/react/use-render";
31import { type ReactNode, type AnimationEvent, type MouseEvent, type ReactElement } from "react";
32import { cn } from "../lib/utils";
33import { revealThreadTerminal } from "../lib/revealThreadTerminal";
34​
35import { useEnvironmentQuery } from "../state/query";
36import { linkedPullRequestDetailAtom, useSharedPullRequestSummary } from "../state/pullRequests";
37import { useThreadRunningTerminalIds } from "../state/terminalSessions";
38import { vcsEnvironment } from "../state/vcs";
39import { useUiStateStore } from "../uiStateStore";
40import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
41import {
42 pullRequestMatchesSearchQuery,
43 resolveThreadLastVisitedAt,
44 resolveThreadStatusPill,
45 type ThreadStatusPill,
46 useRetainedValue,
47 useSidebarRowSubscriptionLease,
48} from "./Sidebar.logic";
49​
50import type { SidebarThreadSummary } from "../types";
51import { formatWorktreePathForDisplay } from "../worktreeCleanup";
52import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
53import {
54 PULL_REQUEST_STATE_PRESENTATION,
55 PullRequestGlyph,
56 type PullRequestGlyphIcon,
57} from "./pullRequest/pullRequestIcons";
58import { resolvePullRequestState } from "./pullRequest/pullRequestPresentation";
59​
60export interface PrStatusIndicator {
61 label: string;
62 colorClass: string;
63 Icon: PullRequestGlyphIcon;
64 tooltip: string;
65 tooltipLead: string;
66 tooltipTitle: string;
67 url: string;
69​
70export interface TerminalStatusIndicator {
71 label: "Terminal process running";
72 colorClass: string;
73 pulse: boolean;
75​
76export type ThreadPr = VcsStatusResult["pr"];
77​
78export interface LinkedThreadPullRequestStatus {
79 readonly pr: NonNullable<ThreadPr>;
80 readonly sourceControlProvider: NonNullable<VcsStatusResult["sourceControlProvider"]>;
82​
83export function useLinkedThreadPullRequest(
84 environmentId: EnvironmentId | null,
85 linkedPullRequest: ThreadLinkedPullRequest | null | undefined,
86 enabled = true,
87 pullRequests?: ReadonlyArray<ThreadPullRequestLink>,
88 branchPullRequest?: ThreadLinkedPullRequest | null,
89): LinkedThreadPullRequestStatus | null {
90 const supportsLinks = useSupportsMultiplePullRequests(environmentId);
91 const current = supportsLinks ? resolveThreadCurrentPullRequestLink(pullRequests ?? []) : null;
92 const currentStatus = current === null ? null : linkedPullRequestSnapshotStatus(current);
93 const fallback =
94 current === null ? ((!supportsLinks ? linkedPullRequest : null) ?? branchPullRequest) : null;
95 // Preserve reference identity so sidebar renders do not touch the summary cache.
96 const reference = fallback == null ? null : linkedPullRequestReference(fallback);
97 // Mounted for its answers, which land in the shared summary read below.
98 useEnvironmentQuery(
99 !enabled || environmentId === null || reference === null
100 ? null
101 : linkedPullRequestDetailAtom({ environmentId, input: reference }),
102 );
103 const detail = useSharedPullRequestSummary(environmentId, reference);
104​
105 if (current !== null) return currentStatus;
106 return detail === null
107 ? null
108 : {
109 pr: pullRequestDetailToVcsStatus(detail),
110 sourceControlProvider: {
111 kind: detail.provider,
112 name: sourceControlClients.get(detail.provider).label,
113 baseUrl: "",
114 },
115 };
117​
118function linkedPullRequestReference(fallback: ThreadLinkedPullRequest) {
119 const host = sourceControlClients.parseChangeRequestUrl(fallback.url)?.link.host;
120 return { ...fallback, ...(host === undefined ? {} : { host }) };
122​
123function changeRequestTerminologyForUrl(url: string | undefined) {
124 const host = url === undefined ? null : sourceControlClients.findByChangeRequestUrl(url);
125 return (host ?? sourceControlClients.get(undefined)).changeRequest;
127​
128export function linkedPullRequestSnapshotStatus(
129 link: ThreadPullRequestLink,
130): LinkedThreadPullRequestStatus | null {
131 const snapshot = link.snapshot;
132 if (snapshot === null) return null;
133 const kind = (
134 sourceControlClients.findByChangeRequestUrl(link.url) ?? sourceControlClients.get(undefined)
135 ).kind;
136 return {
137 pr: {
138 number: link.number,
139 url: link.url,
140 title: snapshot.title,
141 state: snapshot.state,
142 isDraft: snapshot.isDraft,
143 headRef: snapshot.headBranch,
144 baseRef: snapshot.baseBranch,
145 ...(snapshot.updatedAt === null ? {} : { updatedAt: snapshot.updatedAt }),
146 },
147 sourceControlProvider: { kind, name: kind, baseUrl: "" },
148 };
150​
151export {
152 resolveThreadPullRequestBadge,
153 type ThreadPullRequestBadge,
154} from "@t3tools/client-runtime/thread-pull-requests";
155​
156export interface ThreadPullRequestBadgePresentation {
157 readonly Icon: PullRequestGlyphIcon;
158 readonly toneClassName: string;
159 readonly label: string;
160 readonly text: string | number;
162​
163function resolveThreadPullRequestBadgePresentation({
164 badge,
165 number,
166 url,
167 status,
168}: {
169 readonly badge: ThreadPullRequestBadge | null;
170 readonly number?: number | undefined;
171 readonly url?: string | undefined;
172 readonly status: PrStatusIndicator | null;
173}): ThreadPullRequestBadgePresentation | null {
174 const terminology = changeRequestTerminologyForUrl(url);
175 if (badge?.kind === "stack") {
176 const aggregate = PULL_REQUEST_STATE_PRESENTATION[badge.state];
177 return {
178 Icon: PullRequestGlyph.stack,
179 toneClassName: aggregate.toneClassName,
180 label: `Stack of ${badge.layers} ${terminology.plural}, ${aggregate.label.toLowerCase()}`,
181 text: badge.layers,
182 };
183 }
184 if (number === undefined || url === undefined) return null;
185​
186 const tooltip = status?.tooltip ?? `${terminology.shortLabel} #${number}, status pending`;
187 if (badge?.kind === "pull-request" && badge.others > 0) {
188 const aggregate = PULL_REQUEST_STATE_PRESENTATION[badge.state];
189 return {
190 Icon: aggregate.Icon,
191 toneClassName: aggregate.toneClassName,
192 label: `${tooltip}, and ${badge.others} more linked; overall ${aggregate.label.toLowerCase()}`,
193 text: `+${badge.others + 1}`,
194 };
195 }
196 return {
197 Icon: status?.Icon ?? PullRequestGlyph.pullRequest,
198 toneClassName: status?.colorClass ?? "text-muted-foreground",
199 label: tooltip,
200 text: number,
201 };
203​
204export function ThreadPullRequestBadgeControl({
205 render,
206 badge,
207 pullRequests,
208 number,
209 url,
210 status,
211 onOpenList,
212 onOpenPullRequest,
213}: {
214 render: ReactElement<{ render?: useRender.RenderProp }>;
215 badge: ThreadPullRequestBadge | null;
216 pullRequests: ReadonlyArray<ThreadPullRequestLink>;
217 number?: number | undefined;
218 url?: string | undefined;
219 status: PrStatusIndicator | null;
220 onOpenList: () => void;
221 onOpenPullRequest: (event: MouseEvent<HTMLElement>, url?: string) => void;
222}) {
223 const presentation = resolveThreadPullRequestBadgePresentation({ badge, number, url, status });
224 if (presentation === null) return null;
225 return (
226 <PullRequestBadge
227 render={render}
228 presentation={presentation}
229 opensList={badge !== null && (badge.kind === "stack" || badge.others > 0)}
230 url={url}
231 number={number}
232 status={status}
233 pullRequests={pullRequests}
234 onOpenList={onOpenList}
235 onOpenPullRequest={onOpenPullRequest}
236 />
237 );
239​
240function PullRequestBadge({
241 render,
242 presentation,
243 opensList,
244 url,
245 number,
246 status,
247 pullRequests,
248 onOpenList,
249 onOpenPullRequest,
250}: {
251 render: ReactElement<{ render?: useRender.RenderProp }>;
252 presentation: NonNullable<ReturnType<typeof resolveThreadPullRequestBadgePresentation>>;
253 opensList: boolean;
254 url: string | undefined;
255 number: number | undefined;
256 status: PrStatusIndicator | null;
257 pullRequests: ReadonlyArray<ThreadPullRequestLink>;
258 onOpenList: () => void;
259 onOpenPullRequest: (event: MouseEvent<HTMLElement>, url?: string) => void;
260}) {
261 const onClick = opensList
262 ? (event: MouseEvent<HTMLElement>) => {
263 event.preventDefault();
264 event.stopPropagation();
265 onOpenList();
266 }
267 : onOpenPullRequest;
268 const element = opensList ? (
269 <button type="button" />
270 ) : (
271 <a href={url} target="_blank" rel="noopener noreferrer" />
272 );
273 const control = useRender({
274 render,
275 props: {
276 render: element,
277 "aria-label": presentation.label,
278 onPointerDown: (event: MouseEvent<HTMLElement>) => event.stopPropagation(),
279 onClick,
280 },
281 });
282 return (
283 <Tooltip key={opensList ? "list" : "link"}>
284 <TooltipTrigger render={control}>
285 <span
286 className={cn("contents font-normal text-xs tabular-nums", presentation.toneClassName)}
287 >
288 <presentation.Icon aria-hidden className="size-3 shrink-0" />
289 <span className="text-secondary-label">{presentation.text}</span>
290 </span>
291 </TooltipTrigger>
292 <TooltipPopup
293 side="top"
294 sideOffset={0}
295 variant="glass"
296 className="pointer-events-auto w-80 max-w-[calc(100vw-2rem)] text-left whitespace-normal"
297 >
298 <div className="-mx-1 max-h-[calc(var(--available-height)-0.5rem-2px)] overflow-y-auto overscroll-contain">
299 {visibleThreadPullRequests(pullRequests).length > 0 ? (
300 <ThreadPullRequestsMiniList
301 pullRequests={pullRequests}
302 onOpenPullRequest={onOpenPullRequest}
303 />
304 ) : number !== undefined && url !== undefined ? (
305 <ul className="flex flex-col gap-1">
306 <ThreadPullRequestMiniListItem
307 number={number}
308 url={url}
309 title={status?.tooltipTitle ?? presentation.label}
310 presentation={presentation}
311 onOpenPullRequest={onOpenPullRequest}
312 />
313 </ul>
314 ) : null}
315 </div>
316 </TooltipPopup>
317 </Tooltip>
318 );
320​
321export function ThreadPullRequestsMiniList({
322 pullRequests,
323 onOpenPullRequest,
324}: {
325 pullRequests: ReadonlyArray<ThreadPullRequestLink>;
326 onOpenPullRequest?: (event: MouseEvent<HTMLAnchorElement>, url: string) => void;
327}) {
328 const lines = pullRequestListLines(
329 resolveThreadPullRequestChains(visibleThreadPullRequests(pullRequests)),
330 );
331 if (lines.length === 0) return null;
332 return (
333 <ul className="flex flex-col gap-1">
334 {lines.map((line) => {
335 const snapshot = line.link.snapshot;
336 const presentation =
337 snapshot === null
338 ? null
339 : resolvePullRequestState({ state: snapshot.state, isDraft: snapshot.isDraft });
340 return (
341 <ThreadPullRequestMiniListItem
342 key={`${line.link.host}/${line.link.repository}#${line.link.number}`}
343 number={line.link.number}
344 url={line.link.url}
345 title={snapshot?.title ?? line.link.repository}
346 presentation={presentation}
347 depth={line.depth}
348 onOpenPullRequest={onOpenPullRequest}
349 >
350 {line.stack ? (
351 <span className="ml-auto shrink-0 pl-1 text-3xs">
352 {line.stack.kind === "native" ? "stack" : "chain"} · {line.stack.size}
353 </span>
354 ) : null}
355 </ThreadPullRequestMiniListItem>
356 );
357 })}
358 </ul>
359 );
361​
362function ThreadPullRequestMiniListItem({
363 number,
364 url,
365 title,
366 presentation,
367 depth = 0,
368 onOpenPullRequest,
369 children,
370}: {
371 number: number;
372 url: string;
373 title: string;
374 presentation: Pick<ThreadPullRequestBadgePresentation, "Icon" | "toneClassName"> | null;
375 depth?: number;
376 onOpenPullRequest?: ((event: MouseEvent<HTMLAnchorElement>, url: string) => void) | undefined;
377 children?: ReactNode;
378}) {
379 const Icon = presentation?.Icon ?? PullRequestGlyph.pullRequest;
380 const content = (
381 <>
382 <Icon
383 aria-hidden
384 className={cn("size-3 shrink-0", presentation?.toneClassName ?? "stroke-muted-foreground")}
385 />
386 <span className="shrink-0 font-mono tabular-nums">#{number}</span>
387 <span className="min-w-0 truncate text-foreground/75">{title}</span>
388 {children}
389 </>
390 );
391 return (
392 <li style={{ paddingLeft: `${Math.min(depth, 3) * 0.75}rem` }}>
393 {onOpenPullRequest ? (
394 <a
395 href={url}
396 target="_blank"
397 rel="noopener noreferrer"
398 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"
399 onPointerDown={(event) => event.stopPropagation()}
400 onClick={(event) => onOpenPullRequest(event, url)}
401 >
402 {content}
403 </a>
404 ) : (
405 <div className="flex min-w-0 items-center gap-2">{content}</div>
406 )}
407 </li>
408 );
410​
411export function prStatusIndicator(
412 pr: ThreadPr,
413 provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
414): PrStatusIndicator | null {
415 if (!pr) return null;
416 const { shortLabel } = sourceControlClients.get(provider?.kind).changeRequest;
417 const state = resolvePullRequestState({ state: pr.state, isDraft: pr.isDraft === true });
418​
419 const tooltipLead = `${shortLabel} #${pr.number} - ${state.label}`;
420 return {
421 label: `${shortLabel} ${state.label.toLowerCase()}`,
422 colorClass: state.toneClassName,
423 Icon: state.Icon,
424 tooltip: `${tooltipLead}: ${pr.title}`,
425 tooltipLead,
426 tooltipTitle: pr.title,
427 url: pr.url,
428 };
430​
431export function ChangeRequestStatusIcon({
432 state,
433 isDraft = false,
434 className,
435}: Pick<NonNullable<ThreadPr>, "state"> & {
436 readonly isDraft?: boolean | undefined;
437 readonly className?: string | undefined;
438}) {
439 const presentation = resolvePullRequestState({ state, isDraft });
440 return <presentation.Icon className={className} />;
442​
443function PrStatusTooltipContent({ status }: { status: PrStatusIndicator }) {
444 return (
445 <span className="flex max-w-[min(34rem,calc(100vw-2rem))] items-stretch overflow-hidden whitespace-nowrap">
446 <span className="shrink-0 pr-2 font-medium">{status.tooltipLead}</span>
447 <span className="min-h-4 shrink-0 border-border/70 border-l" aria-hidden="true" />
448 <span className="min-w-0 truncate pl-2">{status.tooltipTitle}</span>
449 </span>
450 );
452​
453export function resolveDisplayedThreadPr(input: {
454 threadBranch: string | null;
455 gitStatus: VcsStatusResult | null;
456 linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
457 linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
458}): ThreadPr | null {
459 const { threadBranch, gitStatus, linkedPullRequest, linkedPullRequestStatus } = input;
460 if (linkedPullRequest != null) {
461 return linkedPullRequestStatus?.pr ?? null;
462 }
463 if (
464 threadBranch !== null &&
465 gitStatus !== null &&
466 gitStatus.refName === threadBranch &&
467 gitStatus.pr != null
468 ) {
469 return gitStatus.pr;
470 }
471​
472 return null;
474​
475export function resolveDisplayedThreadPrProvider(input: {
476 threadBranch: string | null;
477 gitStatus: VcsStatusResult | null;
478 linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
479 linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
480}): VcsStatusResult["sourceControlProvider"] | undefined {
481 const { threadBranch, gitStatus, linkedPullRequest, linkedPullRequestStatus } = input;
482 if (linkedPullRequest != null) {
483 return linkedPullRequestStatus?.sourceControlProvider;
484 }
485 if (
486 threadBranch !== null &&
487 gitStatus !== null &&
488 gitStatus.refName === threadBranch &&
489 gitStatus.pr != null
490 ) {
491 return gitStatus.sourceControlProvider;
492 }
493​
494 return undefined;
496​
497export function terminalStatusFromRunningIds(
498 runningTerminalIds: ReadonlyArray<string>,
499): TerminalStatusIndicator | null {
500 if (runningTerminalIds.length === 0) {
501 return null;
502 }
503 return {
504 label: "Terminal process running",
505 colorClass: "text-teal-600 dark:text-teal-300/90",
506 pulse: true,
507 };
509​
510function synchronizeTerminalPulse(event: AnimationEvent<SVGSVGElement>) {
511 if (event.animationName !== "status-pulse") return;
512​
513 for (const animation of event.currentTarget.getAnimations()) {
514 if ("animationName" in animation && animation.animationName === "status-pulse") {
515 animation.startTime = 0;
516 }
517 }
519​
520export function ThreadTerminalStatusButton({
521 threadRef,
522 terminalIds,
523 onThreadActivate,
524}: {
525 threadRef: ScopedThreadRef;
526 terminalIds: readonly string[];
527 onThreadActivate: (threadRef: ScopedThreadRef) => void;
528}) {
529 const terminalId = terminalIds[0];
530 if (terminalId === undefined) return null;
531 const status = terminalStatusFromRunningIds(terminalIds);
532 const label =
533 terminalIds.length === 1
534 ? "1 terminal process running. Open terminal"
535 : `${terminalIds.length} terminal processes running. Open terminal`;
536 return (
537 <Tooltip>
538 <TooltipTrigger
539 render={
540 <button
541 type="button"
542 aria-label={label}
543 data-testid={`sidebar-terminal-status-${threadRef.threadId}`}
544 className={cn(
545 "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",
546 status?.colorClass,
547 )}
548 onPointerDown={(event) => event.stopPropagation()}
549 onKeyDown={(event) => event.stopPropagation()}
550 onClick={(event) => {
551 event.preventDefault();
552 event.stopPropagation();
553 revealThreadTerminal(threadRef, terminalId);
554 onThreadActivate(threadRef);
555 }}
556 />
557 }
558 >
559 <TerminalIcon
560 className="size-3.5 motion-safe:animate-status-pulse"
561 onAnimationStart={synchronizeTerminalPulse}
562 />
563 </TooltipTrigger>
564 <TooltipPopup side="top">{label}</TooltipPopup>
565 </Tooltip>
566 );
568​
569export function ThreadWorktreeIndicator({
570 thread,
571}: {
572 thread: Pick<SidebarThreadSummary, "id" | "branch" | "worktreePath">;
573}) {
574 const worktreePath = thread.worktreePath?.trim();
575 if (!worktreePath) {
576 return null;
577 }
578​
579 const displayPath = formatWorktreePathForDisplay(worktreePath);
580 const tooltip = thread.branch
581 ? `Worktree: ${displayPath} (${thread.branch})`
582 : `Worktree: ${displayPath}`;
583​
584 return (
585 <Tooltip>
586 <TooltipTrigger
587 render={
588 <span
589 role="img"
590 aria-label={tooltip}
591 data-testid={`thread-worktree-${thread.id}`}
592 className="inline-flex items-center justify-center"
593 />
594 }
595 >
596 <FolderGit2Icon className="size-3.5 shrink-0 text-icon-muted" />
597 </TooltipTrigger>
598 <TooltipPopup side="top">{tooltip}</TooltipPopup>
599 </Tooltip>
600 );
602​
603function ThreadStatusLabel({
604 status,
605 compact = false,
606}: {
607 status: ThreadStatusPill;
608 compact?: boolean;
609}) {
610 if (compact) {
611 return (
612 <Tooltip>
613 <TooltipTrigger
614 render={
615 <span
616 role="img"
617 aria-label={status.label}
618 className={`inline-flex size-3.5 shrink-0 items-center justify-center ${status.colorClass}`}
619 />
620 }
621 >
622 <span
623 className={`size-[9px] rounded-full ${status.dotClass} ${
624 status.pulse ? "motion-safe:animate-status-pulse" : ""
625 }`}
626 />
627 </TooltipTrigger>
628 <TooltipPopup side="top">{status.label}</TooltipPopup>
629 </Tooltip>
630 );
631 }
632​
633 return (
634 <Tooltip>
635 <TooltipTrigger
636 render={
637 <span
638 role="img"
639 aria-label={status.label}
640 className={`inline-flex items-center gap-1 text-3xs ${status.colorClass}`}
641 />
642 }
643 >
644 <span
645 className={`h-1.5 w-1.5 rounded-full ${status.dotClass} ${
646 status.pulse ? "motion-safe:animate-status-pulse" : ""
647 }`}
648 />
649 <span className="hidden md:inline">{status.label}</span>
650 </TooltipTrigger>
651 <TooltipPopup side="top">{status.label}</TooltipPopup>
652 </Tooltip>
653 );
655​
656export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummary }) {
657 const { leaseLiveStatus, rowRef } = useSidebarRowSubscriptionLease(false);
658 // A new ref callback would detach and reattach the row, and each reattach sets lease state.
659 const statusRef = useStableCallback((node: HTMLSpanElement | null) =>
660 rowRef(node?.parentElement ?? null),
661 );
662 const threadRef = scopeThreadRef(thread.environmentId, thread.id);
663 const localLastVisitedAt = useUiStateStore(
664 (state) => state.threadLastVisitedAtById[scopedThreadKey(threadRef)],
665 );
666 const lastVisitedAt = resolveThreadLastVisitedAt(thread.lastVisitedAt, localLastVisitedAt);
667 const threadProject = useProject(scopeProjectRef(thread.environmentId, thread.projectId));
668 const threadProjectCwd = threadProject?.workspaceRoot ?? null;
669 const gitCwd = thread.worktreePath ?? threadProjectCwd;
670 const linkedPullRequest = useLinkedThreadPullRequest(
671 thread.environmentId,
672 thread.linkedPullRequest,
673 leaseLiveStatus,
674 );
675 const gitStatus = useEnvironmentQuery(
676 leaseLiveStatus &&
677 thread.linkedPullRequest == null &&
678 (thread.branch != null || thread.worktreePath !== null) &&
679 gitCwd !== null
680 ? vcsEnvironment.status({
681 environmentId: thread.environmentId,
682 input: { cwd: gitCwd, includeRemote: false },
683 })
684 : null,
685 );
686 const visibleGitStatus = useRetainedValue(
687 JSON.stringify([thread.environmentId, gitCwd]),
688 gitStatus.data,
689 );
690 const displayedPrInput = {
691 threadBranch: thread.branch,
692 gitStatus: visibleGitStatus,
693 linkedPullRequest: thread.linkedPullRequest,
694 linkedPullRequestStatus: linkedPullRequest,
695 };
696 const pr = resolveDisplayedThreadPr(displayedPrInput);
697 const prStatus = prStatusIndicator(pr, resolveDisplayedThreadPrProvider(displayedPrInput));
698 const threadStatus = resolveThreadStatusPill({
699 thread: {
700 ...thread,
701 lastVisitedAt,
702 },
703 });
704​
705 const supportsMultiplePullRequests = useSupportsMultiplePullRequests(thread.environmentId);
706 const pendingLink =
707 pr === null && supportsMultiplePullRequests
708 ? resolveThreadCurrentPullRequestLink(thread.pullRequests)
709 : null;
710​
711 return (
712 <span
713 ref={statusRef}
714 className={
715 prStatus || threadStatus ? "inline-flex shrink-0 items-center gap-1.5" : "contents"
716 }
717 >
718 {prStatus && pr ? (
719 <Tooltip>
720 <TooltipTrigger
721 render={
722 <span
723 aria-label={prStatus.tooltip}
724 className={`inline-flex items-center justify-center ${prStatus.colorClass}`}
725 />
726 }
727 >
728 <ChangeRequestStatusIcon state={pr.state} isDraft={pr.isDraft} className="size-3" />
729 </TooltipTrigger>
730 <TooltipPopup side="top">
731 <PrStatusTooltipContent status={prStatus} />
732 </TooltipPopup>
733 </Tooltip>
734 ) : null}
735 {pendingLink ? (
736 <PullRequestGlyph.pullRequest
737 className="size-3 text-muted-foreground"
738 aria-label={`${changeRequestTerminologyForUrl(pendingLink.url).shortLabel} #${pendingLink.number}, status pending`}
739 />
740 ) : null}
741 {threadStatus ? <ThreadStatusLabel status={threadStatus} /> : null}
742 </span>
743 );
745​
746export function ThreadRowTrailingStatus({ thread }: { thread: SidebarThreadSummary }) {
747 const runningTerminalIds = useThreadRunningTerminalIds({
748 environmentId: thread.environmentId,
749 threadId: thread.id,
750 });
751 const environment = useEnvironment(thread.environmentId);
752 const primaryEnvironmentId = usePrimaryEnvironmentId();
753 const isRemoteThread = thread.environmentId !== primaryEnvironmentId;
754 const remoteEnvLabel = environment?.label ?? null;
755 const threadEnvironmentLabel = isRemoteThread ? (remoteEnvLabel ?? "Remote") : null;
756 const remoteMachine = resolveEnvironmentMachineKind(environment?.serverConfig ?? null);
757 const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
758​
759 if (!terminalStatus && !isRemoteThread) {
760 return null;
761 }
762​
763 return (
764 <span className="inline-flex shrink-0 items-center gap-1.5">
765 {terminalStatus ? (
766 <Tooltip>
767 <TooltipTrigger
768 render={
769 <span
770 role="img"
771 aria-label={terminalStatus.label}
772 className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
773 />
774 }
775 >
776 <TerminalIcon
777 className={`size-3 ${terminalStatus.pulse ? "motion-safe:animate-status-pulse" : ""}`}
778 onAnimationStart={synchronizeTerminalPulse}
779 />
780 </TooltipTrigger>
781 <TooltipPopup side="top">{terminalStatus.label}</TooltipPopup>
782 </Tooltip>
783 ) : null}
784 {isRemoteThread ? (
785 <Tooltip>
786 <TooltipTrigger
787 render={
788 <span
789 aria-label={threadEnvironmentLabel ?? "Remote"}
790 className="inline-flex items-center justify-center"
791 />
792 }
793 >
794 <EnvironmentMachineIcon
795 kind={remoteMachine}
796 className="size-3 text-muted-foreground/60"
797 />
798 </TooltipTrigger>
799 <TooltipPopup side="top">{threadEnvironmentLabel}</TooltipPopup>
800 </Tooltip>
801 ) : null}
802 </span>
803 );
805​
806function settledPrHoverColorClass(state: ThreadPullRequestBadge["state"]): string {
807 switch (state) {
808 case "draft":
809 return "group-hover/sidebar-row:text-zinc-500 dark:group-hover/sidebar-row:text-zinc-400/80";
810 case "open":
811 return "group-hover/sidebar-row:text-emerald-600 dark:group-hover/sidebar-row:text-emerald-300/90";
812 case "merged":
813 return "group-hover/sidebar-row:text-violet-600 dark:group-hover/sidebar-row:text-violet-300/90";
814 case "closed":
815 return "group-hover/sidebar-row:text-red-600 dark:group-hover/sidebar-row:text-red-300/90";
816 }
818​
819// Search rows are already buttons, so this renders the sidebar badge's look without its controls.
820export function ThreadSearchPullRequestNumber({
821 thread,
822 query,
823 enabled = true,
824 settled = false,
825}: {
826 thread: SidebarThreadSummary;
827 query: string;
828 enabled?: boolean;
829 settled?: boolean;
830}) {
831 const matched = pullRequestMatchesSearchQuery(thread, query);
832 const supportsMultiplePullRequests = useSupportsMultiplePullRequests(thread.environmentId);
833 const linked = useLinkedThreadPullRequest(
834 thread.environmentId,
835 thread.linkedPullRequest,
836 enabled && matched,
837 thread.pullRequests,
838 thread.branchPullRequest,
839 );
840 if (!matched) return null;
841 const badge = supportsMultiplePullRequests
842 ? resolveThreadPullRequestBadge(thread.pullRequests)
843 : null;
844 const current = supportsMultiplePullRequests
845 ? resolveThreadCurrentPullRequestLink(thread.pullRequests)
846 : null;
847 const pr = linked?.pr ?? null;
848 // Stored references already carry a number, so the badge shows before PR details load.
849 const stored =
850 current ??
851 [thread.linkedPullRequest, thread.branchPullRequest].find(
852 (reference) =>
853 reference != null && pullRequestMatchesSearchQuery({ linkedPullRequest: reference }, query),
854 );
855 const presentation = resolveThreadPullRequestBadgePresentation({
856 badge,
857 number: pr?.number ?? stored?.number,
858 url: pr?.url ?? stored?.url,
859 status: prStatusIndicator(pr, linked?.sourceControlProvider),
860 });
861 if (presentation === null) return null;
862 const aggregate = badge !== null && (badge.kind === "stack" || badge.others > 0);
863 const state = aggregate
864 ? badge.state
865 : pr === null
866 ? null
867 : pr.state === "open" && pr.isDraft
868 ? "draft"
869 : pr.state;
870 return (
871 <span
872 aria-label={presentation.label}
873 className={cn(
874 "inline-flex shrink-0 items-center gap-0.5 text-xs tabular-nums",
875 settled
876 ? cn("text-secondary-label transition-colors", state && settledPrHoverColorClass(state))
877 : presentation.toneClassName,
878 )}
879 >
880 {/* text-current opts out of the command palette's muted icon color. */}
881 <presentation.Icon aria-hidden className="size-3 shrink-0 text-current" />
882 <span>{presentation.text}</span>
883 </span>
884 );