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