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