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

ThreadStatusIndicators.tsx

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