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

ThreadStatusIndicators.tsx

888 lines28.8 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?.state === "open"
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 { gitStatus, linkedPullRequest, linkedPullRequestStatus } = input;
485 if (linkedPullRequest != null) {
486 return linkedPullRequestStatus?.sourceControlProvider;
487 }
488 if (resolveDisplayedThreadPr(input) !== null) {
489 return gitStatus?.sourceControlProvider;
490 }
491​
492 return undefined;
494​
495export function terminalStatusFromRunningIds(
496 runningTerminalIds: ReadonlyArray<string>,
497): TerminalStatusIndicator | null {
498 if (runningTerminalIds.length === 0) {
499 return null;
500 }
501 return {
502 label: "Terminal process running",
503 colorClass: "text-teal-600 dark:text-teal-300/90",
504 pulse: true,
505 };
507​
508function synchronizeTerminalPulse(event: AnimationEvent<SVGSVGElement>) {
509 if (event.animationName !== "status-pulse") return;
510​
511 for (const animation of event.currentTarget.getAnimations()) {
512 if ("animationName" in animation && animation.animationName === "status-pulse") {
513 animation.startTime = 0;
514 }
515 }
517​
518export function ThreadTerminalStatusButton({
519 threadRef,
520 terminalIds,
521 onThreadActivate,
522}: {
523 threadRef: ScopedThreadRef;
524 terminalIds: readonly string[];
525 onThreadActivate: (threadRef: ScopedThreadRef) => void;
526}) {
527 const terminalId = terminalIds[0];
528 if (terminalId === undefined) return null;
529 const status = terminalStatusFromRunningIds(terminalIds);
530 const label =
531 terminalIds.length === 1
532 ? "1 terminal process running. Open terminal"
533 : `${terminalIds.length} terminal processes running. Open terminal`;
534 return (
535 <Tooltip>
536 <TooltipTrigger
537 render={
538 <button
539 type="button"
540 aria-label={label}
541 data-testid={`sidebar-terminal-status-${threadRef.threadId}`}
542 className={cn(
543 "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",
544 status?.colorClass,
545 )}
546 onPointerDown={(event) => event.stopPropagation()}
547 onKeyDown={(event) => event.stopPropagation()}
548 onClick={(event) => {
549 event.preventDefault();
550 event.stopPropagation();
551 revealThreadTerminal(threadRef, terminalId);
552 onThreadActivate(threadRef);
553 }}
554 />
555 }
556 >
557 <TerminalIcon
558 className="size-3.5 motion-safe:animate-status-pulse"
559 onAnimationStart={synchronizeTerminalPulse}
560 />
561 </TooltipTrigger>
562 <TooltipPopup side="top">{label}</TooltipPopup>
563 </Tooltip>
564 );
566​
567export function ThreadWorktreeIndicator({
568 thread,
569}: {
570 thread: Pick<SidebarThreadSummary, "id" | "branch" | "worktreePath">;
571}) {
572 const worktreePath = thread.worktreePath?.trim();
573 if (!worktreePath) {
574 return null;
575 }
576​
577 const displayPath = formatWorktreePathForDisplay(worktreePath);
578 const tooltip = thread.branch
579 ? `Worktree: ${displayPath} (${thread.branch})`
580 : `Worktree: ${displayPath}`;
581​
582 return (
583 <Tooltip>
584 <TooltipTrigger
585 render={
586 <span
587 role="img"
588 aria-label={tooltip}
589 data-testid={`thread-worktree-${thread.id}`}
590 className="inline-flex items-center justify-center"
591 />
592 }
593 >
594 <FolderGit2Icon className="size-3.5 shrink-0 text-icon-muted" />
595 </TooltipTrigger>
596 <TooltipPopup side="top">{tooltip}</TooltipPopup>
597 </Tooltip>
598 );
600​
601function ThreadStatusLabel({
602 status,
603 compact = false,
604}: {
605 status: ThreadStatusPill;
606 compact?: boolean;
607}) {
608 if (compact) {
609 return (
610 <Tooltip>
611 <TooltipTrigger
612 render={
613 <span
614 role="img"
615 aria-label={status.label}
616 className={`inline-flex size-3.5 shrink-0 items-center justify-center ${status.colorClass}`}
617 />
618 }
619 >
620 <span
621 className={`size-[9px] rounded-full ${status.dotClass} ${
622 status.pulse ? "motion-safe:animate-status-pulse" : ""
623 }`}
624 />
625 </TooltipTrigger>
626 <TooltipPopup side="top">{status.label}</TooltipPopup>
627 </Tooltip>
628 );
629 }
630​
631 return (
632 <Tooltip>
633 <TooltipTrigger
634 render={
635 <span
636 role="img"
637 aria-label={status.label}
638 className={`inline-flex items-center gap-1 text-3xs ${status.colorClass}`}
639 />
640 }
641 >
642 <span
643 className={`h-1.5 w-1.5 rounded-full ${status.dotClass} ${
644 status.pulse ? "motion-safe:animate-status-pulse" : ""
645 }`}
646 />
647 <span className="hidden md:inline">{status.label}</span>
648 </TooltipTrigger>
649 <TooltipPopup side="top">{status.label}</TooltipPopup>
650 </Tooltip>
651 );
653​
654export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummary }) {
655 const { leaseLiveStatus, rowRef } = useSidebarRowSubscriptionLease(false);
656 // A new ref callback would detach and reattach the row, and each reattach sets lease state.
657 const statusRef = useStableCallback((node: HTMLSpanElement | null) =>
658 rowRef(node?.parentElement ?? null),
659 );
660 const threadRef = scopeThreadRef(thread.environmentId, thread.id);
661 const localLastVisitedAt = useUiStateStore(
662 (state) => state.threadLastVisitedAtById[scopedThreadKey(threadRef)],
663 );
664 const lastVisitedAt = resolveThreadLastVisitedAt(thread.lastVisitedAt, localLastVisitedAt);
665 const threadProject = useProject(scopeProjectRef(thread.environmentId, thread.projectId));
666 const threadProjectCwd = threadProject?.workspaceRoot ?? null;
667 const gitCwd = thread.worktreePath ?? threadProjectCwd;
668 const linkedPullRequest = useLinkedThreadPullRequest(
669 thread.environmentId,
670 thread.linkedPullRequest,
671 leaseLiveStatus,
672 thread.pullRequests,
673 thread.branchPullRequest,
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 = linkedPullRequest?.pr ?? resolveDisplayedThreadPr(displayedPrInput);
697 const prStatus = prStatusIndicator(
698 pr,
699 linkedPullRequest?.sourceControlProvider ?? resolveDisplayedThreadPrProvider(displayedPrInput),
700 );
701 const threadStatus = resolveThreadStatusPill({
702 thread: {
703 ...thread,
704 lastVisitedAt,
705 },
706 });
707​
708 const supportsMultiplePullRequests = useSupportsMultiplePullRequests(thread.environmentId);
709 const pendingLink =
710 pr === null && supportsMultiplePullRequests
711 ? resolveThreadCurrentPullRequestLink(thread.pullRequests)
712 : null;
713​
714 return (
715 <span
716 ref={statusRef}
717 className={
718 prStatus || threadStatus ? "inline-flex shrink-0 items-center gap-1.5" : "contents"
719 }
720 >
721 {prStatus && pr ? (
722 <Tooltip>
723 <TooltipTrigger
724 render={
725 <span
726 aria-label={prStatus.tooltip}
727 className={`inline-flex items-center justify-center ${prStatus.colorClass}`}
728 />
729 }
730 >
731 <ChangeRequestStatusIcon state={pr.state} isDraft={pr.isDraft} className="size-3" />
732 </TooltipTrigger>
733 <TooltipPopup side="top">
734 <PrStatusTooltipContent status={prStatus} />
735 </TooltipPopup>
736 </Tooltip>
737 ) : null}
738 {pendingLink ? (
739 <PullRequestGlyph.pullRequest
740 className="size-3 text-muted-foreground"
741 aria-label={`${changeRequestTerminologyForUrl(pendingLink.url).shortLabel} #${pendingLink.number}, status pending`}
742 />
743 ) : null}
744 {threadStatus ? <ThreadStatusLabel status={threadStatus} /> : null}
745 </span>
746 );
748​
749export function ThreadRowTrailingStatus({ thread }: { thread: SidebarThreadSummary }) {
750 const runningTerminalIds = useThreadRunningTerminalIds({
751 environmentId: thread.environmentId,
752 threadId: thread.id,
753 });
754 const environment = useEnvironment(thread.environmentId);
755 const primaryEnvironmentId = usePrimaryEnvironmentId();
756 const isRemoteThread = thread.environmentId !== primaryEnvironmentId;
757 const remoteEnvLabel = environment?.label ?? null;
758 const threadEnvironmentLabel = isRemoteThread ? (remoteEnvLabel ?? "Remote") : null;
759 const remoteMachine = resolveEnvironmentMachineKind(environment?.serverConfig ?? null);
760 const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
761​
762 if (!terminalStatus && !isRemoteThread) {
763 return null;
764 }
765​
766 return (
767 <span className="inline-flex shrink-0 items-center gap-1.5">
768 {terminalStatus ? (
769 <Tooltip>
770 <TooltipTrigger
771 render={
772 <span
773 role="img"
774 aria-label={terminalStatus.label}
775 className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
776 />
777 }
778 >
779 <TerminalIcon
780 className={`size-3 ${terminalStatus.pulse ? "motion-safe:animate-status-pulse" : ""}`}
781 onAnimationStart={synchronizeTerminalPulse}
782 />
783 </TooltipTrigger>
784 <TooltipPopup side="top">{terminalStatus.label}</TooltipPopup>
785 </Tooltip>
786 ) : null}
787 {isRemoteThread ? (
788 <Tooltip>
789 <TooltipTrigger
790 render={
791 <span
792 aria-label={threadEnvironmentLabel ?? "Remote"}
793 className="inline-flex items-center justify-center"
794 />
795 }
796 >
797 <EnvironmentMachineIcon
798 kind={remoteMachine}
799 className="size-3 text-muted-foreground/60"
800 />
801 </TooltipTrigger>
802 <TooltipPopup side="top">{threadEnvironmentLabel}</TooltipPopup>
803 </Tooltip>
804 ) : null}
805 </span>
806 );
808​
809function settledPrHoverColorClass(state: ThreadPullRequestBadge["state"]): string {
810 switch (state) {
811 case "draft":
812 return "group-hover/sidebar-row:text-zinc-500 dark:group-hover/sidebar-row:text-zinc-400/80";
813 case "open":
814 return "group-hover/sidebar-row:text-emerald-600 dark:group-hover/sidebar-row:text-emerald-300/90";
815 case "merged":
816 return "group-hover/sidebar-row:text-violet-600 dark:group-hover/sidebar-row:text-violet-300/90";
817 case "closed":
818 return "group-hover/sidebar-row:text-red-600 dark:group-hover/sidebar-row:text-red-300/90";
819 }
821​
822// Search rows are already buttons, so this renders the sidebar badge's look without its controls.
823export function ThreadSearchPullRequestNumber({
824 thread,
825 query,
826 enabled = true,
827 settled = false,
828}: {
829 thread: SidebarThreadSummary;
830 query: string;
831 enabled?: boolean;
832 settled?: boolean;
833}) {
834 const matched = pullRequestMatchesSearchQuery(thread, query);
835 const supportsMultiplePullRequests = useSupportsMultiplePullRequests(thread.environmentId);
836 const linked = useLinkedThreadPullRequest(
837 thread.environmentId,
838 thread.linkedPullRequest,
839 enabled && matched,
840 thread.pullRequests,
841 thread.branchPullRequest,
842 );
843 if (!matched) return null;
844 const badge = supportsMultiplePullRequests
845 ? resolveThreadPullRequestBadge(thread.pullRequests)
846 : null;
847 const current = supportsMultiplePullRequests
848 ? resolveThreadCurrentPullRequestLink(thread.pullRequests)
849 : null;
850 const pr = linked?.pr ?? null;
851 // Stored references already carry a number, so the badge shows before PR details load.
852 const stored =
853 current ??
854 [thread.linkedPullRequest, thread.branchPullRequest].find(
855 (reference) =>
856 reference != null && pullRequestMatchesSearchQuery({ linkedPullRequest: reference }, query),
857 );
858 const presentation = resolveThreadPullRequestBadgePresentation({
859 badge,
860 number: pr?.number ?? stored?.number,
861 url: pr?.url ?? stored?.url,
862 status: prStatusIndicator(pr, linked?.sourceControlProvider),
863 });
864 if (presentation === null) return null;
865 const aggregate = badge !== null && (badge.kind === "stack" || badge.others > 0);
866 const state = aggregate
867 ? badge.state
868 : pr === null
869 ? null
870 : pr.state === "open" && pr.isDraft
871 ? "draft"
872 : pr.state;
873 return (
874 <span
875 aria-label={presentation.label}
876 className={cn(
877 "inline-flex shrink-0 items-center gap-0.5 text-xs tabular-nums",
878 settled
879 ? cn("text-secondary-label transition-colors", state && settledPrHoverColorClass(state))
880 : presentation.toneClassName,
881 )}
882 >
883 {/* text-current opts out of the command palette's muted icon color. */}
884 <presentation.Icon aria-hidden className="size-3 shrink-0 text-current" />
885 <span>{presentation.text}</span>
886 </span>
887 );