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 { 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;
62}
63
64export interface TerminalStatusIndicator {
65 label: "Terminal process running";
66 colorClass: string;
67 pulse: boolean;
68}
69
70export type ThreadPr = VcsStatusResult["pr"];
71
72export interface LinkedThreadPullRequestStatus {
73 readonly pr: NonNullable<ThreadPr>;
74 readonly sourceControlProvider: NonNullable<VcsStatusResult["sourceControlProvider"]>;
75}
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]);
111}
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 : link.url.includes("/pulls/")
125 ? "forgejo"
126 : "github";
127 return {
128 pr: {
129 number: link.number,
130 url: link.url,
131 title: snapshot.title,
132 state: snapshot.state,
133 isDraft: snapshot.isDraft,
134 headRef: snapshot.headBranch,
135 baseRef: snapshot.baseBranch,
136 ...(snapshot.updatedAt === null ? {} : { updatedAt: snapshot.updatedAt }),
137 },
138 sourceControlProvider: { kind, name: kind, baseUrl: "" },
139 };
140}
141
142export {
143 resolveThreadPullRequestBadge,
144 type ThreadPullRequestBadge,
145} from "@t3tools/shared/threadPullRequests";
146
147/** The glyph a row's badge wears: the layers icon for a stack, the pull-request one otherwise. */
148function ThreadPullRequestBadgeIcon({
149 icon,
150 className,
151}: {
152 icon: "stack" | "pull-request";
153 className?: string | undefined;
154}) {
155 const Icon = icon === "stack" ? LayersIcon : GitPullRequestArrowIcon;
156 return <Icon aria-hidden className={cn("size-3 shrink-0", className)} />;
157}
158
159/** The complete linked-PR control shared by the sidebar and composer footer. */
160export function ThreadPullRequestBadgeControl({
161 variant,
162 badge,
163 number,
164 url,
165 status,
166 onOpenStack,
167 onOpenPullRequest,
168}: {
169 variant: "underline" | "ghost";
170 badge: ThreadPullRequestBadge | null;
171 number?: number | undefined;
172 url?: string | undefined;
173 status: PrStatusIndicator | null;
174 onOpenStack: () => void;
175 onOpenPullRequest: (event: MouseEvent<HTMLAnchorElement>) => void;
176}) {
177 const isStack = badge?.kind === "stack";
178 const linkedCount = badge?.kind === "pull-request" && badge.others > 0 ? badge.others + 1 : null;
179 if (!isStack && (number === undefined || url === undefined)) return null;
180 const label = isStack
181 ? `Stack of ${badge.layers} pull requests, ${badge.state}`
182 : `${status?.tooltip ?? `PR #${number}, status pending`}${
183 badge?.kind === "pull-request" && badge.others > 0
184 ? `, and ${badge.others} more linked; overall ${badge.state}`
185 : ""
186 }`;
187 const className = cn(
188 variant === "ghost"
189 ? buttonVariants({ variant: "ghost", size: "xs" })
190 : "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",
191 "text-xs tabular-nums",
192 variant === "ghost" &&
193 "font-normal text-xs! active:scale-100 [--control-icon-color:currentColor]",
194 badge !== null && (isStack || linkedCount !== null)
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 );
237}
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 );
295}
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<ThreadPullRequestBadge["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 draft: "text-zinc-500 dark:text-zinc-400/80",
303};
304
305export function settledPrHoverColorClass(
306 state: NonNullable<ThreadPr>["state"],
307 isDraft = false,
308): string {
309 switch (state) {
310 case "open":
311 if (isDraft) {
312 return "group-hover/sidebar-row:text-zinc-500 dark:group-hover/sidebar-row:text-zinc-400/80";
313 }
314 return "group-hover/sidebar-row:text-emerald-600 dark:group-hover/sidebar-row:text-emerald-300/90";
315 case "merged":
316 return "group-hover/sidebar-row:text-violet-600 dark:group-hover/sidebar-row:text-violet-300/90";
317 case "closed":
318 return "group-hover/sidebar-row:text-red-600 dark:group-hover/sidebar-row:text-red-300/90";
319 }
320}
321
322export function prStatusIndicator(
323 pr: ThreadPr,
324 provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
325): PrStatusIndicator | null {
326 function formatPrState(pr: NonNullable<ThreadPr>): string {
327 if (pr.state === "open" && pr.isDraft === true) return "Draft";
328 return pr.state.charAt(0).toUpperCase() + pr.state.slice(1);
329 }
330
331 function formatPrStatusLead(pr: NonNullable<ThreadPr>, changeRequestShortName: string): string {
332 return `${changeRequestShortName} #${pr.number} - ${formatPrState(pr)}`;
333 }
334 if (!pr) return null;
335 const presentation = resolveChangeRequestPresentation(provider);
336
337 const tooltipLead = formatPrStatusLead(pr, presentation.shortName);
338 const tooltip = `${tooltipLead}: ${pr.title}`;
339
340 if (pr.state === "open") {
341 const isDraft = pr.isDraft === true;
342 return {
343 label: `${presentation.shortName} ${isDraft ? "draft" : "open"}`,
344 colorClass: isDraft
345 ? "text-zinc-500 dark:text-zinc-400/80"
346 : "text-emerald-600 dark:text-emerald-300/90",
347 tooltip,
348 tooltipLead,
349 tooltipTitle: pr.title,
350 url: pr.url,
351 };
352 }
353 if (pr.state === "closed") {
354 return {
355 label: `${presentation.shortName} closed`,
356 colorClass: "text-red-600 dark:text-red-300/90",
357 tooltip,
358 tooltipLead,
359 tooltipTitle: pr.title,
360 url: pr.url,
361 };
362 }
363 if (pr.state === "merged") {
364 return {
365 label: `${presentation.shortName} merged`,
366 colorClass: "text-violet-600 dark:text-violet-300/90",
367 tooltip,
368 tooltipLead,
369 tooltipTitle: pr.title,
370 url: pr.url,
371 };
372 }
373 return null;
374}
375
376export function ChangeRequestStatusIcon({
377 state,
378 isDraft = false,
379 className,
380}: Pick<NonNullable<ThreadPr>, "state"> & {
381 readonly isDraft?: boolean | undefined;
382 readonly className?: string | undefined;
383}) {
384 const presentation = resolvePullRequestState({ state, isDraft });
385 return <presentation.Icon className={className} />;
386}
387
388export function PrStatusTooltipContent({ status }: { status: PrStatusIndicator }) {
389 return (
390 <span className="flex max-w-[min(34rem,calc(100vw-2rem))] items-stretch overflow-hidden whitespace-nowrap">
391 <span className="shrink-0 pr-2 font-medium">{status.tooltipLead}</span>
392 <span className="min-h-4 shrink-0 border-border/70 border-l" aria-hidden="true" />
393 <span className="min-w-0 truncate pl-2">{status.tooltipTitle}</span>
394 </span>
395 );
396}
397
398export function resolveThreadPr(input: {
399 threadBranch: string | null;
400 gitStatus: VcsStatusResult | null;
401}): ThreadPr | null {
402 const { threadBranch, gitStatus } = input;
403 if (gitStatus === null) {
404 return null;
405 }
406
407 if (threadBranch === null || gitStatus.refName !== threadBranch) {
408 return null;
409 }
410
411 return gitStatus.pr ?? null;
412}
413
414/**
415 * Parent-held PR snapshot for Sidebar V2. Rows remount when settlement
416 * partitions move them, so terminal PR metadata must live above the row.
417 */
418export interface ThreadChangeRequestSnapshot {
419 readonly branch: string;
420 readonly pr: NonNullable<ThreadPr>;
421 readonly sourceControlProvider: VcsStatusResult["sourceControlProvider"] | undefined;
422 readonly linkedPullRequest?: ThreadLinkedPullRequest;
423}
424
425export const threadChangeRequestSnapshotsAtom = Atom.make<
426 ReadonlyMap<string, ThreadChangeRequestSnapshot>
427>(new Map()).pipe(Atom.keepAlive, Atom.withLabel("sidebar:thread-change-request-snapshots"));
428
429function isTerminalChangeRequestState(
430 state: NonNullable<ThreadPr>["state"],
431): state is "merged" | "closed" {
432 return state === "merged" || state === "closed";
433}
434
435function sourceControlProvidersEqual(
436 left: VcsStatusResult["sourceControlProvider"] | undefined,
437 right: VcsStatusResult["sourceControlProvider"] | undefined,
438): boolean {
439 if (left === right) return true;
440 if (left == null || right == null) return left == null && right == null;
441 return left.kind === right.kind && left.name === right.name && left.baseUrl === right.baseUrl;
442}
443
444function linkedPullRequestsEqual(
445 left: ThreadLinkedPullRequest | null | undefined,
446 right: ThreadLinkedPullRequest | null | undefined,
447): boolean {
448 if (left == null || right == null) return left == null && right == null;
449 return (
450 left.projectId === right.projectId &&
451 left.repository === right.repository &&
452 left.number === right.number &&
453 left.url === right.url
454 );
455}
456
457export function threadChangeRequestSnapshotsEqual(
458 left: ThreadChangeRequestSnapshot,
459 right: ThreadChangeRequestSnapshot,
460): boolean {
461 return (
462 left.branch === right.branch &&
463 left.pr.number === right.pr.number &&
464 left.pr.title === right.pr.title &&
465 left.pr.url === right.pr.url &&
466 left.pr.baseRef === right.pr.baseRef &&
467 left.pr.headRef === right.pr.headRef &&
468 left.pr.state === right.pr.state &&
469 left.pr.isDraft === right.pr.isDraft &&
470 (left.pr.updatedAt ?? null) === (right.pr.updatedAt ?? null) &&
471 sourceControlProvidersEqual(left.sourceControlProvider, right.sourceControlProvider) &&
472 linkedPullRequestsEqual(left.linkedPullRequest, right.linkedPullRequest)
473 );
474}
475
476export function setThreadChangeRequestSnapshot(
477 threadKey: string,
478 snapshot: ThreadChangeRequestSnapshot | null,
479): void {
480 appAtomRegistry.modify(threadChangeRequestSnapshotsAtom, (current) => {
481 const existing = current.get(threadKey);
482 if (snapshot === null) {
483 if (existing === undefined) return [false, current];
484 const next = new Map(current);
485 next.delete(threadKey);
486 return [true, next];
487 }
488 if (existing !== undefined && threadChangeRequestSnapshotsEqual(existing, snapshot)) {
489 return [false, current];
490 }
491 const next = new Map(current);
492 next.set(threadKey, snapshot);
493 return [true, next];
494 });
495}
496
497/**
498 * Authoritative snapshot update from live VCS status.
499 * - `undefined`: missing status, or a local checkout retaining a terminal PR — leave the map alone
500 * - `null`: no PR (without a retained terminal snapshot), a cleared branch, or a mismatch without a terminal PR — clear
501 * - snapshot: matching branch reports a PR — store/replace
502 */
503export function nextThreadChangeRequestSnapshot(input: {
504 threadBranch: string | null;
505 gitStatus: VcsStatusResult | null;
506 snapshot: ThreadChangeRequestSnapshot | null | undefined;
507 retainTerminalOnBranchMismatch: boolean;
508 linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
509 linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
510}): ThreadChangeRequestSnapshot | null | undefined {
511 const {
512 threadBranch,
513 gitStatus,
514 snapshot,
515 retainTerminalOnBranchMismatch,
516 linkedPullRequest,
517 linkedPullRequestStatus,
518 } = input;
519 if (linkedPullRequest != null) {
520 if (linkedPullRequestStatus === null || linkedPullRequestStatus === undefined) {
521 return linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest)
522 ? undefined
523 : null;
524 }
525 return {
526 branch: threadBranch ?? linkedPullRequestStatus.pr.headRef,
527 pr: linkedPullRequestStatus.pr,
528 sourceControlProvider: linkedPullRequestStatus.sourceControlProvider,
529 linkedPullRequest,
530 };
531 }
532 if (gitStatus === null) {
533 return snapshot?.linkedPullRequest === undefined ? undefined : null;
534 }
535 if (threadBranch === null) {
536 return null;
537 }
538 if (gitStatus.refName !== threadBranch) {
539 return retainTerminalOnBranchMismatch &&
540 snapshot != null &&
541 snapshot.linkedPullRequest === undefined &&
542 isTerminalChangeRequestState(snapshot.pr.state)
543 ? undefined
544 : null;
545 }
546 if (gitStatus.pr == null) {
547 if (
548 retainTerminalOnBranchMismatch &&
549 snapshot != null &&
550 snapshot.linkedPullRequest === undefined &&
551 isTerminalChangeRequestState(snapshot.pr.state)
552 ) {
553 return undefined;
554 }
555 return null;
556 }
557 return {
558 branch: threadBranch,
559 pr: gitStatus.pr,
560 sourceControlProvider: gitStatus.sourceControlProvider,
561 };
562}
563
564/**
565 * Live PR when the checkout matches the thread branch; otherwise, for local
566 * checkouts only, a cached merged/closed PR for the thread. Local thread
567 * metadata follows the shared checkout, so the cached branch intentionally
568 * survives that metadata changing to the newly checked-out branch. Open PRs
569 * are retained only while live status is absent and the branch still matches.
570 */
571export function resolveDisplayedThreadPr(input: {
572 threadBranch: string | null;
573 gitStatus: VcsStatusResult | null;
574 snapshot: ThreadChangeRequestSnapshot | null | undefined;
575 retainTerminalOnBranchMismatch: boolean;
576 linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
577 linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
578}): ThreadPr | null {
579 const {
580 threadBranch,
581 gitStatus,
582 snapshot,
583 retainTerminalOnBranchMismatch,
584 linkedPullRequest,
585 linkedPullRequestStatus,
586 } = input;
587 if (linkedPullRequest != null) {
588 return (
589 linkedPullRequestStatus?.pr ??
590 (linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest)
591 ? (snapshot?.pr ?? null)
592 : null)
593 );
594 }
595 if (
596 threadBranch !== null &&
597 gitStatus !== null &&
598 gitStatus.refName === threadBranch &&
599 gitStatus.pr != null
600 ) {
601 return gitStatus.pr;
602 }
603
604 if (
605 gitStatus === null &&
606 threadBranch !== null &&
607 snapshot?.branch === threadBranch &&
608 snapshot.linkedPullRequest === undefined
609 ) {
610 return snapshot.pr;
611 }
612
613 if (
614 threadBranch !== null &&
615 retainTerminalOnBranchMismatch &&
616 snapshot != null &&
617 snapshot.linkedPullRequest === undefined &&
618 isTerminalChangeRequestState(snapshot.pr.state)
619 ) {
620 return snapshot.pr;
621 }
622
623 return null;
624}
625
626export function resolveDisplayedThreadPrProvider(input: {
627 threadBranch: string | null;
628 gitStatus: VcsStatusResult | null;
629 snapshot: ThreadChangeRequestSnapshot | null | undefined;
630 retainTerminalOnBranchMismatch: boolean;
631 linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
632 linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
633}): VcsStatusResult["sourceControlProvider"] | undefined {
634 const {
635 threadBranch,
636 gitStatus,
637 snapshot,
638 retainTerminalOnBranchMismatch,
639 linkedPullRequest,
640 linkedPullRequestStatus,
641 } = input;
642 if (linkedPullRequest != null) {
643 return (
644 linkedPullRequestStatus?.sourceControlProvider ??
645 (linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest)
646 ? snapshot?.sourceControlProvider
647 : undefined)
648 );
649 }
650 if (
651 threadBranch !== null &&
652 gitStatus !== null &&
653 gitStatus.refName === threadBranch &&
654 gitStatus.pr != null
655 ) {
656 return gitStatus.sourceControlProvider;
657 }
658
659 if (
660 gitStatus === null &&
661 threadBranch !== null &&
662 snapshot?.branch === threadBranch &&
663 snapshot.linkedPullRequest === undefined
664 ) {
665 return snapshot.sourceControlProvider;
666 }
667
668 if (
669 threadBranch !== null &&
670 retainTerminalOnBranchMismatch &&
671 snapshot != null &&
672 snapshot.linkedPullRequest === undefined &&
673 isTerminalChangeRequestState(snapshot.pr.state)
674 ) {
675 return snapshot.sourceControlProvider;
676 }
677
678 return undefined;
679}
680
681export function terminalStatusFromRunningIds(
682 runningTerminalIds: ReadonlyArray<string>,
683): TerminalStatusIndicator | null {
684 if (runningTerminalIds.length === 0) {
685 return null;
686 }
687 return {
688 label: "Terminal process running",
689 colorClass: "text-teal-600 dark:text-teal-300/90",
690 pulse: true,
691 };
692}
693
694export function ThreadWorktreeIndicator({
695 thread,
696}: {
697 thread: Pick<SidebarThreadSummary, "id" | "branch" | "worktreePath">;
698}) {
699 const worktreePath = thread.worktreePath?.trim();
700 if (!worktreePath) {
701 return null;
702 }
703
704 const displayPath = formatWorktreePathForDisplay(worktreePath);
705 const tooltip = thread.branch
706 ? `Worktree: ${displayPath} (${thread.branch})`
707 : `Worktree: ${displayPath}`;
708
709 return (
710 <Tooltip>
711 <TooltipTrigger
712 render={
713 <span
714 role="img"
715 aria-label={tooltip}
716 data-testid={`thread-worktree-${thread.id}`}
717 className="inline-flex items-center justify-center"
718 />
719 }
720 >
721 <FolderGit2Icon className="size-3 text-muted-foreground/40" />
722 </TooltipTrigger>
723 <TooltipPopup side="top">{tooltip}</TooltipPopup>
724 </Tooltip>
725 );
726}
727
728export function ThreadStatusLabel({
729 status,
730 compact = false,
731}: {
732 status: ThreadStatusPill;
733 compact?: boolean;
734}) {
735 if (compact) {
736 return (
737 <Tooltip>
738 <TooltipTrigger
739 render={
740 <span
741 aria-label={status.label}
742 className={`inline-flex size-3.5 shrink-0 items-center justify-center ${status.colorClass}`}
743 />
744 }
745 >
746 <span
747 className={`size-[9px] rounded-full ${status.dotClass} ${
748 status.pulse ? "animate-status-pulse" : ""
749 }`}
750 />
751 </TooltipTrigger>
752 <TooltipPopup side="top">{status.label}</TooltipPopup>
753 </Tooltip>
754 );
755 }
756
757 return (
758 <Tooltip>
759 <TooltipTrigger
760 render={
761 <span
762 aria-label={status.label}
763 className={`inline-flex items-center gap-1 text-[10px] ${status.colorClass}`}
764 />
765 }
766 >
767 <span
768 className={`h-1.5 w-1.5 rounded-full ${status.dotClass} ${
769 status.pulse ? "animate-status-pulse" : ""
770 }`}
771 />
772 <span className="hidden md:inline">{status.label}</span>
773 </TooltipTrigger>
774 <TooltipPopup side="top">{status.label}</TooltipPopup>
775 </Tooltip>
776 );
777}
778
779/**
780 * Non-interactive leading status icons for a thread row in compact contexts
781 * like the command palette. Shows the change request state icon (if present) and the
782 * thread status dot, matching the sidebar's leading indicators.
783 */
784export function ThreadRowLeadingStatus({
785 thread,
786 snapshot,
787}: {
788 thread: SidebarThreadSummary;
789 snapshot?: ThreadChangeRequestSnapshot | undefined;
790}) {
791 const { leaseLiveStatus, rowRef } = useSidebarRowSubscriptionLease(false);
792 // Observe the containing title even when this thread has no badge yet.
793 const statusRef = useCallback(
794 (node: HTMLSpanElement | null) => rowRef(node?.parentElement ?? null),
795 [rowRef],
796 );
797 const threadRef = scopeThreadRef(thread.environmentId, thread.id);
798 const localLastVisitedAt = useUiStateStore(
799 (state) => state.threadLastVisitedAtById[scopedThreadKey(threadRef)],
800 );
801 const lastVisitedAt = resolveThreadLastVisitedAt(thread.lastVisitedAt, localLastVisitedAt);
802 const threadProject = useProject(
803 useMemo(
804 () => scopeProjectRef(thread.environmentId, thread.projectId),
805 [thread.environmentId, thread.projectId],
806 ),
807 );
808 const threadProjectCwd = threadProject?.workspaceRoot ?? null;
809 const gitCwd = thread.worktreePath ?? threadProjectCwd;
810 const linkedPullRequest = useLinkedThreadPullRequest(
811 thread.environmentId,
812 thread.linkedPullRequest,
813 leaseLiveStatus,
814 );
815 const gitStatus = useEnvironmentQuery(
816 leaseLiveStatus &&
817 thread.linkedPullRequest == null &&
818 (thread.branch != null || thread.worktreePath !== null) &&
819 gitCwd !== null
820 ? vcsEnvironment.status({
821 environmentId: thread.environmentId,
822 input: { cwd: gitCwd },
823 })
824 : null,
825 );
826 const visibleGitStatus = useRetainedValue(
827 JSON.stringify([thread.environmentId, gitCwd]),
828 gitStatus.data,
829 );
830 const displayedPrInput = {
831 threadBranch: thread.branch,
832 gitStatus: visibleGitStatus,
833 snapshot,
834 retainTerminalOnBranchMismatch: thread.worktreePath === null,
835 linkedPullRequest: thread.linkedPullRequest,
836 linkedPullRequestStatus: linkedPullRequest,
837 };
838 const pr = resolveDisplayedThreadPr(displayedPrInput);
839 const prStatus = prStatusIndicator(pr, resolveDisplayedThreadPrProvider(displayedPrInput));
840 const threadStatus = resolveThreadStatusPill({
841 thread: {
842 ...thread,
843 lastVisitedAt,
844 },
845 });
846
847 const supportsMultiplePullRequests = useSupportsMultiplePullRequests(thread.environmentId);
848 const pendingLink =
849 pr === null && supportsMultiplePullRequests
850 ? resolveThreadCurrentPullRequestLink(thread.pullRequests)
851 : null;
852
853 return (
854 <span
855 ref={statusRef}
856 className={
857 prStatus || threadStatus ? "inline-flex shrink-0 items-center gap-1.5" : "contents"
858 }
859 >
860 {prStatus && pr ? (
861 <Tooltip>
862 <TooltipTrigger
863 render={
864 <span
865 aria-label={prStatus.tooltip}
866 className={`inline-flex items-center justify-center ${prStatus.colorClass}`}
867 />
868 }
869 >
870 <ChangeRequestStatusIcon state={pr.state} isDraft={pr.isDraft} className="size-3" />
871 </TooltipTrigger>
872 <TooltipPopup side="top">
873 <PrStatusTooltipContent status={prStatus} />
874 </TooltipPopup>
875 </Tooltip>
876 ) : null}
877 {pendingLink ? (
878 <GitPullRequestArrowIcon
879 className="size-3 text-muted-foreground"
880 aria-label={`PR #${pendingLink.number}, status pending`}
881 />
882 ) : null}
883 {threadStatus ? <ThreadStatusLabel status={threadStatus} /> : null}
884 </span>
885 );
886}
887
888/**
889 * Non-interactive trailing status icons for a thread row in compact contexts
890 * like the command palette. Shows a terminal-running indicator and a remote
891 * environment indicator, matching the sidebar's trailing indicators.
892 */
893export function ThreadRowTrailingStatus({ thread }: { thread: SidebarThreadSummary }) {
894 const runningTerminalIds = useThreadRunningTerminalIds({
895 environmentId: thread.environmentId,
896 threadId: thread.id,
897 });
898 const environment = useEnvironment(thread.environmentId);
899 const primaryEnvironmentId = usePrimaryEnvironmentId();
900 // No primary (the hosted app) means every thread is remote, and the machine
901 // glyph is what tells the environments apart.
902 const isRemoteThread = thread.environmentId !== primaryEnvironmentId;
903 const remoteEnvLabel = environment?.label ?? null;
904 const threadEnvironmentLabel = isRemoteThread ? (remoteEnvLabel ?? "Remote") : null;
905 const remoteMachine = resolveEnvironmentMachineKind(environment?.serverConfig ?? null);
906 const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
907
908 if (!terminalStatus && !isRemoteThread) {
909 return null;
910 }
911
912 return (
913 <span className="inline-flex shrink-0 items-center gap-1.5">
914 {terminalStatus ? (
915 <Tooltip>
916 <TooltipTrigger
917 render={
918 <span
919 role="img"
920 aria-label={terminalStatus.label}
921 className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
922 />
923 }
924 >
925 <TerminalIcon
926 className={`size-3 ${terminalStatus.pulse ? "animate-status-pulse" : ""}`}
927 />
928 </TooltipTrigger>
929 <TooltipPopup side="top">{terminalStatus.label}</TooltipPopup>
930 </Tooltip>
931 ) : null}
932 {isRemoteThread ? (
933 <Tooltip>
934 <TooltipTrigger
935 render={
936 <span
937 aria-label={threadEnvironmentLabel ?? "Remote"}
938 className="inline-flex items-center justify-center"
939 />
940 }
941 >
942 <EnvironmentMachineIcon
943 kind={remoteMachine}
944 className="size-3 text-muted-foreground/60"
945 />
946 </TooltipTrigger>
947 <TooltipPopup side="top">{threadEnvironmentLabel}</TooltipPopup>
948 </Tooltip>
949 ) : null}
950 </span>
951 );
952}