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