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/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 { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
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 // A link records no host kind, so read it from the URL's change request path.
133 const kind = (
134 sourceControlClients.findByChangeRequestUrl(link.url) ?? sourceControlClients.get(undefined)
135 ).kind;
136 return {
137 pr: {
138 number: link.number,
139 url: link.url,
140 title: snapshot.title,
141 state: snapshot.state,
142 isDraft: snapshot.isDraft,
143 headRef: snapshot.headBranch,
144 baseRef: snapshot.baseBranch,
145 ...(snapshot.updatedAt === null ? {} : { updatedAt: snapshot.updatedAt }),
146 },
147 sourceControlProvider: { kind, name: kind, baseUrl: "" },
148 };
149}
150
151export {
152 resolveThreadPullRequestBadge,
153 type ThreadPullRequestBadge,
154} from "@t3tools/shared/threadPullRequests";
155
156export interface ThreadPullRequestBadgePresentation {
157 readonly Icon: PullRequestGlyphIcon;
158 readonly toneClassName: string;
159 readonly label: string;
160 readonly text: string | number;
161}
162
163/** Resolve the complete badge appearance before rendering it in the sidebar or composer. */
164export function resolveThreadPullRequestBadgePresentation({
165 badge,
166 number,
167 url,
168 status,
169}: {
170 readonly badge: ThreadPullRequestBadge | null;
171 readonly number?: number | undefined;
172 readonly url?: string | undefined;
173 readonly status: PrStatusIndicator | null;
174}): ThreadPullRequestBadgePresentation | null {
175 // The badge already folds every visible link into one state, draft included, so both the
176 // stack and the linked count index the shared table directly rather than the single-PR resolver.
177 if (badge?.kind === "stack") {
178 const aggregate = PULL_REQUEST_STATE_PRESENTATION[badge.state];
179 return {
180 Icon: PullRequestGlyph.stack,
181 toneClassName: aggregate.toneClassName,
182 label: `Stack of ${badge.layers} pull requests, ${aggregate.label.toLowerCase()}`,
183 text: badge.layers,
184 };
185 }
186 if (number === undefined || url === undefined) return null;
187
188 const tooltip = status?.tooltip ?? `PR #${number}, status pending`;
189 if (badge?.kind === "pull-request" && badge.others > 0) {
190 // Unrelated links fold into one state, so a count of merged PRs reads as merged.
191 const aggregate = PULL_REQUEST_STATE_PRESENTATION[badge.state];
192 return {
193 Icon: aggregate.Icon,
194 toneClassName: aggregate.toneClassName,
195 label: `${tooltip}, and ${badge.others} more linked; overall ${aggregate.label.toLowerCase()}`,
196 text: `+${badge.others + 1}`,
197 };
198 }
199 return {
200 Icon: status?.Icon ?? PullRequestGlyph.pullRequest,
201 toneClassName: status?.colorClass ?? "text-muted-foreground",
202 label: tooltip,
203 text: number,
204 };
205}
206
207/**
208 * The linked-PR badge shared by the sidebar and composer footer. The badge owns what it shows:
209 * the state glyph and number at the meta size, in the state's color. The caller owns the control
210 * it sits in through `render` (an inline link in a sidebar row, a toolbar control in the
211 * composer), and the badge fills in the behavior: a single PR is a link to it, while a stack or
212 * several linked PRs is a button that opens the thread's pull requests tab.
213 */
214export function ThreadPullRequestBadgeControl({
215 render,
216 badge,
217 pullRequests,
218 number,
219 url,
220 status,
221 onOpenList,
222 onOpenPullRequest,
223}: {
224 render: ReactElement<{ render?: useRender.RenderProp }>;
225 badge: ThreadPullRequestBadge | null;
226 pullRequests: ReadonlyArray<ThreadPullRequestLink>;
227 number?: number | undefined;
228 url?: string | undefined;
229 status: PrStatusIndicator | null;
230 onOpenList: () => void;
231 onOpenPullRequest: (event: MouseEvent<HTMLElement>, url?: string) => void;
232}) {
233 const presentation = resolveThreadPullRequestBadgePresentation({ badge, number, url, status });
234 if (presentation === null) return null;
235 return (
236 <PullRequestBadge
237 render={render}
238 presentation={presentation}
239 opensList={badge !== null && (badge.kind === "stack" || badge.others > 0)}
240 url={url}
241 number={number}
242 status={status}
243 pullRequests={pullRequests}
244 onOpenList={onOpenList}
245 onOpenPullRequest={onOpenPullRequest}
246 />
247 );
248}
249
250function PullRequestBadge({
251 render,
252 presentation,
253 opensList,
254 url,
255 number,
256 status,
257 pullRequests,
258 onOpenList,
259 onOpenPullRequest,
260}: {
261 render: ReactElement<{ render?: useRender.RenderProp }>;
262 presentation: NonNullable<ReturnType<typeof resolveThreadPullRequestBadgePresentation>>;
263 opensList: boolean;
264 url: string | undefined;
265 number: number | undefined;
266 status: PrStatusIndicator | null;
267 pullRequests: ReadonlyArray<ThreadPullRequestLink>;
268 onOpenList: () => void;
269 onOpenPullRequest: (event: MouseEvent<HTMLElement>, url?: string) => void;
270}) {
271 const onClick = opensList
272 ? (event: MouseEvent<HTMLElement>) => {
273 event.preventDefault();
274 event.stopPropagation();
275 onOpenList();
276 }
277 : onOpenPullRequest;
278 const element = opensList ? (
279 <button type="button" />
280 ) : (
281 <a href={url} target="_blank" rel="noopener noreferrer" />
282 );
283 // The caller's control (InlineButton, ComposerControl) renders as the link or stack button
284 // through its own render prop; useRender merges the badge's behavior into it.
285 const control = useRender({
286 render,
287 props: {
288 render: element,
289 "aria-label": presentation.label,
290 onPointerDown: (event: MouseEvent<HTMLElement>) => event.stopPropagation(),
291 onClick,
292 },
293 });
294 return (
295 <Tooltip>
296 <TooltipTrigger render={control}>
297 <span
298 className={cn("contents font-normal text-xs tabular-nums", presentation.toneClassName)}
299 >
300 <presentation.Icon aria-hidden className="size-3 shrink-0" />
301 {/* An element, not bare text: bare text takes its line box from the control, which
302 inherits the row's size, so beside a text-sm title it sat below the other meta. */}
303 <span>{presentation.text}</span>
304 </span>
305 </TooltipTrigger>
306 <TooltipPopup
307 side="top"
308 sideOffset={0}
309 variant="glass"
310 className="pointer-events-auto w-80 max-w-[calc(100vw-2rem)] text-left whitespace-normal"
311 >
312 {visibleThreadPullRequests(pullRequests).length > 0 ? (
313 <ThreadPullRequestsMiniList
314 pullRequests={pullRequests}
315 onOpenPullRequest={onOpenPullRequest}
316 />
317 ) : number !== undefined && url !== undefined ? (
318 <ul className="flex flex-col gap-1">
319 <ThreadPullRequestMiniListItem
320 number={number}
321 url={url}
322 title={status?.tooltipTitle ?? presentation.label}
323 presentation={presentation}
324 onOpenPullRequest={onOpenPullRequest}
325 />
326 </ul>
327 ) : null}
328 </TooltipPopup>
329 </Tooltip>
330 );
331}
332
333/**
334 * A miniature of the pull-requests panel for the thread tooltip: same order, same indentation,
335 * so the hover answers "what is in here" without opening the surface.
336 */
337export function ThreadPullRequestsMiniList({
338 pullRequests,
339 onOpenPullRequest,
340}: {
341 pullRequests: ReadonlyArray<ThreadPullRequestLink>;
342 onOpenPullRequest?: (event: MouseEvent<HTMLAnchorElement>, url: string) => void;
343}) {
344 const lines = useMemo(
345 () =>
346 pullRequestListLines(resolveThreadPullRequestChains(visibleThreadPullRequests(pullRequests))),
347 [pullRequests],
348 );
349 if (lines.length === 0) return null;
350 return (
351 <ul className="flex flex-col gap-1">
352 {lines.map((line) => {
353 const snapshot = line.link.snapshot;
354 const presentation =
355 snapshot === null
356 ? null
357 : resolvePullRequestState({ state: snapshot.state, isDraft: snapshot.isDraft });
358 return (
359 <ThreadPullRequestMiniListItem
360 key={`${line.link.host}/${line.link.repository}#${line.link.number}`}
361 number={line.link.number}
362 url={line.link.url}
363 title={snapshot?.title ?? line.link.repository}
364 presentation={presentation}
365 depth={line.depth}
366 onOpenPullRequest={onOpenPullRequest}
367 >
368 {line.stack ? (
369 <span className="ml-auto shrink-0 pl-1 text-3xs">
370 {line.stack.kind === "native" ? "stack" : "chain"} · {line.stack.size}
371 </span>
372 ) : null}
373 </ThreadPullRequestMiniListItem>
374 );
375 })}
376 </ul>
377 );
378}
379
380function ThreadPullRequestMiniListItem({
381 number,
382 url,
383 title,
384 presentation,
385 depth = 0,
386 onOpenPullRequest,
387 children,
388}: {
389 number: number;
390 url: string;
391 title: string;
392 presentation: Pick<ThreadPullRequestBadgePresentation, "Icon" | "toneClassName"> | null;
393 depth?: number;
394 onOpenPullRequest?: ((event: MouseEvent<HTMLAnchorElement>, url: string) => void) | undefined;
395 children?: ReactNode;
396}) {
397 const Icon = presentation?.Icon ?? PullRequestGlyph.pullRequest;
398 const content = (
399 <>
400 <Icon
401 aria-hidden
402 className={cn("size-3 shrink-0", presentation?.toneClassName ?? "stroke-muted-foreground")}
403 />
404 <span className="shrink-0 font-mono tabular-nums">#{number}</span>
405 <span className="min-w-0 truncate text-foreground/75">{title}</span>
406 {children}
407 </>
408 );
409 return (
410 <li style={{ paddingLeft: `${Math.min(depth, 3) * 0.75}rem` }}>
411 {onOpenPullRequest ? (
412 <a
413 href={url}
414 target="_blank"
415 rel="noopener noreferrer"
416 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"
417 onPointerDown={(event) => event.stopPropagation()}
418 onClick={(event) => onOpenPullRequest(event, url)}
419 >
420 {content}
421 </a>
422 ) : (
423 <div className="flex min-w-0 items-center gap-2">{content}</div>
424 )}
425 </li>
426 );
427}
428
429export function prStatusIndicator(
430 pr: ThreadPr,
431 provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
432): PrStatusIndicator | null {
433 if (!pr) return null;
434 const { shortLabel } = sourceControlClients.get(provider?.kind).changeRequest;
435 const state = resolvePullRequestState({ state: pr.state, isDraft: pr.isDraft === true });
436
437 const tooltipLead = `${shortLabel} #${pr.number} - ${state.label}`;
438 return {
439 label: `${shortLabel} ${state.label.toLowerCase()}`,
440 colorClass: state.toneClassName,
441 Icon: state.Icon,
442 tooltip: `${tooltipLead}: ${pr.title}`,
443 tooltipLead,
444 tooltipTitle: pr.title,
445 url: pr.url,
446 };
447}
448
449export function ChangeRequestStatusIcon({
450 state,
451 isDraft = false,
452 className,
453}: Pick<NonNullable<ThreadPr>, "state"> & {
454 readonly isDraft?: boolean | undefined;
455 readonly className?: string | undefined;
456}) {
457 const presentation = resolvePullRequestState({ state, isDraft });
458 return <presentation.Icon className={className} />;
459}
460
461export function PrStatusTooltipContent({ status }: { status: PrStatusIndicator }) {
462 return (
463 <span className="flex max-w-[min(34rem,calc(100vw-2rem))] items-stretch overflow-hidden whitespace-nowrap">
464 <span className="shrink-0 pr-2 font-medium">{status.tooltipLead}</span>
465 <span className="min-h-4 shrink-0 border-border/70 border-l" aria-hidden="true" />
466 <span className="min-w-0 truncate pl-2">{status.tooltipTitle}</span>
467 </span>
468 );
469}
470
471export function resolveThreadPr(input: {
472 threadBranch: string | null;
473 gitStatus: VcsStatusResult | null;
474}): ThreadPr | null {
475 const { threadBranch, gitStatus } = input;
476 if (gitStatus === null) {
477 return null;
478 }
479
480 if (threadBranch === null || gitStatus.refName !== threadBranch) {
481 return null;
482 }
483
484 return gitStatus.pr ?? null;
485}
486
487/**
488 * Parent-held PR snapshot for Sidebar V2. Rows remount when settlement
489 * partitions move them, so terminal PR metadata must live above the row.
490 */
491export interface ThreadChangeRequestSnapshot {
492 readonly branch: string;
493 readonly pr: NonNullable<ThreadPr>;
494 readonly sourceControlProvider: VcsStatusResult["sourceControlProvider"] | undefined;
495 readonly linkedPullRequest?: ThreadLinkedPullRequest;
496}
497
498export const threadChangeRequestSnapshotsAtom = Atom.make<
499 ReadonlyMap<string, ThreadChangeRequestSnapshot>
500>(new Map()).pipe(Atom.keepAlive, Atom.withLabel("sidebar:thread-change-request-snapshots"));
501
502function isTerminalChangeRequestState(
503 state: NonNullable<ThreadPr>["state"],
504): state is "merged" | "closed" {
505 return state === "merged" || state === "closed";
506}
507
508function sourceControlProvidersEqual(
509 left: VcsStatusResult["sourceControlProvider"] | undefined,
510 right: VcsStatusResult["sourceControlProvider"] | undefined,
511): boolean {
512 if (left === right) return true;
513 if (left == null || right == null) return left == null && right == null;
514 return left.kind === right.kind && left.name === right.name && left.baseUrl === right.baseUrl;
515}
516
517function linkedPullRequestsEqual(
518 left: ThreadLinkedPullRequest | null | undefined,
519 right: ThreadLinkedPullRequest | null | undefined,
520): boolean {
521 if (left == null || right == null) return left == null && right == null;
522 return (
523 left.projectId === right.projectId &&
524 left.repository === right.repository &&
525 left.number === right.number &&
526 left.url === right.url
527 );
528}
529
530export function threadChangeRequestSnapshotsEqual(
531 left: ThreadChangeRequestSnapshot,
532 right: ThreadChangeRequestSnapshot,
533): boolean {
534 return (
535 left.branch === right.branch &&
536 left.pr.number === right.pr.number &&
537 left.pr.title === right.pr.title &&
538 left.pr.url === right.pr.url &&
539 left.pr.baseRef === right.pr.baseRef &&
540 left.pr.headRef === right.pr.headRef &&
541 left.pr.state === right.pr.state &&
542 left.pr.isDraft === right.pr.isDraft &&
543 (left.pr.updatedAt ?? null) === (right.pr.updatedAt ?? null) &&
544 sourceControlProvidersEqual(left.sourceControlProvider, right.sourceControlProvider) &&
545 linkedPullRequestsEqual(left.linkedPullRequest, right.linkedPullRequest)
546 );
547}
548
549export function setThreadChangeRequestSnapshot(
550 threadKey: string,
551 snapshot: ThreadChangeRequestSnapshot | null,
552): void {
553 appAtomRegistry.modify(threadChangeRequestSnapshotsAtom, (current) => {
554 const existing = current.get(threadKey);
555 if (snapshot === null) {
556 if (existing === undefined) return [false, current];
557 const next = new Map(current);
558 next.delete(threadKey);
559 return [true, next];
560 }
561 if (existing !== undefined && threadChangeRequestSnapshotsEqual(existing, snapshot)) {
562 return [false, current];
563 }
564 const next = new Map(current);
565 next.set(threadKey, snapshot);
566 return [true, next];
567 });
568}
569
570/**
571 * Authoritative snapshot update from live VCS status.
572 * - `undefined`: missing status, or a local checkout retaining a terminal PR — leave the map alone
573 * - `null`: no PR (without a retained terminal snapshot), a cleared branch, or a mismatch without a terminal PR — clear
574 * - snapshot: matching branch reports a PR — store/replace
575 */
576export function nextThreadChangeRequestSnapshot(input: {
577 threadBranch: string | null;
578 gitStatus: VcsStatusResult | null;
579 snapshot: ThreadChangeRequestSnapshot | null | undefined;
580 retainTerminalOnBranchMismatch: boolean;
581 linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
582 linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
583}): ThreadChangeRequestSnapshot | null | undefined {
584 const {
585 threadBranch,
586 gitStatus,
587 snapshot,
588 retainTerminalOnBranchMismatch,
589 linkedPullRequest,
590 linkedPullRequestStatus,
591 } = input;
592 if (linkedPullRequest != null) {
593 if (linkedPullRequestStatus === null || linkedPullRequestStatus === undefined) {
594 return linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest)
595 ? undefined
596 : null;
597 }
598 return {
599 branch: threadBranch ?? linkedPullRequestStatus.pr.headRef,
600 pr: linkedPullRequestStatus.pr,
601 sourceControlProvider: linkedPullRequestStatus.sourceControlProvider,
602 linkedPullRequest,
603 };
604 }
605 if (gitStatus === null) {
606 return snapshot?.linkedPullRequest === undefined ? undefined : null;
607 }
608 if (threadBranch === null) {
609 return null;
610 }
611 if (gitStatus.refName !== threadBranch) {
612 return retainTerminalOnBranchMismatch &&
613 snapshot != null &&
614 snapshot.linkedPullRequest === undefined &&
615 isTerminalChangeRequestState(snapshot.pr.state)
616 ? undefined
617 : null;
618 }
619 if (gitStatus.pr == null) {
620 if (
621 retainTerminalOnBranchMismatch &&
622 snapshot != null &&
623 snapshot.linkedPullRequest === undefined &&
624 isTerminalChangeRequestState(snapshot.pr.state)
625 ) {
626 return undefined;
627 }
628 return null;
629 }
630 return {
631 branch: threadBranch,
632 pr: gitStatus.pr,
633 sourceControlProvider: gitStatus.sourceControlProvider,
634 };
635}
636
637/**
638 * Live PR when the checkout matches the thread branch; otherwise, for local
639 * checkouts only, a cached merged/closed PR for the thread. Local thread
640 * metadata follows the shared checkout, so the cached branch intentionally
641 * survives that metadata changing to the newly checked-out branch. Open PRs
642 * are retained only while live status is absent and the branch still matches.
643 */
644export function resolveDisplayedThreadPr(input: {
645 threadBranch: string | null;
646 gitStatus: VcsStatusResult | null;
647 snapshot: ThreadChangeRequestSnapshot | null | undefined;
648 retainTerminalOnBranchMismatch: boolean;
649 linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
650 linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
651}): ThreadPr | null {
652 const {
653 threadBranch,
654 gitStatus,
655 snapshot,
656 retainTerminalOnBranchMismatch,
657 linkedPullRequest,
658 linkedPullRequestStatus,
659 } = input;
660 if (linkedPullRequest != null) {
661 return (
662 linkedPullRequestStatus?.pr ??
663 (linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest)
664 ? (snapshot?.pr ?? null)
665 : null)
666 );
667 }
668 if (
669 threadBranch !== null &&
670 gitStatus !== null &&
671 gitStatus.refName === threadBranch &&
672 gitStatus.pr != null
673 ) {
674 return gitStatus.pr;
675 }
676
677 if (
678 gitStatus === null &&
679 threadBranch !== null &&
680 snapshot?.branch === threadBranch &&
681 snapshot.linkedPullRequest === undefined
682 ) {
683 return snapshot.pr;
684 }
685
686 if (
687 threadBranch !== null &&
688 retainTerminalOnBranchMismatch &&
689 snapshot != null &&
690 snapshot.linkedPullRequest === undefined &&
691 isTerminalChangeRequestState(snapshot.pr.state)
692 ) {
693 return snapshot.pr;
694 }
695
696 return null;
697}
698
699export function resolveDisplayedThreadPrProvider(input: {
700 threadBranch: string | null;
701 gitStatus: VcsStatusResult | null;
702 snapshot: ThreadChangeRequestSnapshot | null | undefined;
703 retainTerminalOnBranchMismatch: boolean;
704 linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
705 linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
706}): VcsStatusResult["sourceControlProvider"] | undefined {
707 const {
708 threadBranch,
709 gitStatus,
710 snapshot,
711 retainTerminalOnBranchMismatch,
712 linkedPullRequest,
713 linkedPullRequestStatus,
714 } = input;
715 if (linkedPullRequest != null) {
716 return (
717 linkedPullRequestStatus?.sourceControlProvider ??
718 (linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest)
719 ? snapshot?.sourceControlProvider
720 : undefined)
721 );
722 }
723 if (
724 threadBranch !== null &&
725 gitStatus !== null &&
726 gitStatus.refName === threadBranch &&
727 gitStatus.pr != null
728 ) {
729 return gitStatus.sourceControlProvider;
730 }
731
732 if (
733 gitStatus === null &&
734 threadBranch !== null &&
735 snapshot?.branch === threadBranch &&
736 snapshot.linkedPullRequest === undefined
737 ) {
738 return snapshot.sourceControlProvider;
739 }
740
741 if (
742 threadBranch !== null &&
743 retainTerminalOnBranchMismatch &&
744 snapshot != null &&
745 snapshot.linkedPullRequest === undefined &&
746 isTerminalChangeRequestState(snapshot.pr.state)
747 ) {
748 return snapshot.sourceControlProvider;
749 }
750
751 return undefined;
752}
753
754export function terminalStatusFromRunningIds(
755 runningTerminalIds: ReadonlyArray<string>,
756): TerminalStatusIndicator | null {
757 if (runningTerminalIds.length === 0) {
758 return null;
759 }
760 return {
761 label: "Terminal process running",
762 colorClass: "text-teal-600 dark:text-teal-300/90",
763 pulse: true,
764 };
765}
766
767/** Align newly started pulses with the document clock without a timer or frame loop. */
768export function synchronizeTerminalPulse(event: AnimationEvent<SVGSVGElement>) {
769 if (event.animationName !== "status-pulse") return;
770
771 for (const animation of event.currentTarget.getAnimations()) {
772 if ("animationName" in animation && animation.animationName === "status-pulse") {
773 animation.startTime = 0;
774 }
775 }
776}
777
778export function ThreadWorktreeIndicator({
779 thread,
780}: {
781 thread: Pick<SidebarThreadSummary, "id" | "branch" | "worktreePath">;
782}) {
783 const worktreePath = thread.worktreePath?.trim();
784 if (!worktreePath) {
785 return null;
786 }
787
788 const displayPath = formatWorktreePathForDisplay(worktreePath);
789 const tooltip = thread.branch
790 ? `Worktree: ${displayPath} (${thread.branch})`
791 : `Worktree: ${displayPath}`;
792
793 return (
794 <Tooltip>
795 <TooltipTrigger
796 render={
797 <span
798 role="img"
799 aria-label={tooltip}
800 data-testid={`thread-worktree-${thread.id}`}
801 className="inline-flex items-center justify-center"
802 />
803 }
804 >
805 <FolderGit2Icon className="size-3 text-muted-foreground/40" />
806 </TooltipTrigger>
807 <TooltipPopup side="top">{tooltip}</TooltipPopup>
808 </Tooltip>
809 );
810}
811
812export function ThreadStatusLabel({
813 status,
814 compact = false,
815}: {
816 status: ThreadStatusPill;
817 compact?: boolean;
818}) {
819 if (compact) {
820 return (
821 <Tooltip>
822 <TooltipTrigger
823 render={
824 <span
825 role="img"
826 aria-label={status.label}
827 className={`inline-flex size-3.5 shrink-0 items-center justify-center ${status.colorClass}`}
828 />
829 }
830 >
831 <span
832 className={`size-[9px] rounded-full ${status.dotClass} ${
833 status.pulse ? "animate-status-pulse" : ""
834 }`}
835 />
836 </TooltipTrigger>
837 <TooltipPopup side="top">{status.label}</TooltipPopup>
838 </Tooltip>
839 );
840 }
841
842 return (
843 <Tooltip>
844 <TooltipTrigger
845 render={
846 <span
847 role="img"
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, includeRemote: false },
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}