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

ThreadStatusIndicators.tsx

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