Open History to see the last commit
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;
69}
70
71export interface TerminalStatusIndicator {
72 label: "Terminal process running";
73 colorClass: string;
74 pulse: boolean;
75}
76
77export type ThreadPr = VcsStatusResult["pr"];
78
79export interface LinkedThreadPullRequestStatus {
80 readonly pr: NonNullable<ThreadPr>;
81 readonly sourceControlProvider: NonNullable<VcsStatusResult["sourceControlProvider"]>;
82}
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 };
117}
118
119function linkedPullRequestReference(fallback: ThreadLinkedPullRequest) {
120 const host = sourceControlClients.parseChangeRequestUrl(fallback.url)?.link.host;
121 return { ...fallback, ...(host === undefined ? {} : { host }) };
122}
123
124function changeRequestTerminologyForUrl(url: string | undefined) {
125 const host = url === undefined ? null : sourceControlClients.findByChangeRequestUrl(url);
126 return (host ?? sourceControlClients.get(undefined)).changeRequest;
127}
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 };
150}
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;
162}
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 };
203}
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 );
239}
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 );
320}
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 );
363}
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 );
412}
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 };
432}
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} />;
444}
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 );
454}
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;
476}
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;
498}
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 };
511}
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 }
521}
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 );
570}
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 );
604}
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 );
657}
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 );
678 const gitStatus = useEnvironmentQuery(
679 leaseLiveStatus &&
680 thread.linkedPullRequest == null &&
681 (thread.branch != null || thread.worktreePath !== null) &&
682 gitCwd !== null
683 ? vcsEnvironment.status({
684 environmentId: thread.environmentId,
685 input: { cwd: gitCwd, includeRemote: false },
686 })
687 : null,
688 );
689 const visibleGitStatus = useRetainedValue(
690 JSON.stringify([thread.environmentId, gitCwd]),
691 gitStatus.data,
692 );
693 const displayedPrInput = {
694 threadBranch: thread.branch,
695 gitStatus: visibleGitStatus,
696 linkedPullRequest: thread.linkedPullRequest,
697 linkedPullRequestStatus: linkedPullRequest,
698 };
699 const pr = resolveDisplayedThreadPr(displayedPrInput);
700 const prStatus = prStatusIndicator(pr, resolveDisplayedThreadPrProvider(displayedPrInput));
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 );
747}
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 );
807}
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 }
820}
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 );
888}