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