Open History to see the last commit
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 } 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;
67}
68
69export interface TerminalStatusIndicator {
70 label: "Terminal process running";
71 colorClass: string;
72 pulse: boolean;
73}
74
75export type ThreadPr = VcsStatusResult["pr"];
76
77export interface LinkedThreadPullRequestStatus {
78 readonly pr: NonNullable<ThreadPr>;
79 readonly sourceControlProvider: NonNullable<VcsStatusResult["sourceControlProvider"]>;
80}
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]);
116}
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 };
145}
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;
157}
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 };
201}
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 showList = isStack || (badge?.kind === "pull-request" && badge.others > 0);
227 const className = cn(
228 variant === "ghost"
229 ? buttonVariants({ variant: "ghost", size: "xs" })
230 : "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",
231 "text-xs tabular-nums",
232 variant === "ghost" &&
233 "font-normal text-xs! active:scale-100 [--control-icon-color:currentColor]",
234 presentation.toneClassName,
235 );
236 const content = (
237 <>
238 <presentation.Icon aria-hidden className="size-3 shrink-0" />
239 {presentation.text}
240 </>
241 );
242 return (
243 <Tooltip>
244 <TooltipTrigger
245 render={
246 isStack ? (
247 <InlineButton
248 className={className}
249 aria-label={presentation.label}
250 onPointerDown={(event) => event.stopPropagation()}
251 onClick={(event) => {
252 event.preventDefault();
253 event.stopPropagation();
254 onOpenStack();
255 }}
256 />
257 ) : (
258 <a
259 href={url}
260 target="_blank"
261 rel="noopener noreferrer"
262 className={className}
263 aria-label={presentation.label}
264 onPointerDown={(event) => event.stopPropagation()}
265 onClick={onOpenPullRequest}
266 />
267 )
268 }
269 >
270 {content}
271 </TooltipTrigger>
272 <TooltipPopup
273 side="top"
274 variant={showList ? "glass" : "default"}
275 className={
276 showList
277 ? "pointer-events-auto w-80 max-w-[calc(100vw-2rem)] text-left whitespace-normal"
278 : undefined
279 }
280 >
281 {showList ? (
282 <ThreadPullRequestsMiniList
283 pullRequests={pullRequests}
284 onOpenPullRequest={onOpenPullRequest}
285 />
286 ) : (
287 presentation.label
288 )}
289 </TooltipPopup>
290 </Tooltip>
291 );
292}
293
294/**
295 * A miniature of the pull-requests panel for the thread tooltip: same order, same indentation,
296 * so the hover answers "what is in here" without opening the surface.
297 */
298export function ThreadPullRequestsMiniList({
299 pullRequests,
300 onOpenPullRequest,
301}: {
302 pullRequests: ReadonlyArray<ThreadPullRequestLink>;
303 onOpenPullRequest?: (event: MouseEvent<HTMLAnchorElement>, url: string) => void;
304}) {
305 const lines = useMemo(
306 () =>
307 pullRequestListLines(resolveThreadPullRequestChains(visibleThreadPullRequests(pullRequests))),
308 [pullRequests],
309 );
310 if (lines.length === 0) return null;
311 return (
312 <ul className="flex flex-col gap-1">
313 {lines.map((line) => {
314 const snapshot = line.link.snapshot;
315 const presentation =
316 snapshot === null
317 ? null
318 : resolvePullRequestState({ state: snapshot.state, isDraft: snapshot.isDraft });
319 const content = (
320 <>
321 {presentation ? (
322 <presentation.Icon
323 aria-hidden
324 className={cn("size-3 shrink-0", presentation.toneClassName)}
325 />
326 ) : (
327 <PullRequestGlyph.pullRequest
328 aria-hidden
329 className="size-3 shrink-0 stroke-muted-foreground"
330 />
331 )}
332 <span className="shrink-0 font-mono tabular-nums">#{line.link.number}</span>
333 <span className="min-w-0 truncate text-foreground/75">
334 {snapshot?.title ?? line.link.repository}
335 </span>
336 {line.stack ? (
337 <span className="ml-auto shrink-0 pl-1 text-[10px]">
338 {line.stack.kind === "native" ? "stack" : "chain"} · {line.stack.size}
339 </span>
340 ) : null}
341 </>
342 );
343 return (
344 <li
345 key={`${line.link.host}/${line.link.repository}#${line.link.number}`}
346 style={{ paddingLeft: `${Math.min(line.depth, 3) * 0.75}rem` }}
347 >
348 {onOpenPullRequest ? (
349 <a
350 href={line.link.url}
351 target="_blank"
352 rel="noopener noreferrer"
353 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"
354 onPointerDown={(event) => event.stopPropagation()}
355 onClick={(event) => onOpenPullRequest(event, line.link.url)}
356 >
357 {content}
358 </a>
359 ) : (
360 <div className="flex min-w-0 items-center gap-2">{content}</div>
361 )}
362 </li>
363 );
364 })}
365 </ul>
366 );
367}
368
369export function prStatusIndicator(
370 pr: ThreadPr,
371 provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
372): PrStatusIndicator | null {
373 if (!pr) return null;
374 const presentation = resolveChangeRequestPresentation(provider);
375 const state = resolvePullRequestState({ state: pr.state, isDraft: pr.isDraft === true });
376
377 const tooltipLead = `${presentation.shortName} #${pr.number} - ${state.label}`;
378 return {
379 label: `${presentation.shortName} ${state.label.toLowerCase()}`,
380 colorClass: state.toneClassName,
381 Icon: state.Icon,
382 tooltip: `${tooltipLead}: ${pr.title}`,
383 tooltipLead,
384 tooltipTitle: pr.title,
385 url: pr.url,
386 };
387}
388
389export function ChangeRequestStatusIcon({
390 state,
391 isDraft = false,
392 className,
393}: Pick<NonNullable<ThreadPr>, "state"> & {
394 readonly isDraft?: boolean | undefined;
395 readonly className?: string | undefined;
396}) {
397 const presentation = resolvePullRequestState({ state, isDraft });
398 return <presentation.Icon className={className} />;
399}
400
401export function PrStatusTooltipContent({ status }: { status: PrStatusIndicator }) {
402 return (
403 <span className="flex max-w-[min(34rem,calc(100vw-2rem))] items-stretch overflow-hidden whitespace-nowrap">
404 <span className="shrink-0 pr-2 font-medium">{status.tooltipLead}</span>
405 <span className="min-h-4 shrink-0 border-border/70 border-l" aria-hidden="true" />
406 <span className="min-w-0 truncate pl-2">{status.tooltipTitle}</span>
407 </span>
408 );
409}
410
411export function resolveThreadPr(input: {
412 threadBranch: string | null;
413 gitStatus: VcsStatusResult | null;
414}): ThreadPr | null {
415 const { threadBranch, gitStatus } = input;
416 if (gitStatus === null) {
417 return null;
418 }
419
420 if (threadBranch === null || gitStatus.refName !== threadBranch) {
421 return null;
422 }
423
424 return gitStatus.pr ?? null;
425}
426
427/**
428 * Parent-held PR snapshot for Sidebar V2. Rows remount when settlement
429 * partitions move them, so terminal PR metadata must live above the row.
430 */
431export interface ThreadChangeRequestSnapshot {
432 readonly branch: string;
433 readonly pr: NonNullable<ThreadPr>;
434 readonly sourceControlProvider: VcsStatusResult["sourceControlProvider"] | undefined;
435 readonly linkedPullRequest?: ThreadLinkedPullRequest;
436}
437
438export const threadChangeRequestSnapshotsAtom = Atom.make<
439 ReadonlyMap<string, ThreadChangeRequestSnapshot>
440>(new Map()).pipe(Atom.keepAlive, Atom.withLabel("sidebar:thread-change-request-snapshots"));
441
442function isTerminalChangeRequestState(
443 state: NonNullable<ThreadPr>["state"],
444): state is "merged" | "closed" {
445 return state === "merged" || state === "closed";
446}
447
448function sourceControlProvidersEqual(
449 left: VcsStatusResult["sourceControlProvider"] | undefined,
450 right: VcsStatusResult["sourceControlProvider"] | undefined,
451): boolean {
452 if (left === right) return true;
453 if (left == null || right == null) return left == null && right == null;
454 return left.kind === right.kind && left.name === right.name && left.baseUrl === right.baseUrl;
455}
456
457function linkedPullRequestsEqual(
458 left: ThreadLinkedPullRequest | null | undefined,
459 right: ThreadLinkedPullRequest | null | undefined,
460): boolean {
461 if (left == null || right == null) return left == null && right == null;
462 return (
463 left.projectId === right.projectId &&
464 left.repository === right.repository &&
465 left.number === right.number &&
466 left.url === right.url
467 );
468}
469
470export function threadChangeRequestSnapshotsEqual(
471 left: ThreadChangeRequestSnapshot,
472 right: ThreadChangeRequestSnapshot,
473): boolean {
474 return (
475 left.branch === right.branch &&
476 left.pr.number === right.pr.number &&
477 left.pr.title === right.pr.title &&
478 left.pr.url === right.pr.url &&
479 left.pr.baseRef === right.pr.baseRef &&
480 left.pr.headRef === right.pr.headRef &&
481 left.pr.state === right.pr.state &&
482 left.pr.isDraft === right.pr.isDraft &&
483 (left.pr.updatedAt ?? null) === (right.pr.updatedAt ?? null) &&
484 sourceControlProvidersEqual(left.sourceControlProvider, right.sourceControlProvider) &&
485 linkedPullRequestsEqual(left.linkedPullRequest, right.linkedPullRequest)
486 );
487}
488
489export function setThreadChangeRequestSnapshot(
490 threadKey: string,
491 snapshot: ThreadChangeRequestSnapshot | null,
492): void {
493 appAtomRegistry.modify(threadChangeRequestSnapshotsAtom, (current) => {
494 const existing = current.get(threadKey);
495 if (snapshot === null) {
496 if (existing === undefined) return [false, current];
497 const next = new Map(current);
498 next.delete(threadKey);
499 return [true, next];
500 }
501 if (existing !== undefined && threadChangeRequestSnapshotsEqual(existing, snapshot)) {
502 return [false, current];
503 }
504 const next = new Map(current);
505 next.set(threadKey, snapshot);
506 return [true, next];
507 });
508}
509
510/**
511 * Authoritative snapshot update from live VCS status.
512 * - `undefined`: missing status, or a local checkout retaining a terminal PR — leave the map alone
513 * - `null`: no PR (without a retained terminal snapshot), a cleared branch, or a mismatch without a terminal PR — clear
514 * - snapshot: matching branch reports a PR — store/replace
515 */
516export function nextThreadChangeRequestSnapshot(input: {
517 threadBranch: string | null;
518 gitStatus: VcsStatusResult | null;
519 snapshot: ThreadChangeRequestSnapshot | null | undefined;
520 retainTerminalOnBranchMismatch: boolean;
521 linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
522 linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
523}): ThreadChangeRequestSnapshot | null | undefined {
524 const {
525 threadBranch,
526 gitStatus,
527 snapshot,
528 retainTerminalOnBranchMismatch,
529 linkedPullRequest,
530 linkedPullRequestStatus,
531 } = input;
532 if (linkedPullRequest != null) {
533 if (linkedPullRequestStatus === null || linkedPullRequestStatus === undefined) {
534 return linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest)
535 ? undefined
536 : null;
537 }
538 return {
539 branch: threadBranch ?? linkedPullRequestStatus.pr.headRef,
540 pr: linkedPullRequestStatus.pr,
541 sourceControlProvider: linkedPullRequestStatus.sourceControlProvider,
542 linkedPullRequest,
543 };
544 }
545 if (gitStatus === null) {
546 return snapshot?.linkedPullRequest === undefined ? undefined : null;
547 }
548 if (threadBranch === null) {
549 return null;
550 }
551 if (gitStatus.refName !== threadBranch) {
552 return retainTerminalOnBranchMismatch &&
553 snapshot != null &&
554 snapshot.linkedPullRequest === undefined &&
555 isTerminalChangeRequestState(snapshot.pr.state)
556 ? undefined
557 : null;
558 }
559 if (gitStatus.pr == null) {
560 if (
561 retainTerminalOnBranchMismatch &&
562 snapshot != null &&
563 snapshot.linkedPullRequest === undefined &&
564 isTerminalChangeRequestState(snapshot.pr.state)
565 ) {
566 return undefined;
567 }
568 return null;
569 }
570 return {
571 branch: threadBranch,
572 pr: gitStatus.pr,
573 sourceControlProvider: gitStatus.sourceControlProvider,
574 };
575}
576
577/**
578 * Live PR when the checkout matches the thread branch; otherwise, for local
579 * checkouts only, a cached merged/closed PR for the thread. Local thread
580 * metadata follows the shared checkout, so the cached branch intentionally
581 * survives that metadata changing to the newly checked-out branch. Open PRs
582 * are retained only while live status is absent and the branch still matches.
583 */
584export function resolveDisplayedThreadPr(input: {
585 threadBranch: string | null;
586 gitStatus: VcsStatusResult | null;
587 snapshot: ThreadChangeRequestSnapshot | null | undefined;
588 retainTerminalOnBranchMismatch: boolean;
589 linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
590 linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
591}): ThreadPr | null {
592 const {
593 threadBranch,
594 gitStatus,
595 snapshot,
596 retainTerminalOnBranchMismatch,
597 linkedPullRequest,
598 linkedPullRequestStatus,
599 } = input;
600 if (linkedPullRequest != null) {
601 return (
602 linkedPullRequestStatus?.pr ??
603 (linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest)
604 ? (snapshot?.pr ?? null)
605 : null)
606 );
607 }
608 if (
609 threadBranch !== null &&
610 gitStatus !== null &&
611 gitStatus.refName === threadBranch &&
612 gitStatus.pr != null
613 ) {
614 return gitStatus.pr;
615 }
616
617 if (
618 gitStatus === null &&
619 threadBranch !== null &&
620 snapshot?.branch === threadBranch &&
621 snapshot.linkedPullRequest === undefined
622 ) {
623 return snapshot.pr;
624 }
625
626 if (
627 threadBranch !== null &&
628 retainTerminalOnBranchMismatch &&
629 snapshot != null &&
630 snapshot.linkedPullRequest === undefined &&
631 isTerminalChangeRequestState(snapshot.pr.state)
632 ) {
633 return snapshot.pr;
634 }
635
636 return null;
637}
638
639export function resolveDisplayedThreadPrProvider(input: {
640 threadBranch: string | null;
641 gitStatus: VcsStatusResult | null;
642 snapshot: ThreadChangeRequestSnapshot | null | undefined;
643 retainTerminalOnBranchMismatch: boolean;
644 linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
645 linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
646}): VcsStatusResult["sourceControlProvider"] | undefined {
647 const {
648 threadBranch,
649 gitStatus,
650 snapshot,
651 retainTerminalOnBranchMismatch,
652 linkedPullRequest,
653 linkedPullRequestStatus,
654 } = input;
655 if (linkedPullRequest != null) {
656 return (
657 linkedPullRequestStatus?.sourceControlProvider ??
658 (linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest)
659 ? snapshot?.sourceControlProvider
660 : undefined)
661 );
662 }
663 if (
664 threadBranch !== null &&
665 gitStatus !== null &&
666 gitStatus.refName === threadBranch &&
667 gitStatus.pr != null
668 ) {
669 return gitStatus.sourceControlProvider;
670 }
671
672 if (
673 gitStatus === null &&
674 threadBranch !== null &&
675 snapshot?.branch === threadBranch &&
676 snapshot.linkedPullRequest === undefined
677 ) {
678 return snapshot.sourceControlProvider;
679 }
680
681 if (
682 threadBranch !== null &&
683 retainTerminalOnBranchMismatch &&
684 snapshot != null &&
685 snapshot.linkedPullRequest === undefined &&
686 isTerminalChangeRequestState(snapshot.pr.state)
687 ) {
688 return snapshot.sourceControlProvider;
689 }
690
691 return undefined;
692}
693
694export function terminalStatusFromRunningIds(
695 runningTerminalIds: ReadonlyArray<string>,
696): TerminalStatusIndicator | null {
697 if (runningTerminalIds.length === 0) {
698 return null;
699 }
700 return {
701 label: "Terminal process running",
702 colorClass: "text-teal-600 dark:text-teal-300/90",
703 pulse: true,
704 };
705}
706
707export function ThreadWorktreeIndicator({
708 thread,
709}: {
710 thread: Pick<SidebarThreadSummary, "id" | "branch" | "worktreePath">;
711}) {
712 const worktreePath = thread.worktreePath?.trim();
713 if (!worktreePath) {
714 return null;
715 }
716
717 const displayPath = formatWorktreePathForDisplay(worktreePath);
718 const tooltip = thread.branch
719 ? `Worktree: ${displayPath} (${thread.branch})`
720 : `Worktree: ${displayPath}`;
721
722 return (
723 <Tooltip>
724 <TooltipTrigger
725 render={
726 <span
727 role="img"
728 aria-label={tooltip}
729 data-testid={`thread-worktree-${thread.id}`}
730 className="inline-flex items-center justify-center"
731 />
732 }
733 >
734 <FolderGit2Icon className="size-3 text-muted-foreground/40" />
735 </TooltipTrigger>
736 <TooltipPopup side="top">{tooltip}</TooltipPopup>
737 </Tooltip>
738 );
739}
740
741export function ThreadStatusLabel({
742 status,
743 compact = false,
744}: {
745 status: ThreadStatusPill;
746 compact?: boolean;
747}) {
748 if (compact) {
749 return (
750 <Tooltip>
751 <TooltipTrigger
752 render={
753 <span
754 aria-label={status.label}
755 className={`inline-flex size-3.5 shrink-0 items-center justify-center ${status.colorClass}`}
756 />
757 }
758 >
759 <span
760 className={`size-[9px] rounded-full ${status.dotClass} ${
761 status.pulse ? "animate-status-pulse" : ""
762 }`}
763 />
764 </TooltipTrigger>
765 <TooltipPopup side="top">{status.label}</TooltipPopup>
766 </Tooltip>
767 );
768 }
769
770 return (
771 <Tooltip>
772 <TooltipTrigger
773 render={
774 <span
775 aria-label={status.label}
776 className={`inline-flex items-center gap-1 text-[10px] ${status.colorClass}`}
777 />
778 }
779 >
780 <span
781 className={`h-1.5 w-1.5 rounded-full ${status.dotClass} ${
782 status.pulse ? "animate-status-pulse" : ""
783 }`}
784 />
785 <span className="hidden md:inline">{status.label}</span>
786 </TooltipTrigger>
787 <TooltipPopup side="top">{status.label}</TooltipPopup>
788 </Tooltip>
789 );
790}
791
792/**
793 * Non-interactive leading status icons for a thread row in compact contexts
794 * like the command palette. Shows the change request state icon (if present) and the
795 * thread status dot, matching the sidebar's leading indicators.
796 */
797export function ThreadRowLeadingStatus({
798 thread,
799 snapshot,
800}: {
801 thread: SidebarThreadSummary;
802 snapshot?: ThreadChangeRequestSnapshot | undefined;
803}) {
804 const { leaseLiveStatus, rowRef } = useSidebarRowSubscriptionLease(false);
805 // Observe the containing title even when this thread has no badge yet.
806 const statusRef = useCallback(
807 (node: HTMLSpanElement | null) => rowRef(node?.parentElement ?? null),
808 [rowRef],
809 );
810 const threadRef = scopeThreadRef(thread.environmentId, thread.id);
811 const localLastVisitedAt = useUiStateStore(
812 (state) => state.threadLastVisitedAtById[scopedThreadKey(threadRef)],
813 );
814 const lastVisitedAt = resolveThreadLastVisitedAt(thread.lastVisitedAt, localLastVisitedAt);
815 const threadProject = useProject(
816 useMemo(
817 () => scopeProjectRef(thread.environmentId, thread.projectId),
818 [thread.environmentId, thread.projectId],
819 ),
820 );
821 const threadProjectCwd = threadProject?.workspaceRoot ?? null;
822 const gitCwd = thread.worktreePath ?? threadProjectCwd;
823 const linkedPullRequest = useLinkedThreadPullRequest(
824 thread.environmentId,
825 thread.linkedPullRequest,
826 leaseLiveStatus,
827 );
828 const gitStatus = useEnvironmentQuery(
829 leaseLiveStatus &&
830 thread.linkedPullRequest == null &&
831 (thread.branch != null || thread.worktreePath !== null) &&
832 gitCwd !== null
833 ? vcsEnvironment.status({
834 environmentId: thread.environmentId,
835 input: { cwd: gitCwd },
836 })
837 : null,
838 );
839 const visibleGitStatus = useRetainedValue(
840 JSON.stringify([thread.environmentId, gitCwd]),
841 gitStatus.data,
842 );
843 const displayedPrInput = {
844 threadBranch: thread.branch,
845 gitStatus: visibleGitStatus,
846 snapshot,
847 retainTerminalOnBranchMismatch: thread.worktreePath === null,
848 linkedPullRequest: thread.linkedPullRequest,
849 linkedPullRequestStatus: linkedPullRequest,
850 };
851 const pr = resolveDisplayedThreadPr(displayedPrInput);
852 const prStatus = prStatusIndicator(pr, resolveDisplayedThreadPrProvider(displayedPrInput));
853 const threadStatus = resolveThreadStatusPill({
854 thread: {
855 ...thread,
856 lastVisitedAt,
857 },
858 });
859
860 const supportsMultiplePullRequests = useSupportsMultiplePullRequests(thread.environmentId);
861 const pendingLink =
862 pr === null && supportsMultiplePullRequests
863 ? resolveThreadCurrentPullRequestLink(thread.pullRequests)
864 : null;
865
866 return (
867 <span
868 ref={statusRef}
869 className={
870 prStatus || threadStatus ? "inline-flex shrink-0 items-center gap-1.5" : "contents"
871 }
872 >
873 {prStatus && pr ? (
874 <Tooltip>
875 <TooltipTrigger
876 render={
877 <span
878 aria-label={prStatus.tooltip}
879 className={`inline-flex items-center justify-center ${prStatus.colorClass}`}
880 />
881 }
882 >
883 <ChangeRequestStatusIcon state={pr.state} isDraft={pr.isDraft} className="size-3" />
884 </TooltipTrigger>
885 <TooltipPopup side="top">
886 <PrStatusTooltipContent status={prStatus} />
887 </TooltipPopup>
888 </Tooltip>
889 ) : null}
890 {pendingLink ? (
891 <PullRequestGlyph.pullRequest
892 className="size-3 text-muted-foreground"
893 aria-label={`PR #${pendingLink.number}, status pending`}
894 />
895 ) : null}
896 {threadStatus ? <ThreadStatusLabel status={threadStatus} /> : null}
897 </span>
898 );
899}
900
901/**
902 * Non-interactive trailing status icons for a thread row in compact contexts
903 * like the command palette. Shows a terminal-running indicator and a remote
904 * environment indicator, matching the sidebar's trailing indicators.
905 */
906export function ThreadRowTrailingStatus({ thread }: { thread: SidebarThreadSummary }) {
907 const runningTerminalIds = useThreadRunningTerminalIds({
908 environmentId: thread.environmentId,
909 threadId: thread.id,
910 });
911 const environment = useEnvironment(thread.environmentId);
912 const primaryEnvironmentId = usePrimaryEnvironmentId();
913 // No primary (the hosted app) means every thread is remote, and the machine
914 // glyph is what tells the environments apart.
915 const isRemoteThread = thread.environmentId !== primaryEnvironmentId;
916 const remoteEnvLabel = environment?.label ?? null;
917 const threadEnvironmentLabel = isRemoteThread ? (remoteEnvLabel ?? "Remote") : null;
918 const remoteMachine = resolveEnvironmentMachineKind(environment?.serverConfig ?? null);
919 const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
920
921 if (!terminalStatus && !isRemoteThread) {
922 return null;
923 }
924
925 return (
926 <span className="inline-flex shrink-0 items-center gap-1.5">
927 {terminalStatus ? (
928 <Tooltip>
929 <TooltipTrigger
930 render={
931 <span
932 role="img"
933 aria-label={terminalStatus.label}
934 className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
935 />
936 }
937 >
938 <TerminalIcon
939 className={`size-3 ${terminalStatus.pulse ? "animate-status-pulse" : ""}`}
940 />
941 </TooltipTrigger>
942 <TooltipPopup side="top">{terminalStatus.label}</TooltipPopup>
943 </Tooltip>
944 ) : null}
945 {isRemoteThread ? (
946 <Tooltip>
947 <TooltipTrigger
948 render={
949 <span
950 aria-label={threadEnvironmentLabel ?? "Remote"}
951 className="inline-flex items-center justify-center"
952 />
953 }
954 >
955 <EnvironmentMachineIcon
956 kind={remoteMachine}
957 className="size-3 text-muted-foreground/60"
958 />
959 </TooltipTrigger>
960 <TooltipPopup side="top">{threadEnvironmentLabel}</TooltipPopup>
961 </Tooltip>
962 ) : null}
963 </span>
964 );
965}