import { scopeProjectRef, scopedThreadKey, scopeThreadRef, } from "@t3tools/client-runtime/environment"; import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests"; import { pullRequestDetailToVcsStatus } from "@t3tools/client-runtime/state/pull-requests"; import { resolveEnvironmentMachineKind, type EnvironmentId, type ThreadLinkedPullRequest, type ThreadPullRequestLink, type VcsStatusResult, } from "@t3tools/contracts"; import { Atom } from "effect/unstable/reactivity"; import { FolderGit2Icon, TerminalIcon } from "lucide-react"; import { useCallback, useMemo } from "react"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments"; import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon"; import { useProject } from "../state/entities"; import { resolveThreadCurrentPullRequestLink, resolveThreadPullRequestChains, visibleThreadPullRequests, type ThreadPullRequestBadge, } from "@t3tools/shared/threadPullRequests"; import { useRender } from "@base-ui/react/use-render"; import { type ReactNode, type AnimationEvent, type MouseEvent, type ReactElement } from "react"; import { cn } from "../lib/utils"; import { parseChangeRequestUrl } from "../lib/openPullRequestLink"; import { useEnvironmentQuery } from "../state/query"; import { linkedPullRequestDetailAtom, useSharedPullRequestSummary } from "../state/pullRequests"; import { useThreadRunningTerminalIds } from "../state/terminalSessions"; import { vcsEnvironment } from "../state/vcs"; import { useUiStateStore } from "../uiStateStore"; import { resolveChangeRequestPresentation } from "../sourceControlPresentation"; import { resolveThreadLastVisitedAt, resolveThreadStatusPill, type ThreadStatusPill, useRetainedValue, useSidebarRowSubscriptionLease, } from "./Sidebar.logic"; import type { SidebarThreadSummary } from "../types"; import { formatWorktreePathForDisplay } from "../worktreeCleanup"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { pullRequestListLines } from "./pullRequest/pullRequestListLines"; import { PULL_REQUEST_STATE_PRESENTATION, PullRequestGlyph, type PullRequestGlyphIcon, } from "./pullRequest/pullRequestIcons"; import { resolvePullRequestState } from "./pullRequest/pullRequestPresentation"; export interface PrStatusIndicator { label: string; colorClass: string; Icon: PullRequestGlyphIcon; tooltip: string; tooltipLead: string; tooltipTitle: string; url: string; } export interface TerminalStatusIndicator { label: "Terminal process running"; colorClass: string; pulse: boolean; } export type ThreadPr = VcsStatusResult["pr"]; export interface LinkedThreadPullRequestStatus { readonly pr: NonNullable; readonly sourceControlProvider: NonNullable; } /** Linked badges use persisted snapshots; only branch and legacy fallbacks lease summary reads. */ export function useLinkedThreadPullRequest( environmentId: EnvironmentId | null, linkedPullRequest: ThreadLinkedPullRequest | null | undefined, enabled = true, pullRequests?: ReadonlyArray, branchPullRequest?: ThreadLinkedPullRequest | null, ): LinkedThreadPullRequestStatus | null { const supportsLinks = useSupportsMultiplePullRequests(environmentId); const current = useMemo( () => (supportsLinks ? resolveThreadCurrentPullRequestLink(pullRequests ?? []) : null), [pullRequests, supportsLinks], ); const fallback = current === null ? ((!supportsLinks ? linkedPullRequest : null) ?? branchPullRequest) : null; // Stable per link: the shared summary effect keys on this object, and a sidebar row must not // touch the cache on every render. const reference = useMemo(() => { if (fallback == null) return null; const host = parseChangeRequestUrl(fallback.url)?.host; return { ...fallback, ...(host === undefined ? {} : { host }) }; }, [fallback]); const queried = useEnvironmentQuery( !enabled || environmentId === null || reference === null ? null : linkedPullRequestDetailAtom({ environmentId, input: reference }), ); const detail = useSharedPullRequestSummary( environmentId, reference, queried.data, queried.dataUpdatedAt, ); return useMemo(() => { if (current !== null) return linkedPullRequestSnapshotStatus(current); return detail === null ? null : { pr: pullRequestDetailToVcsStatus(detail), sourceControlProvider: { kind: detail.provider, name: detail.provider, baseUrl: "" }, }; }, [current, detail]); } export function linkedPullRequestSnapshotStatus( link: ThreadPullRequestLink, ): LinkedThreadPullRequestStatus | null { const snapshot = link.snapshot; if (snapshot === null) return null; const kind = link.url.includes("/-/merge_requests/") ? "gitlab" : link.url.includes("/pullrequest/") ? "azure-devops" : link.url.includes("/pull-requests/") ? "bitbucket" : link.url.includes("/pulls/") ? "forgejo" : "github"; return { pr: { number: link.number, url: link.url, title: snapshot.title, state: snapshot.state, isDraft: snapshot.isDraft, headRef: snapshot.headBranch, baseRef: snapshot.baseBranch, ...(snapshot.updatedAt === null ? {} : { updatedAt: snapshot.updatedAt }), }, sourceControlProvider: { kind, name: kind, baseUrl: "" }, }; } export { resolveThreadPullRequestBadge, type ThreadPullRequestBadge, } from "@t3tools/shared/threadPullRequests"; export interface ThreadPullRequestBadgePresentation { readonly Icon: PullRequestGlyphIcon; readonly toneClassName: string; readonly label: string; readonly text: string | number; } /** Resolve the complete badge appearance before rendering it in the sidebar or composer. */ export function resolveThreadPullRequestBadgePresentation({ badge, number, url, status, }: { readonly badge: ThreadPullRequestBadge | null; readonly number?: number | undefined; readonly url?: string | undefined; readonly status: PrStatusIndicator | null; }): ThreadPullRequestBadgePresentation | null { // The badge already folds every visible link into one state, draft included, so both the // stack and the linked count index the shared table directly rather than the single-PR resolver. if (badge?.kind === "stack") { const aggregate = PULL_REQUEST_STATE_PRESENTATION[badge.state]; return { Icon: PullRequestGlyph.stack, toneClassName: aggregate.toneClassName, label: `Stack of ${badge.layers} pull requests, ${aggregate.label.toLowerCase()}`, text: badge.layers, }; } if (number === undefined || url === undefined) return null; const tooltip = status?.tooltip ?? `PR #${number}, status pending`; if (badge?.kind === "pull-request" && badge.others > 0) { // Unrelated links fold into one state, so a count of merged PRs reads as merged. const aggregate = PULL_REQUEST_STATE_PRESENTATION[badge.state]; return { Icon: aggregate.Icon, toneClassName: aggregate.toneClassName, label: `${tooltip}, and ${badge.others} more linked; overall ${aggregate.label.toLowerCase()}`, text: `+${badge.others + 1}`, }; } return { Icon: status?.Icon ?? PullRequestGlyph.pullRequest, toneClassName: status?.colorClass ?? "text-muted-foreground", label: tooltip, text: number, }; } /** * The linked-PR badge shared by the sidebar and composer footer. The badge owns what it shows: * the state glyph and number at the meta size, in the state's color. The caller owns the control * it sits in through `render` (an inline link in a sidebar row, a toolbar control in the * composer), and the badge fills in the behavior: a single PR is a link to it, while a stack or * several linked PRs is a button that opens the thread's pull requests tab. */ export function ThreadPullRequestBadgeControl({ render, badge, pullRequests, number, url, status, onOpenList, onOpenPullRequest, }: { render: ReactElement<{ render?: useRender.RenderProp }>; badge: ThreadPullRequestBadge | null; pullRequests: ReadonlyArray; number?: number | undefined; url?: string | undefined; status: PrStatusIndicator | null; onOpenList: () => void; onOpenPullRequest: (event: MouseEvent, url?: string) => void; }) { const presentation = resolveThreadPullRequestBadgePresentation({ badge, number, url, status }); if (presentation === null) return null; return ( 0)} url={url} number={number} status={status} pullRequests={pullRequests} onOpenList={onOpenList} onOpenPullRequest={onOpenPullRequest} /> ); } function PullRequestBadge({ render, presentation, opensList, url, number, status, pullRequests, onOpenList, onOpenPullRequest, }: { render: ReactElement<{ render?: useRender.RenderProp }>; presentation: NonNullable>; opensList: boolean; url: string | undefined; number: number | undefined; status: PrStatusIndicator | null; pullRequests: ReadonlyArray; onOpenList: () => void; onOpenPullRequest: (event: MouseEvent, url?: string) => void; }) { const onClick = opensList ? (event: MouseEvent) => { event.preventDefault(); event.stopPropagation(); onOpenList(); } : onOpenPullRequest; const element = opensList ? (