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