Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadStatusIndicators.tsx

1,122 lines35.8 KB

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;
75​
76export interface TerminalStatusIndicator {
77 label: "Terminal process running";
78 colorClass: string;
79 pulse: boolean;
81​
82export type ThreadPr = VcsStatusResult["pr"];
83​
84export interface LinkedThreadPullRequestStatus {
85 readonly pr: NonNullable<ThreadPr>;
86 readonly sourceControlProvider: NonNullable<VcsStatusResult["sourceControlProvider"]>;
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]);
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 };
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;
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 };
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 );
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>
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 {visibleThreadPullRequests(pullRequests).length > 0 ? (
320 <ThreadPullRequestsMiniList
321 pullRequests={pullRequests}
322 onOpenPullRequest={onOpenPullRequest}
323 />
324 ) : number !== undefined && url !== undefined ? (
325 <ul className="flex flex-col gap-1">
326 <ThreadPullRequestMiniListItem
327 number={number}
328 url={url}
329 title={status?.tooltipTitle ?? presentation.label}
330 presentation={presentation}
331 onOpenPullRequest={onOpenPullRequest}
332 />
333 </ul>
334 ) : null}
335 </TooltipPopup>
336 </Tooltip>
337 );
339​
340/**
341 * A miniature of the pull-requests panel for the thread tooltip: same order, same indentation,
342 * so the hover answers "what is in here" without opening the surface.
343 */
344export function ThreadPullRequestsMiniList({
345 pullRequests,
346 onOpenPullRequest,
347}: {
348 pullRequests: ReadonlyArray<ThreadPullRequestLink>;
349 onOpenPullRequest?: (event: MouseEvent<HTMLAnchorElement>, url: string) => void;
350}) {
351 const lines = useMemo(
352 () =>
353 pullRequestListLines(resolveThreadPullRequestChains(visibleThreadPullRequests(pullRequests))),
354 [pullRequests],
355 );
356 if (lines.length === 0) return null;
357 return (
358 <ul className="flex flex-col gap-1">
359 {lines.map((line) => {
360 const snapshot = line.link.snapshot;
361 const presentation =
362 snapshot === null
363 ? null
364 : resolvePullRequestState({ state: snapshot.state, isDraft: snapshot.isDraft });
365 return (
366 <ThreadPullRequestMiniListItem
367 key={`${line.link.host}/${line.link.repository}#${line.link.number}`}
368 number={line.link.number}
369 url={line.link.url}
370 title={snapshot?.title ?? line.link.repository}
371 presentation={presentation}
372 depth={line.depth}
373 onOpenPullRequest={onOpenPullRequest}
374 >
375 {line.stack ? (
376 <span className="ml-auto shrink-0 pl-1 text-3xs">
377 {line.stack.kind === "native" ? "stack" : "chain"} · {line.stack.size}
378 </span>
379 ) : null}
380 </ThreadPullRequestMiniListItem>
381 );
382 })}
383 </ul>
384 );
386​
387function ThreadPullRequestMiniListItem({
388 number,
389 url,
390 title,
391 presentation,
392 depth = 0,
393 onOpenPullRequest,
394 children,
395}: {
396 number: number;
397 url: string;
398 title: string;
399 presentation: Pick<ThreadPullRequestBadgePresentation, "Icon" | "toneClassName"> | null;
400 depth?: number;
401 onOpenPullRequest?: ((event: MouseEvent<HTMLAnchorElement>, url: string) => void) | undefined;
402 children?: ReactNode;
403}) {
404 const Icon = presentation?.Icon ?? PullRequestGlyph.pullRequest;
405 const content = (
406 <>
407 <Icon
408 aria-hidden
409 className={cn("size-3 shrink-0", presentation?.toneClassName ?? "stroke-muted-foreground")}
410 />
411 <span className="shrink-0 font-mono tabular-nums">#{number}</span>
412 <span className="min-w-0 truncate text-foreground/75">{title}</span>
413 {children}
414 </>
415 );
416 return (
417 <li style={{ paddingLeft: `${Math.min(depth, 3) * 0.75}rem` }}>
418 {onOpenPullRequest ? (
419 <a
420 href={url}
421 target="_blank"
422 rel="noopener noreferrer"
423 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"
424 onPointerDown={(event) => event.stopPropagation()}
425 onClick={(event) => onOpenPullRequest(event, url)}
426 >
427 {content}
428 </a>
429 ) : (
430 <div className="flex min-w-0 items-center gap-2">{content}</div>
431 )}
432 </li>
433 );
435​
436export function prStatusIndicator(
437 pr: ThreadPr,
438 provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
439): PrStatusIndicator | null {
440 if (!pr) return null;
441 const { shortLabel } = sourceControlClients.get(provider?.kind).changeRequest;
442 const state = resolvePullRequestState({ state: pr.state, isDraft: pr.isDraft === true });
443​
444 const tooltipLead = `${shortLabel} #${pr.number} - ${state.label}`;
445 return {
446 label: `${shortLabel} ${state.label.toLowerCase()}`,
447 colorClass: state.toneClassName,
448 Icon: state.Icon,
449 tooltip: `${tooltipLead}: ${pr.title}`,
450 tooltipLead,
451 tooltipTitle: pr.title,
452 url: pr.url,
453 };
455​
456export function ChangeRequestStatusIcon({
457 state,
458 isDraft = false,
459 className,
460}: Pick<NonNullable<ThreadPr>, "state"> & {
461 readonly isDraft?: boolean | undefined;
462 readonly className?: string | undefined;
463}) {
464 const presentation = resolvePullRequestState({ state, isDraft });
465 return <presentation.Icon className={className} />;
467​
468export function PrStatusTooltipContent({ status }: { status: PrStatusIndicator }) {
469 return (
470 <span className="flex max-w-[min(34rem,calc(100vw-2rem))] items-stretch overflow-hidden whitespace-nowrap">
471 <span className="shrink-0 pr-2 font-medium">{status.tooltipLead}</span>
472 <span className="min-h-4 shrink-0 border-border/70 border-l" aria-hidden="true" />
473 <span className="min-w-0 truncate pl-2">{status.tooltipTitle}</span>
474 </span>
475 );
477​
478export function resolveThreadPr(input: {
479 threadBranch: string | null;
480 gitStatus: VcsStatusResult | null;
481}): ThreadPr | null {
482 const { threadBranch, gitStatus } = input;
483 if (gitStatus === null) {
484 return null;
485 }
486​
487 if (threadBranch === null || gitStatus.refName !== threadBranch) {
488 return null;
489 }
490​
491 return gitStatus.pr ?? null;
493​
494/**
495 * Parent-held PR snapshot for Sidebar V2. Rows remount when settlement
496 * partitions move them, so terminal PR metadata must live above the row.
497 */
498export interface ThreadChangeRequestSnapshot {
499 readonly branch: string;
500 readonly pr: NonNullable<ThreadPr>;
501 readonly sourceControlProvider: VcsStatusResult["sourceControlProvider"] | undefined;
502 readonly linkedPullRequest?: ThreadLinkedPullRequest;
504​
505export const threadChangeRequestSnapshotsAtom = Atom.make<
506 ReadonlyMap<string, ThreadChangeRequestSnapshot>
507>(new Map()).pipe(Atom.keepAlive, Atom.withLabel("sidebar:thread-change-request-snapshots"));
508​
509function isTerminalChangeRequestState(
510 state: NonNullable<ThreadPr>["state"],
511): state is "merged" | "closed" {
512 return state === "merged" || state === "closed";
514​
515function sourceControlProvidersEqual(
516 left: VcsStatusResult["sourceControlProvider"] | undefined,
517 right: VcsStatusResult["sourceControlProvider"] | undefined,
518): boolean {
519 if (left === right) return true;
520 if (left == null || right == null) return left == null && right == null;
521 return left.kind === right.kind && left.name === right.name && left.baseUrl === right.baseUrl;
523​
524function linkedPullRequestsEqual(
525 left: ThreadLinkedPullRequest | null | undefined,
526 right: ThreadLinkedPullRequest | null | undefined,
527): boolean {
528 if (left == null || right == null) return left == null && right == null;
529 return (
530 left.projectId === right.projectId &&
531 left.repository === right.repository &&
532 left.number === right.number &&
533 left.url === right.url
534 );
536​
537export function threadChangeRequestSnapshotsEqual(
538 left: ThreadChangeRequestSnapshot,
539 right: ThreadChangeRequestSnapshot,
540): boolean {
541 return (
542 left.branch === right.branch &&
543 left.pr.number === right.pr.number &&
544 left.pr.title === right.pr.title &&
545 left.pr.url === right.pr.url &&
546 left.pr.baseRef === right.pr.baseRef &&
547 left.pr.headRef === right.pr.headRef &&
548 left.pr.state === right.pr.state &&
549 left.pr.isDraft === right.pr.isDraft &&
550 (left.pr.updatedAt ?? null) === (right.pr.updatedAt ?? null) &&
551 sourceControlProvidersEqual(left.sourceControlProvider, right.sourceControlProvider) &&
552 linkedPullRequestsEqual(left.linkedPullRequest, right.linkedPullRequest)
553 );
555​
556export function setThreadChangeRequestSnapshot(
557 threadKey: string,
558 snapshot: ThreadChangeRequestSnapshot | null,
559): void {
560 appAtomRegistry.modify(threadChangeRequestSnapshotsAtom, (current) => {
561 const existing = current.get(threadKey);
562 if (snapshot === null) {
563 if (existing === undefined) return [false, current];
564 const next = new Map(current);
565 next.delete(threadKey);
566 return [true, next];
567 }
568 if (existing !== undefined && threadChangeRequestSnapshotsEqual(existing, snapshot)) {
569 return [false, current];
570 }
571 const next = new Map(current);
572 next.set(threadKey, snapshot);
573 return [true, next];
574 });
576​
577/**
578 * Authoritative snapshot update from live VCS status.
579 * - `undefined`: missing status, or a local checkout retaining a terminal PR — leave the map alone
580 * - `null`: no PR (without a retained terminal snapshot), a cleared branch, or a mismatch without a terminal PR — clear
581 * - snapshot: matching branch reports a PR — store/replace
582 */
583export function nextThreadChangeRequestSnapshot(input: {
584 threadBranch: string | null;
585 gitStatus: VcsStatusResult | null;
586 snapshot: ThreadChangeRequestSnapshot | null | undefined;
587 retainTerminalOnBranchMismatch: boolean;
588 linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
589 linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
590}): ThreadChangeRequestSnapshot | null | undefined {
591 const {
592 threadBranch,
593 gitStatus,
594 snapshot,
595 retainTerminalOnBranchMismatch,
596 linkedPullRequest,
597 linkedPullRequestStatus,
598 } = input;
599 if (linkedPullRequest != null) {
600 if (linkedPullRequestStatus === null || linkedPullRequestStatus === undefined) {
601 return linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest)
602 ? undefined
603 : null;
604 }
605 return {
606 branch: threadBranch ?? linkedPullRequestStatus.pr.headRef,
607 pr: linkedPullRequestStatus.pr,
608 sourceControlProvider: linkedPullRequestStatus.sourceControlProvider,
609 linkedPullRequest,
610 };
611 }
612 if (gitStatus === null) {
613 return snapshot?.linkedPullRequest === undefined ? undefined : null;
614 }
615 if (threadBranch === null) {
616 return null;
617 }
618 if (gitStatus.refName !== threadBranch) {
619 return retainTerminalOnBranchMismatch &&
620 snapshot != null &&
621 snapshot.linkedPullRequest === undefined &&
622 isTerminalChangeRequestState(snapshot.pr.state)
623 ? undefined
624 : null;
625 }
626 if (gitStatus.pr == null) {
627 if (
628 retainTerminalOnBranchMismatch &&
629 snapshot != null &&
630 snapshot.linkedPullRequest === undefined &&
631 isTerminalChangeRequestState(snapshot.pr.state)
632 ) {
633 return undefined;
634 }
635 return null;
636 }
637 return {
638 branch: threadBranch,
639 pr: gitStatus.pr,
640 sourceControlProvider: gitStatus.sourceControlProvider,
641 };
643​
644/**
645 * Live PR when the checkout matches the thread branch; otherwise, for local
646 * checkouts only, a cached merged/closed PR for the thread. Local thread
647 * metadata follows the shared checkout, so the cached branch intentionally
648 * survives that metadata changing to the newly checked-out branch. Open PRs
649 * are retained only while live status is absent and the branch still matches.
650 */
651export function resolveDisplayedThreadPr(input: {
652 threadBranch: string | null;
653 gitStatus: VcsStatusResult | null;
654 snapshot: ThreadChangeRequestSnapshot | null | undefined;
655 retainTerminalOnBranchMismatch: boolean;
656 linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
657 linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
658}): ThreadPr | null {
659 const {
660 threadBranch,
661 gitStatus,
662 snapshot,
663 retainTerminalOnBranchMismatch,
664 linkedPullRequest,
665 linkedPullRequestStatus,
666 } = input;
667 if (linkedPullRequest != null) {
668 return (
669 linkedPullRequestStatus?.pr ??
670 (linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest)
671 ? (snapshot?.pr ?? null)
672 : null)
673 );
674 }
675 if (
676 threadBranch !== null &&
677 gitStatus !== null &&
678 gitStatus.refName === threadBranch &&
679 gitStatus.pr != null
680 ) {
681 return gitStatus.pr;
682 }
683​
684 if (
685 gitStatus === null &&
686 threadBranch !== null &&
687 snapshot?.branch === threadBranch &&
688 snapshot.linkedPullRequest === undefined
689 ) {
690 return snapshot.pr;
691 }
692​
693 if (
694 threadBranch !== null &&
695 retainTerminalOnBranchMismatch &&
696 snapshot != null &&
697 snapshot.linkedPullRequest === undefined &&
698 isTerminalChangeRequestState(snapshot.pr.state)
699 ) {
700 return snapshot.pr;
701 }
702​
703 return null;
705​
706export function resolveDisplayedThreadPrProvider(input: {
707 threadBranch: string | null;
708 gitStatus: VcsStatusResult | null;
709 snapshot: ThreadChangeRequestSnapshot | null | undefined;
710 retainTerminalOnBranchMismatch: boolean;
711 linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
712 linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
713}): VcsStatusResult["sourceControlProvider"] | undefined {
714 const {
715 threadBranch,
716 gitStatus,
717 snapshot,
718 retainTerminalOnBranchMismatch,
719 linkedPullRequest,
720 linkedPullRequestStatus,
721 } = input;
722 if (linkedPullRequest != null) {
723 return (
724 linkedPullRequestStatus?.sourceControlProvider ??
725 (linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest)
726 ? snapshot?.sourceControlProvider
727 : undefined)
728 );
729 }
730 if (
731 threadBranch !== null &&
732 gitStatus !== null &&
733 gitStatus.refName === threadBranch &&
734 gitStatus.pr != null
735 ) {
736 return gitStatus.sourceControlProvider;
737 }
738​
739 if (
740 gitStatus === null &&
741 threadBranch !== null &&
742 snapshot?.branch === threadBranch &&
743 snapshot.linkedPullRequest === undefined
744 ) {
745 return snapshot.sourceControlProvider;
746 }
747​
748 if (
749 threadBranch !== null &&
750 retainTerminalOnBranchMismatch &&
751 snapshot != null &&
752 snapshot.linkedPullRequest === undefined &&
753 isTerminalChangeRequestState(snapshot.pr.state)
754 ) {
755 return snapshot.sourceControlProvider;
756 }
757​
758 return undefined;
760​
761export function terminalStatusFromRunningIds(
762 runningTerminalIds: ReadonlyArray<string>,
763): TerminalStatusIndicator | null {
764 if (runningTerminalIds.length === 0) {
765 return null;
766 }
767 return {
768 label: "Terminal process running",
769 colorClass: "text-teal-600 dark:text-teal-300/90",
770 pulse: true,
771 };
773​
774/** Align newly started pulses with the document clock without a timer or frame loop. */
775export function synchronizeTerminalPulse(event: AnimationEvent<SVGSVGElement>) {
776 if (event.animationName !== "status-pulse") return;
777​
778 for (const animation of event.currentTarget.getAnimations()) {
779 if ("animationName" in animation && animation.animationName === "status-pulse") {
780 animation.startTime = 0;
781 }
782 }
784​
785export function ThreadWorktreeIndicator({
786 thread,
787}: {
788 thread: Pick<SidebarThreadSummary, "id" | "branch" | "worktreePath">;
789}) {
790 const worktreePath = thread.worktreePath?.trim();
791 if (!worktreePath) {
792 return null;
793 }
794​
795 const displayPath = formatWorktreePathForDisplay(worktreePath);
796 const tooltip = thread.branch
797 ? `Worktree: ${displayPath} (${thread.branch})`
798 : `Worktree: ${displayPath}`;
799​
800 return (
801 <Tooltip>
802 <TooltipTrigger
803 render={
804 <span
805 role="img"
806 aria-label={tooltip}
807 data-testid={`thread-worktree-${thread.id}`}
808 className="inline-flex items-center justify-center"
809 />
810 }
811 >
812 <FolderGit2Icon className="size-3 text-muted-foreground/40" />
813 </TooltipTrigger>
814 <TooltipPopup side="top">{tooltip}</TooltipPopup>
815 </Tooltip>
816 );
818​
819export function ThreadStatusLabel({
820 status,
821 compact = false,
822}: {
823 status: ThreadStatusPill;
824 compact?: boolean;
825}) {
826 if (compact) {
827 return (
828 <Tooltip>
829 <TooltipTrigger
830 render={
831 <span
832 role="img"
833 aria-label={status.label}
834 className={`inline-flex size-3.5 shrink-0 items-center justify-center ${status.colorClass}`}
835 />
836 }
837 >
838 <span
839 className={`size-[9px] rounded-full ${status.dotClass} ${
840 status.pulse ? "animate-status-pulse" : ""
841 }`}
842 />
843 </TooltipTrigger>
844 <TooltipPopup side="top">{status.label}</TooltipPopup>
845 </Tooltip>
846 );
847 }
848​
849 return (
850 <Tooltip>
851 <TooltipTrigger
852 render={
853 <span
854 role="img"
855 aria-label={status.label}
856 className={`inline-flex items-center gap-1 text-3xs ${status.colorClass}`}
857 />
858 }
859 >
860 <span
861 className={`h-1.5 w-1.5 rounded-full ${status.dotClass} ${
862 status.pulse ? "animate-status-pulse" : ""
863 }`}
864 />
865 <span className="hidden md:inline">{status.label}</span>
866 </TooltipTrigger>
867 <TooltipPopup side="top">{status.label}</TooltipPopup>
868 </Tooltip>
869 );
871​
872/**
873 * Non-interactive leading status icons for a thread row in compact contexts
874 * like the command palette. Shows the change request state icon (if present) and the
875 * thread status dot, matching the sidebar's leading indicators.
876 */
877export function ThreadRowLeadingStatus({
878 thread,
879 snapshot,
880}: {
881 thread: SidebarThreadSummary;
882 snapshot?: ThreadChangeRequestSnapshot | undefined;
883}) {
884 const { leaseLiveStatus, rowRef } = useSidebarRowSubscriptionLease(false);
885 // Observe the containing title even when this thread has no badge yet.
886 const statusRef = useCallback(
887 (node: HTMLSpanElement | null) => rowRef(node?.parentElement ?? null),
888 [rowRef],
889 );
890 const threadRef = scopeThreadRef(thread.environmentId, thread.id);
891 const localLastVisitedAt = useUiStateStore(
892 (state) => state.threadLastVisitedAtById[scopedThreadKey(threadRef)],
893 );
894 const lastVisitedAt = resolveThreadLastVisitedAt(thread.lastVisitedAt, localLastVisitedAt);
895 const threadProject = useProject(
896 useMemo(
897 () => scopeProjectRef(thread.environmentId, thread.projectId),
898 [thread.environmentId, thread.projectId],
899 ),
900 );
901 const threadProjectCwd = threadProject?.workspaceRoot ?? null;
902 const gitCwd = thread.worktreePath ?? threadProjectCwd;
903 const linkedPullRequest = useLinkedThreadPullRequest(
904 thread.environmentId,
905 thread.linkedPullRequest,
906 leaseLiveStatus,
907 );
908 const gitStatus = useEnvironmentQuery(
909 leaseLiveStatus &&
910 thread.linkedPullRequest == null &&
911 (thread.branch != null || thread.worktreePath !== null) &&
912 gitCwd !== null
913 ? vcsEnvironment.status({
914 environmentId: thread.environmentId,
915 input: { cwd: gitCwd, includeRemote: false },
916 })
917 : null,
918 );
919 const visibleGitStatus = useRetainedValue(
920 JSON.stringify([thread.environmentId, gitCwd]),
921 gitStatus.data,
922 );
923 const displayedPrInput = {
924 threadBranch: thread.branch,
925 gitStatus: visibleGitStatus,
926 snapshot,
927 retainTerminalOnBranchMismatch: thread.worktreePath === null,
928 linkedPullRequest: thread.linkedPullRequest,
929 linkedPullRequestStatus: linkedPullRequest,
930 };
931 const pr = resolveDisplayedThreadPr(displayedPrInput);
932 const prStatus = prStatusIndicator(pr, resolveDisplayedThreadPrProvider(displayedPrInput));
933 const threadStatus = resolveThreadStatusPill({
934 thread: {
935 ...thread,
936 lastVisitedAt,
937 },
938 });
939​
940 const supportsMultiplePullRequests = useSupportsMultiplePullRequests(thread.environmentId);
941 const pendingLink =
942 pr === null && supportsMultiplePullRequests
943 ? resolveThreadCurrentPullRequestLink(thread.pullRequests)
944 : null;
945​
946 return (
947 <span
948 ref={statusRef}
949 className={
950 prStatus || threadStatus ? "inline-flex shrink-0 items-center gap-1.5" : "contents"
951 }
952 >
953 {prStatus && pr ? (
954 <Tooltip>
955 <TooltipTrigger
956 render={
957 <span
958 aria-label={prStatus.tooltip}
959 className={`inline-flex items-center justify-center ${prStatus.colorClass}`}
960 />
961 }
962 >
963 <ChangeRequestStatusIcon state={pr.state} isDraft={pr.isDraft} className="size-3" />
964 </TooltipTrigger>
965 <TooltipPopup side="top">
966 <PrStatusTooltipContent status={prStatus} />
967 </TooltipPopup>
968 </Tooltip>
969 ) : null}
970 {pendingLink ? (
971 <PullRequestGlyph.pullRequest
972 className="size-3 text-muted-foreground"
973 aria-label={`PR #${pendingLink.number}, status pending`}
974 />
975 ) : null}
976 {threadStatus ? <ThreadStatusLabel status={threadStatus} /> : null}
977 </span>
978 );
980​
981/**
982 * Non-interactive trailing status icons for a thread row in compact contexts
983 * like the command palette. Shows a terminal-running indicator and a remote
984 * environment indicator, matching the sidebar's trailing indicators.
985 */
986export function ThreadRowTrailingStatus({ thread }: { thread: SidebarThreadSummary }) {
987 const runningTerminalIds = useThreadRunningTerminalIds({
988 environmentId: thread.environmentId,
989 threadId: thread.id,
990 });
991 const environment = useEnvironment(thread.environmentId);
992 const primaryEnvironmentId = usePrimaryEnvironmentId();
993 // No primary (the hosted app) means every thread is remote, and the machine
994 // glyph is what tells the environments apart.
995 const isRemoteThread = thread.environmentId !== primaryEnvironmentId;
996 const remoteEnvLabel = environment?.label ?? null;
997 const threadEnvironmentLabel = isRemoteThread ? (remoteEnvLabel ?? "Remote") : null;
998 const remoteMachine = resolveEnvironmentMachineKind(environment?.serverConfig ?? null);
999 const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
1000​
1001 if (!terminalStatus && !isRemoteThread) {
1002 return null;
1004​
1005 return (
1006 <span className="inline-flex shrink-0 items-center gap-1.5">
1007 {terminalStatus ? (
1008 <Tooltip>
1009 <TooltipTrigger
1010 render={
1011 <span
1012 role="img"
1013 aria-label={terminalStatus.label}
1014 className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
1015 />
1018 <TerminalIcon
1019 className={`size-3 ${terminalStatus.pulse ? "motion-safe:animate-status-pulse" : ""}`}
1020 onAnimationStart={synchronizeTerminalPulse}
1021 />
1022 </TooltipTrigger>
1023 <TooltipPopup side="top">{terminalStatus.label}</TooltipPopup>
1024 </Tooltip>
1025 ) : null}
1026 {isRemoteThread ? (
1027 <Tooltip>
1028 <TooltipTrigger
1029 render={
1030 <span
1031 aria-label={threadEnvironmentLabel ?? "Remote"}
1032 className="inline-flex items-center justify-center"
1033 />
1036 <EnvironmentMachineIcon
1037 kind={remoteMachine}
1038 className="size-3 text-muted-foreground/60"
1039 />
1040 </TooltipTrigger>
1041 <TooltipPopup side="top">{threadEnvironmentLabel}</TooltipPopup>
1042 </Tooltip>
1043 ) : null}
1044 </span>
1045 );
1047​
1048/** Number presentation for compact thread search results. */
1049function ThreadPullRequestNumber({
1050 number,
1051 className,
1052 ...props
1053}: ComponentProps<"span"> & { number: number }) {
1054 return (
1055 <span {...props} className={cn("shrink-0 text-xs tabular-nums", className)}>
1056 #{number}
1057 </span>
1058 );
1060​
1061function settledPrHoverColorClass(state: NonNullable<ThreadPr>["state"], isDraft = false): string {
1062 switch (state) {
1063 case "open":
1064 if (isDraft) {
1065 return "group-hover/sidebar-row:text-zinc-500 dark:group-hover/sidebar-row:text-zinc-400/80";
1067 return "group-hover/sidebar-row:text-emerald-600 dark:group-hover/sidebar-row:text-emerald-300/90";
1068 case "merged":
1069 return "group-hover/sidebar-row:text-violet-600 dark:group-hover/sidebar-row:text-violet-300/90";
1070 case "closed":
1071 return "group-hover/sidebar-row:text-red-600 dark:group-hover/sidebar-row:text-red-300/90";
1074​
1075export function ThreadSearchPullRequestNumber({
1076 thread,
1077 query,
1078 enabled = true,
1079 settled = false,
1080}: {
1081 thread: SidebarThreadSummary;
1082 query: string;
1083 enabled?: boolean;
1084 settled?: boolean;
1085}) {
1086 const matchedLink = visibleThreadPullRequests(thread.pullRequests).find((pr) =>
1087 pullRequestMatchesSearchQuery({ pullRequests: [pr] }, query),
1088 );
1089 const fallbackCandidates =
1090 thread.pullRequests.length === 0
1091 ? [thread.linkedPullRequest, thread.branchPullRequest]
1092 : [thread.branchPullRequest];
1093 const legacyReference = matchedLink
1094 ? undefined
1095 : fallbackCandidates.find(
1096 (pr) => pr != null && pullRequestMatchesSearchQuery({ linkedPullRequest: pr }, query),
1097 );
1098 const legacyStatus = useLinkedThreadPullRequest(
1099 thread.environmentId,
1100 legacyReference,
1101 enabled,
1102 undefined,
1103 legacyReference,
1104 );
1105 const reference = matchedLink ?? legacyReference;
1106 const linked = matchedLink ? linkedPullRequestSnapshotStatus(matchedLink) : legacyStatus;
1107 const status = prStatusIndicator(linked?.pr ?? null, linked?.sourceControlProvider);
1108 return reference ? (
1109 <ThreadPullRequestNumber
1110 number={reference.number}
1111 className={
1112 settled
1113 ? cn(
1114 "text-secondary-label transition-colors",
1115 linked?.pr && settledPrHoverColorClass(linked.pr.state, linked.pr.isDraft),
1117 : (status?.colorClass ?? "text-secondary-label")
1119 aria-label={status?.tooltip ?? `Pull request #${reference.number}`}
1120 />
1121 ) : null;