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