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