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

ThreadStatusIndicators.tsx

893 lines28.9 KB

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