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