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