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