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

ThreadStatusIndicators.tsx

990 lines31.5 KB

1import {
2 scopeProjectRef,
3 scopedThreadKey,
4 scopeThreadRef,
5} from "@t3tools/client-runtime/environment";
6import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests";
7​
8import { pullRequestDetailToVcsStatus } from "@t3tools/client-runtime/state/pull-requests";
9import {
10 resolveEnvironmentMachineKind,
11 type EnvironmentId,
12 type ThreadLinkedPullRequest,
13 type ThreadPullRequestLink,
14 type VcsStatusResult,
15} from "@t3tools/contracts";
16import { Atom } from "effect/unstable/reactivity";
17import { FolderGit2Icon, TerminalIcon } from "lucide-react";
18import { useCallback, useMemo } from "react";
19import { appAtomRegistry } from "../rpc/atomRegistry";
20import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments";
21import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
22import { useProject } from "../state/entities";
23import {
24 resolveThreadCurrentPullRequestLink,
25 resolveThreadPullRequestChains,
26 visibleThreadPullRequests,
27 type ThreadPullRequestBadge,
28} from "@t3tools/shared/threadPullRequests";
29import { type MouseEvent, type ReactNode } from "react";
30import { buttonVariants, InlineButton } from "./ui/button";
31import { cn } from "../lib/utils";
32​
33import { parseChangeRequestUrl } from "../lib/openPullRequestLink";
34import { useEnvironmentQuery } from "../state/query";
35import { linkedPullRequestDetailAtom, useSharedPullRequestSummary } from "../state/pullRequests";
36import { useThreadRunningTerminalIds } from "../state/terminalSessions";
37import { vcsEnvironment } from "../state/vcs";
38import { useUiStateStore } from "../uiStateStore";
39import { resolveChangeRequestPresentation } from "../sourceControlPresentation";
40import {
41 resolveThreadLastVisitedAt,
42 resolveThreadStatusPill,
43 type ThreadStatusPill,
44 useRetainedValue,
45 useSidebarRowSubscriptionLease,
46} from "./Sidebar.logic";
47​
48import type { SidebarThreadSummary } from "../types";
49import { formatWorktreePathForDisplay } from "../worktreeCleanup";
50import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
51import { pullRequestListLines } from "./pullRequest/pullRequestListLines";
52import {
53 PULL_REQUEST_STATE_PRESENTATION,
54 PullRequestGlyph,
55 type PullRequestGlyphIcon,
56} from "./pullRequest/pullRequestIcons";
57import { resolvePullRequestState } from "./pullRequest/pullRequestPresentation";
58​
59export interface PrStatusIndicator {
60 label: string;
61 colorClass: string;
62 Icon: PullRequestGlyphIcon;
63 tooltip: string;
64 tooltipLead: string;
65 tooltipTitle: string;
66 url: string;
68​
69export interface TerminalStatusIndicator {
70 label: "Terminal process running";
71 colorClass: string;
72 pulse: boolean;
74​
75export type ThreadPr = VcsStatusResult["pr"];
76​
77export interface LinkedThreadPullRequestStatus {
78 readonly pr: NonNullable<ThreadPr>;
79 readonly sourceControlProvider: NonNullable<VcsStatusResult["sourceControlProvider"]>;
81​
82/** Linked badges use persisted snapshots; only branch and legacy fallbacks lease summary reads. */
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 = useMemo(
92 () => (supportsLinks ? resolveThreadCurrentPullRequestLink(pullRequests ?? []) : null),
93 [pullRequests, supportsLinks],
94 );
95 const fallback =
96 current === null ? ((!supportsLinks ? linkedPullRequest : null) ?? branchPullRequest) : null;
97 const host = fallback == null ? undefined : parseChangeRequestUrl(fallback.url)?.host;
98 const reference =
99 fallback == null ? null : { ...fallback, ...(host === undefined ? {} : { host }) };
100 const queried = useEnvironmentQuery(
101 !enabled || environmentId === null || reference === null
102 ? null
103 : linkedPullRequestDetailAtom({ environmentId, input: reference }),
104 ).data;
105 const detail = useSharedPullRequestSummary(environmentId, reference, queried);
106​
107 return useMemo(() => {
108 if (current !== null) return linkedPullRequestSnapshotStatus(current);
109 return detail === null
110 ? null
111 : {
112 pr: pullRequestDetailToVcsStatus(detail),
113 sourceControlProvider: { kind: detail.provider, name: detail.provider, baseUrl: "" },
114 };
115 }, [current, detail]);
117​
118export function linkedPullRequestSnapshotStatus(
119 link: ThreadPullRequestLink,
120): LinkedThreadPullRequestStatus | null {
121 const snapshot = link.snapshot;
122 if (snapshot === null) return null;
123 const kind = link.url.includes("/-/merge_requests/")
124 ? "gitlab"
125 : link.url.includes("/pullrequest/")
126 ? "azure-devops"
127 : link.url.includes("/pull-requests/")
128 ? "bitbucket"
129 : link.url.includes("/pulls/")
130 ? "forgejo"
131 : "github";
132 return {
133 pr: {
134 number: link.number,
135 url: link.url,
136 title: snapshot.title,
137 state: snapshot.state,
138 isDraft: snapshot.isDraft,
139 headRef: snapshot.headBranch,
140 baseRef: snapshot.baseBranch,
141 ...(snapshot.updatedAt === null ? {} : { updatedAt: snapshot.updatedAt }),
142 },
143 sourceControlProvider: { kind, name: kind, baseUrl: "" },
144 };
146​
147export {
148 resolveThreadPullRequestBadge,
149 type ThreadPullRequestBadge,
150} from "@t3tools/shared/threadPullRequests";
151​
152export interface ThreadPullRequestBadgePresentation {
153 readonly Icon: PullRequestGlyphIcon;
154 readonly toneClassName: string;
155 readonly label: string;
156 readonly text: string | number;
158​
159/** Resolve the complete badge appearance before rendering it in the sidebar or composer. */
160export function resolveThreadPullRequestBadgePresentation({
161 badge,
162 number,
163 url,
164 status,
165}: {
166 readonly badge: ThreadPullRequestBadge | null;
167 readonly number?: number | undefined;
168 readonly url?: string | undefined;
169 readonly status: PrStatusIndicator | null;
170}): ThreadPullRequestBadgePresentation | null {
171 // The badge already folds every visible link into one state, draft included, so both the
172 // stack and the linked count index the shared table directly rather than the single-PR resolver.
173 if (badge?.kind === "stack") {
174 const aggregate = PULL_REQUEST_STATE_PRESENTATION[badge.state];
175 return {
176 Icon: PullRequestGlyph.stack,
177 toneClassName: aggregate.toneClassName,
178 label: `Stack of ${badge.layers} pull requests, ${aggregate.label.toLowerCase()}`,
179 text: badge.layers,
180 };
181 }
182 if (number === undefined || url === undefined) return null;
183​
184 const tooltip = status?.tooltip ?? `PR #${number}, status pending`;
185 if (badge?.kind === "pull-request" && badge.others > 0) {
186 // Unrelated links fold into one state, so a count of merged PRs reads as merged.
187 const aggregate = PULL_REQUEST_STATE_PRESENTATION[badge.state];
188 return {
189 Icon: aggregate.Icon,
190 toneClassName: aggregate.toneClassName,
191 label: `${tooltip}, and ${badge.others} more linked; overall ${aggregate.label.toLowerCase()}`,
192 text: `+${badge.others + 1}`,
193 };
194 }
195 return {
196 Icon: status?.Icon ?? PullRequestGlyph.pullRequest,
197 toneClassName: status?.colorClass ?? "text-muted-foreground",
198 label: tooltip,
199 text: number,
200 };
202​
203/** The complete linked-PR control shared by the sidebar and composer footer. */
204export function ThreadPullRequestBadgeControl({
205 variant,
206 badge,
207 pullRequests,
208 number,
209 url,
210 status,
211 onOpenStack,
212 onOpenPullRequest,
213}: {
214 variant: "underline" | "ghost";
215 badge: ThreadPullRequestBadge | null;
216 pullRequests: ReadonlyArray<ThreadPullRequestLink>;
217 number?: number | undefined;
218 url?: string | undefined;
219 status: PrStatusIndicator | null;
220 onOpenStack: () => void;
221 onOpenPullRequest: (event: MouseEvent<HTMLAnchorElement>, url?: string) => void;
222}) {
223 const presentation = resolveThreadPullRequestBadgePresentation({ badge, number, url, status });
224 if (presentation === null) return null;
225 const isStack = badge?.kind === "stack";
226 const className = cn(
227 variant === "ghost"
228 ? buttonVariants({ variant: "ghost", size: "xs" })
229 : "inline-flex shrink-0 cursor-pointer items-center gap-0.5 whitespace-nowrap border-b border-transparent hover:border-current focus-visible:outline-2 focus-visible:outline-ring",
230 "text-xs tabular-nums",
231 variant === "ghost" &&
232 "font-normal text-xs! active:scale-100 [--control-icon-color:currentColor]",
233 presentation.toneClassName,
234 );
235 const content = (
236 <>
237 <presentation.Icon aria-hidden className="size-3 shrink-0" />
238 {presentation.text}
239 </>
240 );
241 return (
242 <Tooltip>
243 <TooltipTrigger
244 render={
245 isStack ? (
246 <InlineButton
247 className={className}
248 aria-label={presentation.label}
249 onPointerDown={(event) => event.stopPropagation()}
250 onClick={(event) => {
251 event.preventDefault();
252 event.stopPropagation();
253 onOpenStack();
254 }}
255 />
256 ) : (
257 <a
258 href={url}
259 target="_blank"
260 rel="noopener noreferrer"
261 className={className}
262 aria-label={presentation.label}
263 onPointerDown={(event) => event.stopPropagation()}
264 onClick={onOpenPullRequest}
265 />
266 )
267 }
268 >
269 {content}
270 </TooltipTrigger>
271 <TooltipPopup
272 side="top"
273 sideOffset={0}
274 variant="glass"
275 className="pointer-events-auto w-80 max-w-[calc(100vw-2rem)] text-left whitespace-normal"
276 >
277 {visibleThreadPullRequests(pullRequests).length > 0 ? (
278 <ThreadPullRequestsMiniList
279 pullRequests={pullRequests}
280 onOpenPullRequest={onOpenPullRequest}
281 />
282 ) : number !== undefined && url !== undefined ? (
283 <ul className="flex flex-col gap-1">
284 <ThreadPullRequestMiniListItem
285 number={number}
286 url={url}
287 title={status?.tooltipTitle ?? presentation.label}
288 presentation={presentation}
289 onOpenPullRequest={onOpenPullRequest}
290 />
291 </ul>
292 ) : null}
293 </TooltipPopup>
294 </Tooltip>
295 );
297​
298/**
299 * A miniature of the pull-requests panel for the thread tooltip: same order, same indentation,
300 * so the hover answers "what is in here" without opening the surface.
301 */
302export function ThreadPullRequestsMiniList({
303 pullRequests,
304 onOpenPullRequest,
305}: {
306 pullRequests: ReadonlyArray<ThreadPullRequestLink>;
307 onOpenPullRequest?: (event: MouseEvent<HTMLAnchorElement>, url: string) => void;
308}) {
309 const lines = useMemo(
310 () =>
311 pullRequestListLines(resolveThreadPullRequestChains(visibleThreadPullRequests(pullRequests))),
312 [pullRequests],
313 );
314 if (lines.length === 0) return null;
315 return (
316 <ul className="flex flex-col gap-1">
317 {lines.map((line) => {
318 const snapshot = line.link.snapshot;
319 const presentation =
320 snapshot === null
321 ? null
322 : resolvePullRequestState({ state: snapshot.state, isDraft: snapshot.isDraft });
323 return (
324 <ThreadPullRequestMiniListItem
325 key={`${line.link.host}/${line.link.repository}#${line.link.number}`}
326 number={line.link.number}
327 url={line.link.url}
328 title={snapshot?.title ?? line.link.repository}
329 presentation={presentation}
330 depth={line.depth}
331 onOpenPullRequest={onOpenPullRequest}
332 >
333 {line.stack ? (
334 <span className="ml-auto shrink-0 pl-1 text-[10px]">
335 {line.stack.kind === "native" ? "stack" : "chain"} · {line.stack.size}
336 </span>
337 ) : null}
338 </ThreadPullRequestMiniListItem>
339 );
340 })}
341 </ul>
342 );
344​
345function ThreadPullRequestMiniListItem({
346 number,
347 url,
348 title,
349 presentation,
350 depth = 0,
351 onOpenPullRequest,
352 children,
353}: {
354 number: number;
355 url: string;
356 title: string;
357 presentation: Pick<ThreadPullRequestBadgePresentation, "Icon" | "toneClassName"> | null;
358 depth?: number;
359 onOpenPullRequest?: ((event: MouseEvent<HTMLAnchorElement>, url: string) => void) | undefined;
360 children?: ReactNode;
361}) {
362 const Icon = presentation?.Icon ?? PullRequestGlyph.pullRequest;
363 const content = (
364 <>
365 <Icon
366 aria-hidden
367 className={cn("size-3 shrink-0", presentation?.toneClassName ?? "stroke-muted-foreground")}
368 />
369 <span className="shrink-0 font-mono tabular-nums">#{number}</span>
370 <span className="min-w-0 truncate text-foreground/75">{title}</span>
371 {children}
372 </>
373 );
374 return (
375 <li style={{ paddingLeft: `${Math.min(depth, 3) * 0.75}rem` }}>
376 {onOpenPullRequest ? (
377 <a
378 href={url}
379 target="_blank"
380 rel="noopener noreferrer"
381 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-ring"
382 onPointerDown={(event) => event.stopPropagation()}
383 onClick={(event) => onOpenPullRequest(event, url)}
384 >
385 {content}
386 </a>
387 ) : (
388 <div className="flex min-w-0 items-center gap-2">{content}</div>
389 )}
390 </li>
391 );
393​
394export function prStatusIndicator(
395 pr: ThreadPr,
396 provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
397): PrStatusIndicator | null {
398 if (!pr) return null;
399 const presentation = resolveChangeRequestPresentation(provider);
400 const state = resolvePullRequestState({ state: pr.state, isDraft: pr.isDraft === true });
401​
402 const tooltipLead = `${presentation.shortName} #${pr.number} - ${state.label}`;
403 return {
404 label: `${presentation.shortName} ${state.label.toLowerCase()}`,
405 colorClass: state.toneClassName,
406 Icon: state.Icon,
407 tooltip: `${tooltipLead}: ${pr.title}`,
408 tooltipLead,
409 tooltipTitle: pr.title,
410 url: pr.url,
411 };
413​
414export function ChangeRequestStatusIcon({
415 state,
416 isDraft = false,
417 className,
418}: Pick<NonNullable<ThreadPr>, "state"> & {
419 readonly isDraft?: boolean | undefined;
420 readonly className?: string | undefined;
421}) {
422 const presentation = resolvePullRequestState({ state, isDraft });
423 return <presentation.Icon className={className} />;
425​
426export function PrStatusTooltipContent({ status }: { status: PrStatusIndicator }) {
427 return (
428 <span className="flex max-w-[min(34rem,calc(100vw-2rem))] items-stretch overflow-hidden whitespace-nowrap">
429 <span className="shrink-0 pr-2 font-medium">{status.tooltipLead}</span>
430 <span className="min-h-4 shrink-0 border-border/70 border-l" aria-hidden="true" />
431 <span className="min-w-0 truncate pl-2">{status.tooltipTitle}</span>
432 </span>
433 );
435​
436export function resolveThreadPr(input: {
437 threadBranch: string | null;
438 gitStatus: VcsStatusResult | null;
439}): ThreadPr | null {
440 const { threadBranch, gitStatus } = input;
441 if (gitStatus === null) {
442 return null;
443 }
444​
445 if (threadBranch === null || gitStatus.refName !== threadBranch) {
446 return null;
447 }
448​
449 return gitStatus.pr ?? null;
451​
452/**
453 * Parent-held PR snapshot for Sidebar V2. Rows remount when settlement
454 * partitions move them, so terminal PR metadata must live above the row.
455 */
456export interface ThreadChangeRequestSnapshot {
457 readonly branch: string;
458 readonly pr: NonNullable<ThreadPr>;
459 readonly sourceControlProvider: VcsStatusResult["sourceControlProvider"] | undefined;
460 readonly linkedPullRequest?: ThreadLinkedPullRequest;
462​
463export const threadChangeRequestSnapshotsAtom = Atom.make<
464 ReadonlyMap<string, ThreadChangeRequestSnapshot>
465>(new Map()).pipe(Atom.keepAlive, Atom.withLabel("sidebar:thread-change-request-snapshots"));
466​
467function isTerminalChangeRequestState(
468 state: NonNullable<ThreadPr>["state"],
469): state is "merged" | "closed" {
470 return state === "merged" || state === "closed";
472​
473function sourceControlProvidersEqual(
474 left: VcsStatusResult["sourceControlProvider"] | undefined,
475 right: VcsStatusResult["sourceControlProvider"] | undefined,
476): boolean {
477 if (left === right) return true;
478 if (left == null || right == null) return left == null && right == null;
479 return left.kind === right.kind && left.name === right.name && left.baseUrl === right.baseUrl;
481​
482function linkedPullRequestsEqual(
483 left: ThreadLinkedPullRequest | null | undefined,
484 right: ThreadLinkedPullRequest | null | undefined,
485): boolean {
486 if (left == null || right == null) return left == null && right == null;
487 return (
488 left.projectId === right.projectId &&
489 left.repository === right.repository &&
490 left.number === right.number &&
491 left.url === right.url
492 );
494​
495export function threadChangeRequestSnapshotsEqual(
496 left: ThreadChangeRequestSnapshot,
497 right: ThreadChangeRequestSnapshot,
498): boolean {
499 return (
500 left.branch === right.branch &&
501 left.pr.number === right.pr.number &&
502 left.pr.title === right.pr.title &&
503 left.pr.url === right.pr.url &&
504 left.pr.baseRef === right.pr.baseRef &&
505 left.pr.headRef === right.pr.headRef &&
506 left.pr.state === right.pr.state &&
507 left.pr.isDraft === right.pr.isDraft &&
508 (left.pr.updatedAt ?? null) === (right.pr.updatedAt ?? null) &&
509 sourceControlProvidersEqual(left.sourceControlProvider, right.sourceControlProvider) &&
510 linkedPullRequestsEqual(left.linkedPullRequest, right.linkedPullRequest)
511 );
513​
514export function setThreadChangeRequestSnapshot(
515 threadKey: string,
516 snapshot: ThreadChangeRequestSnapshot | null,
517): void {
518 appAtomRegistry.modify(threadChangeRequestSnapshotsAtom, (current) => {
519 const existing = current.get(threadKey);
520 if (snapshot === null) {
521 if (existing === undefined) return [false, current];
522 const next = new Map(current);
523 next.delete(threadKey);
524 return [true, next];
525 }
526 if (existing !== undefined && threadChangeRequestSnapshotsEqual(existing, snapshot)) {
527 return [false, current];
528 }
529 const next = new Map(current);
530 next.set(threadKey, snapshot);
531 return [true, next];
532 });
534​
535/**
536 * Authoritative snapshot update from live VCS status.
537 * - `undefined`: missing status, or a local checkout retaining a terminal PR — leave the map alone
538 * - `null`: no PR (without a retained terminal snapshot), a cleared branch, or a mismatch without a terminal PR — clear
539 * - snapshot: matching branch reports a PR — store/replace
540 */
541export function nextThreadChangeRequestSnapshot(input: {
542 threadBranch: string | null;
543 gitStatus: VcsStatusResult | null;
544 snapshot: ThreadChangeRequestSnapshot | null | undefined;
545 retainTerminalOnBranchMismatch: boolean;
546 linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
547 linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
548}): ThreadChangeRequestSnapshot | null | undefined {
549 const {
550 threadBranch,
551 gitStatus,
552 snapshot,
553 retainTerminalOnBranchMismatch,
554 linkedPullRequest,
555 linkedPullRequestStatus,
556 } = input;
557 if (linkedPullRequest != null) {
558 if (linkedPullRequestStatus === null || linkedPullRequestStatus === undefined) {
559 return linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest)
560 ? undefined
561 : null;
562 }
563 return {
564 branch: threadBranch ?? linkedPullRequestStatus.pr.headRef,
565 pr: linkedPullRequestStatus.pr,
566 sourceControlProvider: linkedPullRequestStatus.sourceControlProvider,
567 linkedPullRequest,
568 };
569 }
570 if (gitStatus === null) {
571 return snapshot?.linkedPullRequest === undefined ? undefined : null;
572 }
573 if (threadBranch === null) {
574 return null;
575 }
576 if (gitStatus.refName !== threadBranch) {
577 return retainTerminalOnBranchMismatch &&
578 snapshot != null &&
579 snapshot.linkedPullRequest === undefined &&
580 isTerminalChangeRequestState(snapshot.pr.state)
581 ? undefined
582 : null;
583 }
584 if (gitStatus.pr == null) {
585 if (
586 retainTerminalOnBranchMismatch &&
587 snapshot != null &&
588 snapshot.linkedPullRequest === undefined &&
589 isTerminalChangeRequestState(snapshot.pr.state)
590 ) {
591 return undefined;
592 }
593 return null;
594 }
595 return {
596 branch: threadBranch,
597 pr: gitStatus.pr,
598 sourceControlProvider: gitStatus.sourceControlProvider,
599 };
601​
602/**
603 * Live PR when the checkout matches the thread branch; otherwise, for local
604 * checkouts only, a cached merged/closed PR for the thread. Local thread
605 * metadata follows the shared checkout, so the cached branch intentionally
606 * survives that metadata changing to the newly checked-out branch. Open PRs
607 * are retained only while live status is absent and the branch still matches.
608 */
609export function resolveDisplayedThreadPr(input: {
610 threadBranch: string | null;
611 gitStatus: VcsStatusResult | null;
612 snapshot: ThreadChangeRequestSnapshot | null | undefined;
613 retainTerminalOnBranchMismatch: boolean;
614 linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
615 linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
616}): ThreadPr | null {
617 const {
618 threadBranch,
619 gitStatus,
620 snapshot,
621 retainTerminalOnBranchMismatch,
622 linkedPullRequest,
623 linkedPullRequestStatus,
624 } = input;
625 if (linkedPullRequest != null) {
626 return (
627 linkedPullRequestStatus?.pr ??
628 (linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest)
629 ? (snapshot?.pr ?? null)
630 : null)
631 );
632 }
633 if (
634 threadBranch !== null &&
635 gitStatus !== null &&
636 gitStatus.refName === threadBranch &&
637 gitStatus.pr != null
638 ) {
639 return gitStatus.pr;
640 }
641​
642 if (
643 gitStatus === null &&
644 threadBranch !== null &&
645 snapshot?.branch === threadBranch &&
646 snapshot.linkedPullRequest === undefined
647 ) {
648 return snapshot.pr;
649 }
650​
651 if (
652 threadBranch !== null &&
653 retainTerminalOnBranchMismatch &&
654 snapshot != null &&
655 snapshot.linkedPullRequest === undefined &&
656 isTerminalChangeRequestState(snapshot.pr.state)
657 ) {
658 return snapshot.pr;
659 }
660​
661 return null;
663​
664export function resolveDisplayedThreadPrProvider(input: {
665 threadBranch: string | null;
666 gitStatus: VcsStatusResult | null;
667 snapshot: ThreadChangeRequestSnapshot | null | undefined;
668 retainTerminalOnBranchMismatch: boolean;
669 linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
670 linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
671}): VcsStatusResult["sourceControlProvider"] | undefined {
672 const {
673 threadBranch,
674 gitStatus,
675 snapshot,
676 retainTerminalOnBranchMismatch,
677 linkedPullRequest,
678 linkedPullRequestStatus,
679 } = input;
680 if (linkedPullRequest != null) {
681 return (
682 linkedPullRequestStatus?.sourceControlProvider ??
683 (linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest)
684 ? snapshot?.sourceControlProvider
685 : undefined)
686 );
687 }
688 if (
689 threadBranch !== null &&
690 gitStatus !== null &&
691 gitStatus.refName === threadBranch &&
692 gitStatus.pr != null
693 ) {
694 return gitStatus.sourceControlProvider;
695 }
696​
697 if (
698 gitStatus === null &&
699 threadBranch !== null &&
700 snapshot?.branch === threadBranch &&
701 snapshot.linkedPullRequest === undefined
702 ) {
703 return snapshot.sourceControlProvider;
704 }
705​
706 if (
707 threadBranch !== null &&
708 retainTerminalOnBranchMismatch &&
709 snapshot != null &&
710 snapshot.linkedPullRequest === undefined &&
711 isTerminalChangeRequestState(snapshot.pr.state)
712 ) {
713 return snapshot.sourceControlProvider;
714 }
715​
716 return undefined;
718​
719export function terminalStatusFromRunningIds(
720 runningTerminalIds: ReadonlyArray<string>,
721): TerminalStatusIndicator | null {
722 if (runningTerminalIds.length === 0) {
723 return null;
724 }
725 return {
726 label: "Terminal process running",
727 colorClass: "text-teal-600 dark:text-teal-300/90",
728 pulse: true,
729 };
731​
732export function ThreadWorktreeIndicator({
733 thread,
734}: {
735 thread: Pick<SidebarThreadSummary, "id" | "branch" | "worktreePath">;
736}) {
737 const worktreePath = thread.worktreePath?.trim();
738 if (!worktreePath) {
739 return null;
740 }
741​
742 const displayPath = formatWorktreePathForDisplay(worktreePath);
743 const tooltip = thread.branch
744 ? `Worktree: ${displayPath} (${thread.branch})`
745 : `Worktree: ${displayPath}`;
746​
747 return (
748 <Tooltip>
749 <TooltipTrigger
750 render={
751 <span
752 role="img"
753 aria-label={tooltip}
754 data-testid={`thread-worktree-${thread.id}`}
755 className="inline-flex items-center justify-center"
756 />
757 }
758 >
759 <FolderGit2Icon className="size-3 text-muted-foreground/40" />
760 </TooltipTrigger>
761 <TooltipPopup side="top">{tooltip}</TooltipPopup>
762 </Tooltip>
763 );
765​
766export function ThreadStatusLabel({
767 status,
768 compact = false,
769}: {
770 status: ThreadStatusPill;
771 compact?: boolean;
772}) {
773 if (compact) {
774 return (
775 <Tooltip>
776 <TooltipTrigger
777 render={
778 <span
779 aria-label={status.label}
780 className={`inline-flex size-3.5 shrink-0 items-center justify-center ${status.colorClass}`}
781 />
782 }
783 >
784 <span
785 className={`size-[9px] rounded-full ${status.dotClass} ${
786 status.pulse ? "animate-status-pulse" : ""
787 }`}
788 />
789 </TooltipTrigger>
790 <TooltipPopup side="top">{status.label}</TooltipPopup>
791 </Tooltip>
792 );
793 }
794​
795 return (
796 <Tooltip>
797 <TooltipTrigger
798 render={
799 <span
800 aria-label={status.label}
801 className={`inline-flex items-center gap-1 text-[10px] ${status.colorClass}`}
802 />
803 }
804 >
805 <span
806 className={`h-1.5 w-1.5 rounded-full ${status.dotClass} ${
807 status.pulse ? "animate-status-pulse" : ""
808 }`}
809 />
810 <span className="hidden md:inline">{status.label}</span>
811 </TooltipTrigger>
812 <TooltipPopup side="top">{status.label}</TooltipPopup>
813 </Tooltip>
814 );
816​
817/**
818 * Non-interactive leading status icons for a thread row in compact contexts
819 * like the command palette. Shows the change request state icon (if present) and the
820 * thread status dot, matching the sidebar's leading indicators.
821 */
822export function ThreadRowLeadingStatus({
823 thread,
824 snapshot,
825}: {
826 thread: SidebarThreadSummary;
827 snapshot?: ThreadChangeRequestSnapshot | undefined;
828}) {
829 const { leaseLiveStatus, rowRef } = useSidebarRowSubscriptionLease(false);
830 // Observe the containing title even when this thread has no badge yet.
831 const statusRef = useCallback(
832 (node: HTMLSpanElement | null) => rowRef(node?.parentElement ?? null),
833 [rowRef],
834 );
835 const threadRef = scopeThreadRef(thread.environmentId, thread.id);
836 const localLastVisitedAt = useUiStateStore(
837 (state) => state.threadLastVisitedAtById[scopedThreadKey(threadRef)],
838 );
839 const lastVisitedAt = resolveThreadLastVisitedAt(thread.lastVisitedAt, localLastVisitedAt);
840 const threadProject = useProject(
841 useMemo(
842 () => scopeProjectRef(thread.environmentId, thread.projectId),
843 [thread.environmentId, thread.projectId],
844 ),
845 );
846 const threadProjectCwd = threadProject?.workspaceRoot ?? null;
847 const gitCwd = thread.worktreePath ?? threadProjectCwd;
848 const linkedPullRequest = useLinkedThreadPullRequest(
849 thread.environmentId,
850 thread.linkedPullRequest,
851 leaseLiveStatus,
852 );
853 const gitStatus = useEnvironmentQuery(
854 leaseLiveStatus &&
855 thread.linkedPullRequest == null &&
856 (thread.branch != null || thread.worktreePath !== null) &&
857 gitCwd !== null
858 ? vcsEnvironment.status({
859 environmentId: thread.environmentId,
860 input: { cwd: gitCwd },
861 })
862 : null,
863 );
864 const visibleGitStatus = useRetainedValue(
865 JSON.stringify([thread.environmentId, gitCwd]),
866 gitStatus.data,
867 );
868 const displayedPrInput = {
869 threadBranch: thread.branch,
870 gitStatus: visibleGitStatus,
871 snapshot,
872 retainTerminalOnBranchMismatch: thread.worktreePath === null,
873 linkedPullRequest: thread.linkedPullRequest,
874 linkedPullRequestStatus: linkedPullRequest,
875 };
876 const pr = resolveDisplayedThreadPr(displayedPrInput);
877 const prStatus = prStatusIndicator(pr, resolveDisplayedThreadPrProvider(displayedPrInput));
878 const threadStatus = resolveThreadStatusPill({
879 thread: {
880 ...thread,
881 lastVisitedAt,
882 },
883 });
884​
885 const supportsMultiplePullRequests = useSupportsMultiplePullRequests(thread.environmentId);
886 const pendingLink =
887 pr === null && supportsMultiplePullRequests
888 ? resolveThreadCurrentPullRequestLink(thread.pullRequests)
889 : null;
890​
891 return (
892 <span
893 ref={statusRef}
894 className={
895 prStatus || threadStatus ? "inline-flex shrink-0 items-center gap-1.5" : "contents"
896 }
897 >
898 {prStatus && pr ? (
899 <Tooltip>
900 <TooltipTrigger
901 render={
902 <span
903 aria-label={prStatus.tooltip}
904 className={`inline-flex items-center justify-center ${prStatus.colorClass}`}
905 />
906 }
907 >
908 <ChangeRequestStatusIcon state={pr.state} isDraft={pr.isDraft} className="size-3" />
909 </TooltipTrigger>
910 <TooltipPopup side="top">
911 <PrStatusTooltipContent status={prStatus} />
912 </TooltipPopup>
913 </Tooltip>
914 ) : null}
915 {pendingLink ? (
916 <PullRequestGlyph.pullRequest
917 className="size-3 text-muted-foreground"
918 aria-label={`PR #${pendingLink.number}, status pending`}
919 />
920 ) : null}
921 {threadStatus ? <ThreadStatusLabel status={threadStatus} /> : null}
922 </span>
923 );
925​
926/**
927 * Non-interactive trailing status icons for a thread row in compact contexts
928 * like the command palette. Shows a terminal-running indicator and a remote
929 * environment indicator, matching the sidebar's trailing indicators.
930 */
931export function ThreadRowTrailingStatus({ thread }: { thread: SidebarThreadSummary }) {
932 const runningTerminalIds = useThreadRunningTerminalIds({
933 environmentId: thread.environmentId,
934 threadId: thread.id,
935 });
936 const environment = useEnvironment(thread.environmentId);
937 const primaryEnvironmentId = usePrimaryEnvironmentId();
938 // No primary (the hosted app) means every thread is remote, and the machine
939 // glyph is what tells the environments apart.
940 const isRemoteThread = thread.environmentId !== primaryEnvironmentId;
941 const remoteEnvLabel = environment?.label ?? null;
942 const threadEnvironmentLabel = isRemoteThread ? (remoteEnvLabel ?? "Remote") : null;
943 const remoteMachine = resolveEnvironmentMachineKind(environment?.serverConfig ?? null);
944 const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
945​
946 if (!terminalStatus && !isRemoteThread) {
947 return null;
948 }
949​
950 return (
951 <span className="inline-flex shrink-0 items-center gap-1.5">
952 {terminalStatus ? (
953 <Tooltip>
954 <TooltipTrigger
955 render={
956 <span
957 role="img"
958 aria-label={terminalStatus.label}
959 className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
960 />
961 }
962 >
963 <TerminalIcon
964 className={`size-3 ${terminalStatus.pulse ? "animate-status-pulse" : ""}`}
965 />
966 </TooltipTrigger>
967 <TooltipPopup side="top">{terminalStatus.label}</TooltipPopup>
968 </Tooltip>
969 ) : null}
970 {isRemoteThread ? (
971 <Tooltip>
972 <TooltipTrigger
973 render={
974 <span
975 aria-label={threadEnvironmentLabel ?? "Remote"}
976 className="inline-flex items-center justify-center"
977 />
978 }
979 >
980 <EnvironmentMachineIcon
981 kind={remoteMachine}
982 className="size-3 text-muted-foreground/60"
983 />
984 </TooltipTrigger>
985 <TooltipPopup side="top">{threadEnvironmentLabel}</TooltipPopup>
986 </Tooltip>
987 ) : null}
988 </span>
989 );