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

ThreadStatusIndicators.tsx

1,095 lines33.9 KB

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