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/shared/threadPullRequests";
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 { parseChangeRequestUrl } from "../lib/openPullRequestLink";
37import { useEnvironmentQuery } from "../state/query";
38import { linkedPullRequestDetailAtom, useSharedPullRequestSummary } from "../state/pullRequests";
39import { useThreadRunningTerminalIds } from "../state/terminalSessions";
40import { vcsEnvironment } from "../state/vcs";
41import { useUiStateStore } from "../uiStateStore";
42import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
43import {
44 pullRequestMatchesSearchQuery,
45 resolveThreadLastVisitedAt,
46 resolveThreadStatusPill,
47 type ThreadStatusPill,
48 useRetainedValue,
49 useSidebarRowSubscriptionLease,
50} from "./Sidebar.logic";
51
52import type { SidebarThreadSummary } from "../types";
53import { formatWorktreePathForDisplay } from "../worktreeCleanup";
54import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
55import {
56 PULL_REQUEST_STATE_PRESENTATION,
57 PullRequestGlyph,
58 type PullRequestGlyphIcon,
59} from "./pullRequest/pullRequestIcons";
60import { resolvePullRequestState } from "./pullRequest/pullRequestPresentation";
61
62export interface PrStatusIndicator {
63 label: string;
64 colorClass: string;
65 Icon: PullRequestGlyphIcon;
66 tooltip: string;
67 tooltipLead: string;
68 tooltipTitle: string;
69 url: string;
70}
71
72export interface TerminalStatusIndicator {
73 label: "Terminal process running";
74 colorClass: string;
75 pulse: boolean;
76}
77
78export type ThreadPr = VcsStatusResult["pr"];
79
80export interface LinkedThreadPullRequestStatus {
81 readonly pr: NonNullable<ThreadPr>;
82 readonly sourceControlProvider: NonNullable<VcsStatusResult["sourceControlProvider"]>;
83}
84
85export function useLinkedThreadPullRequest(
86 environmentId: EnvironmentId | null,
87 linkedPullRequest: ThreadLinkedPullRequest | null | undefined,
88 enabled = true,
89 pullRequests?: ReadonlyArray<ThreadPullRequestLink>,
90 branchPullRequest?: ThreadLinkedPullRequest | null,
91): LinkedThreadPullRequestStatus | null {
92 const supportsLinks = useSupportsMultiplePullRequests(environmentId);
93 const current = supportsLinks ? resolveThreadCurrentPullRequestLink(pullRequests ?? []) : null;
94 // Callers key on the returned status, so it stays cached across the query hooks.
95 const currentStatus = current === null ? null : linkedPullRequestSnapshotStatus(current);
96 const fallback =
97 current === null ? ((!supportsLinks ? linkedPullRequest : null) ?? branchPullRequest) : null;
98 // The query atom and shared summary effect key on this object, and a sidebar row
99 // must not touch the summary cache on every render.
100 const reference = fallback == null ? null : linkedPullRequestReference(fallback);
101 const queried = useEnvironmentQuery(
102 !enabled || environmentId === null || reference === null
103 ? null
104 : linkedPullRequestDetailAtom({ environmentId, input: reference }),
105 );
106 const detail = useSharedPullRequestSummary(
107 environmentId,
108 reference,
109 queried.data,
110 queried.dataUpdatedAt,
111 );
112
113 if (current !== null) return currentStatus;
114 return detail === null
115 ? null
116 : {
117 pr: pullRequestDetailToVcsStatus(detail),
118 sourceControlProvider: { kind: detail.provider, name: detail.provider, baseUrl: "" },
119 };
120}
121
122function linkedPullRequestReference(fallback: ThreadLinkedPullRequest) {
123 const host = parseChangeRequestUrl(fallback.url)?.host;
124 return { ...fallback, ...(host === undefined ? {} : { host }) };
125}
126
127export function linkedPullRequestSnapshotStatus(
128 link: ThreadPullRequestLink,
129): LinkedThreadPullRequestStatus | null {
130 const snapshot = link.snapshot;
131 if (snapshot === null) return null;
132 const kind = (
133 sourceControlClients.findByChangeRequestUrl(link.url) ?? sourceControlClients.get(undefined)
134 ).kind;
135 return {
136 pr: {
137 number: link.number,
138 url: link.url,
139 title: snapshot.title,
140 state: snapshot.state,
141 isDraft: snapshot.isDraft,
142 headRef: snapshot.headBranch,
143 baseRef: snapshot.baseBranch,
144 ...(snapshot.updatedAt === null ? {} : { updatedAt: snapshot.updatedAt }),
145 },
146 sourceControlProvider: { kind, name: kind, baseUrl: "" },
147 };
148}
149
150export {
151 resolveThreadPullRequestBadge,
152 type ThreadPullRequestBadge,
153} from "@t3tools/shared/threadPullRequests";
154
155export interface ThreadPullRequestBadgePresentation {
156 readonly Icon: PullRequestGlyphIcon;
157 readonly toneClassName: string;
158 readonly label: string;
159 readonly text: string | number;
160}
161
162function resolveThreadPullRequestBadgePresentation({
163 badge,
164 number,
165 url,
166 status,
167}: {
168 readonly badge: ThreadPullRequestBadge | null;
169 readonly number?: number | undefined;
170 readonly url?: string | undefined;
171 readonly status: PrStatusIndicator | null;
172}): ThreadPullRequestBadgePresentation | null {
173 if (badge?.kind === "stack") {
174 const aggregate = PULL_REQUEST_STATE_PRESENTATION[badge.state];
175 return {
176 Icon: PullRequestGlyph.stack,
177 toneClassName: aggregate.toneClassName,
178 label: `Stack of ${badge.layers} pull requests, ${aggregate.label.toLowerCase()}`,
179 text: badge.layers,
180 };
181 }
182 if (number === undefined || url === undefined) return null;
183
184 const tooltip = status?.tooltip ?? `PR #${number}, status pending`;
185 if (badge?.kind === "pull-request" && badge.others > 0) {
186 const aggregate = PULL_REQUEST_STATE_PRESENTATION[badge.state];
187 return {
188 Icon: aggregate.Icon,
189 toneClassName: aggregate.toneClassName,
190 label: `${tooltip}, and ${badge.others} more linked; overall ${aggregate.label.toLowerCase()}`,
191 text: `+${badge.others + 1}`,
192 };
193 }
194 return {
195 Icon: status?.Icon ?? PullRequestGlyph.pullRequest,
196 toneClassName: status?.colorClass ?? "text-muted-foreground",
197 label: tooltip,
198 text: number,
199 };
200}
201
202export function ThreadPullRequestBadgeControl({
203 render,
204 badge,
205 pullRequests,
206 number,
207 url,
208 status,
209 onOpenList,
210 onOpenPullRequest,
211}: {
212 render: ReactElement<{ render?: useRender.RenderProp }>;
213 badge: ThreadPullRequestBadge | null;
214 pullRequests: ReadonlyArray<ThreadPullRequestLink>;
215 number?: number | undefined;
216 url?: string | undefined;
217 status: PrStatusIndicator | null;
218 onOpenList: () => void;
219 onOpenPullRequest: (event: MouseEvent<HTMLElement>, url?: string) => void;
220}) {
221 const presentation = resolveThreadPullRequestBadgePresentation({ badge, number, url, status });
222 if (presentation === null) return null;
223 return (
224 <PullRequestBadge
225 render={render}
226 presentation={presentation}
227 opensList={badge !== null && (badge.kind === "stack" || badge.others > 0)}
228 url={url}
229 number={number}
230 status={status}
231 pullRequests={pullRequests}
232 onOpenList={onOpenList}
233 onOpenPullRequest={onOpenPullRequest}
234 />
235 );
236}
237
238function PullRequestBadge({
239 render,
240 presentation,
241 opensList,
242 url,
243 number,
244 status,
245 pullRequests,
246 onOpenList,
247 onOpenPullRequest,
248}: {
249 render: ReactElement<{ render?: useRender.RenderProp }>;
250 presentation: NonNullable<ReturnType<typeof resolveThreadPullRequestBadgePresentation>>;
251 opensList: boolean;
252 url: string | undefined;
253 number: number | undefined;
254 status: PrStatusIndicator | null;
255 pullRequests: ReadonlyArray<ThreadPullRequestLink>;
256 onOpenList: () => void;
257 onOpenPullRequest: (event: MouseEvent<HTMLElement>, url?: string) => void;
258}) {
259 const onClick = opensList
260 ? (event: MouseEvent<HTMLElement>) => {
261 event.preventDefault();
262 event.stopPropagation();
263 onOpenList();
264 }
265 : onOpenPullRequest;
266 const element = opensList ? (
267 <button type="button" />
268 ) : (
269 <a href={url} target="_blank" rel="noopener noreferrer" />
270 );
271 const control = useRender({
272 render,
273 props: {
274 render: element,
275 "aria-label": presentation.label,
276 onPointerDown: (event: MouseEvent<HTMLElement>) => event.stopPropagation(),
277 onClick,
278 },
279 });
280 return (
281 <Tooltip key={opensList ? "list" : "link"}>
282 <TooltipTrigger render={control}>
283 <span
284 className={cn("contents font-normal text-xs tabular-nums", presentation.toneClassName)}
285 >
286 <presentation.Icon aria-hidden className="size-3 shrink-0" />
287 <span>{presentation.text}</span>
288 </span>
289 </TooltipTrigger>
290 <TooltipPopup
291 side="top"
292 sideOffset={0}
293 variant="glass"
294 className="pointer-events-auto w-80 max-w-[calc(100vw-2rem)] text-left whitespace-normal"
295 >
296 <div className="-mx-1 max-h-[calc(var(--available-height)-0.5rem-2px)] overflow-y-auto overscroll-contain">
297 {visibleThreadPullRequests(pullRequests).length > 0 ? (
298 <ThreadPullRequestsMiniList
299 pullRequests={pullRequests}
300 onOpenPullRequest={onOpenPullRequest}
301 />
302 ) : number !== undefined && url !== undefined ? (
303 <ul className="flex flex-col gap-1">
304 <ThreadPullRequestMiniListItem
305 number={number}
306 url={url}
307 title={status?.tooltipTitle ?? presentation.label}
308 presentation={presentation}
309 onOpenPullRequest={onOpenPullRequest}
310 />
311 </ul>
312 ) : null}
313 </div>
314 </TooltipPopup>
315 </Tooltip>
316 );
317}
318
319export function ThreadPullRequestsMiniList({
320 pullRequests,
321 onOpenPullRequest,
322}: {
323 pullRequests: ReadonlyArray<ThreadPullRequestLink>;
324 onOpenPullRequest?: (event: MouseEvent<HTMLAnchorElement>, url: string) => void;
325}) {
326 const lines = pullRequestListLines(
327 resolveThreadPullRequestChains(visibleThreadPullRequests(pullRequests)),
328 );
329 if (lines.length === 0) return null;
330 return (
331 <ul className="flex flex-col gap-1">
332 {lines.map((line) => {
333 const snapshot = line.link.snapshot;
334 const presentation =
335 snapshot === null
336 ? null
337 : resolvePullRequestState({ state: snapshot.state, isDraft: snapshot.isDraft });
338 return (
339 <ThreadPullRequestMiniListItem
340 key={`${line.link.host}/${line.link.repository}#${line.link.number}`}
341 number={line.link.number}
342 url={line.link.url}
343 title={snapshot?.title ?? line.link.repository}
344 presentation={presentation}
345 depth={line.depth}
346 onOpenPullRequest={onOpenPullRequest}
347 >
348 {line.stack ? (
349 <span className="ml-auto shrink-0 pl-1 text-3xs">
350 {line.stack.kind === "native" ? "stack" : "chain"} · {line.stack.size}
351 </span>
352 ) : null}
353 </ThreadPullRequestMiniListItem>
354 );
355 })}
356 </ul>
357 );
358}
359
360function ThreadPullRequestMiniListItem({
361 number,
362 url,
363 title,
364 presentation,
365 depth = 0,
366 onOpenPullRequest,
367 children,
368}: {
369 number: number;
370 url: string;
371 title: string;
372 presentation: Pick<ThreadPullRequestBadgePresentation, "Icon" | "toneClassName"> | null;
373 depth?: number;
374 onOpenPullRequest?: ((event: MouseEvent<HTMLAnchorElement>, url: string) => void) | undefined;
375 children?: ReactNode;
376}) {
377 const Icon = presentation?.Icon ?? PullRequestGlyph.pullRequest;
378 const content = (
379 <>
380 <Icon
381 aria-hidden
382 className={cn("size-3 shrink-0", presentation?.toneClassName ?? "stroke-muted-foreground")}
383 />
384 <span className="shrink-0 font-mono tabular-nums">#{number}</span>
385 <span className="min-w-0 truncate text-foreground/75">{title}</span>
386 {children}
387 </>
388 );
389 return (
390 <li style={{ paddingLeft: `${Math.min(depth, 3) * 0.75}rem` }}>
391 {onOpenPullRequest ? (
392 <a
393 href={url}
394 target="_blank"
395 rel="noopener noreferrer"
396 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"
397 onPointerDown={(event) => event.stopPropagation()}
398 onClick={(event) => onOpenPullRequest(event, url)}
399 >
400 {content}
401 </a>
402 ) : (
403 <div className="flex min-w-0 items-center gap-2">{content}</div>
404 )}
405 </li>
406 );
407}
408
409export function prStatusIndicator(
410 pr: ThreadPr,
411 provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
412): PrStatusIndicator | null {
413 if (!pr) return null;
414 const { shortLabel } = sourceControlClients.get(provider?.kind).changeRequest;
415 const state = resolvePullRequestState({ state: pr.state, isDraft: pr.isDraft === true });
416
417 const tooltipLead = `${shortLabel} #${pr.number} - ${state.label}`;
418 return {
419 label: `${shortLabel} ${state.label.toLowerCase()}`,
420 colorClass: state.toneClassName,
421 Icon: state.Icon,
422 tooltip: `${tooltipLead}: ${pr.title}`,
423 tooltipLead,
424 tooltipTitle: pr.title,
425 url: pr.url,
426 };
427}
428
429export function ChangeRequestStatusIcon({
430 state,
431 isDraft = false,
432 className,
433}: Pick<NonNullable<ThreadPr>, "state"> & {
434 readonly isDraft?: boolean | undefined;
435 readonly className?: string | undefined;
436}) {
437 const presentation = resolvePullRequestState({ state, isDraft });
438 return <presentation.Icon className={className} />;
439}
440
441export function PrStatusTooltipContent({ status }: { status: PrStatusIndicator }) {
442 return (
443 <span className="flex max-w-[min(34rem,calc(100vw-2rem))] items-stretch overflow-hidden whitespace-nowrap">
444 <span className="shrink-0 pr-2 font-medium">{status.tooltipLead}</span>
445 <span className="min-h-4 shrink-0 border-border/70 border-l" aria-hidden="true" />
446 <span className="min-w-0 truncate pl-2">{status.tooltipTitle}</span>
447 </span>
448 );
449}
450
451export function resolveThreadPr(input: {
452 threadBranch: string | null;
453 gitStatus: VcsStatusResult | null;
454}): ThreadPr | null {
455 const { threadBranch, gitStatus } = input;
456 if (gitStatus === null) {
457 return null;
458 }
459
460 if (threadBranch === null || gitStatus.refName !== threadBranch) {
461 return null;
462 }
463
464 return gitStatus.pr ?? null;
465}
466
467/**
468 * Parent-held PR snapshot for Sidebar V2. Rows remount when settlement
469 * partitions move them, so terminal PR metadata must live above the row.
470 */
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 text-muted-foreground/40" />
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={`PR #${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}