diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index c497415a0c..65db68e7f8 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -69,7 +69,7 @@ import { threadJumpIndexFromCommand, threadTraversalDirectionFromCommand, } from "../keybindings"; -import { useGitStatuses } from "../lib/gitStatusState"; +import { useGitStatus } from "../lib/gitStatusState"; import { readNativeApi } from "../nativeApi"; import { useComposerDraftStore } from "../composerDraftStore"; import { useHandleNewThread } from "../hooks/useHandleNewThread"; @@ -244,8 +244,20 @@ function prStatusIndicator(pr: ThreadPr): PrStatusIndicator | null { return null; } +function resolveThreadPr( + threadBranch: string | null, + gitStatus: GitStatusResult | null, +): ThreadPr | null { + if (threadBranch === null || gitStatus === null || gitStatus.branch !== threadBranch) { + return null; + } + + return gitStatus.pr ?? null; +} + interface SidebarThreadRowProps { threadId: ThreadId; + projectCwd: string | null; orderedProjectThreadIds: readonly ThreadId[]; routeThreadId: ThreadId | null; selectedThreadIds: ReadonlySet; @@ -276,7 +288,6 @@ interface SidebarThreadRowProps { cancelRename: () => void; attemptArchiveThread: (threadId: ThreadId) => Promise; openPrLink: (event: MouseEvent, prUrl: string) => void; - pr: ThreadPr | null; } function SidebarThreadRow(props: SidebarThreadRowProps) { @@ -291,6 +302,8 @@ function SidebarThreadRow(props: SidebarThreadRowProps) { return null; } + const gitCwd = thread.worktreePath ?? props.projectCwd; + const gitStatus = useGitStatus(thread.branch !== null ? gitCwd : null); const isActive = props.routeThreadId === thread.id; const isSelected = props.selectedThreadIds.has(thread.id); const isHighlighted = isActive || isSelected; @@ -302,7 +315,8 @@ function SidebarThreadRow(props: SidebarThreadRowProps) { lastVisitedAt, }, }); - const prStatus = prStatusIndicator(props.pr); + const pr = resolveThreadPr(thread.branch, gitStatus.data); + const prStatus = prStatusIndicator(pr); const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds); const isConfirmingArchive = props.confirmingArchiveThreadId === thread.id && !isThreadRunning; const threadMetaClassName = isConfirmingArchive @@ -761,38 +775,6 @@ export default function Sidebar() { }), [platform, routeTerminalOpen], ); - const threadGitTargets = useMemo( - () => - sidebarThreads.map((thread) => ({ - threadId: thread.id, - branch: thread.branch, - cwd: thread.worktreePath ?? projectCwdById.get(thread.projectId) ?? null, - })), - [projectCwdById, sidebarThreads], - ); - const threadGitStatusCwds = useMemo( - () => [ - ...new Set( - threadGitTargets - .filter((target) => target.branch !== null) - .map((target) => target.cwd) - .filter((cwd): cwd is string => cwd !== null), - ), - ], - [threadGitTargets], - ); - const threadGitStatuses = useGitStatuses(threadGitStatusCwds); - const prByThreadId = useMemo(() => { - const map = new Map(); - for (const target of threadGitTargets) { - const status = target.cwd ? threadGitStatuses.get(target.cwd) : undefined; - const branchMatches = - target.branch !== null && status?.branch !== null && status?.branch === target.branch; - map.set(target.threadId, branchMatches ? (status?.pr ?? null) : null); - } - return map; - }, [threadGitStatuses, threadGitTargets]); - const openPrLink = useCallback((event: MouseEvent, prUrl: string) => { event.preventDefault(); event.stopPropagation(); @@ -1701,6 +1683,7 @@ export default function Sidebar() { ))} diff --git a/apps/web/src/lib/gitStatusState.test.ts b/apps/web/src/lib/gitStatusState.test.ts index 39a9f9574e..eaab931c30 100644 --- a/apps/web/src/lib/gitStatusState.test.ts +++ b/apps/web/src/lib/gitStatusState.test.ts @@ -3,11 +3,9 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { getGitStatusSnapshot, - getGitStatusSubscriptionKey, - pruneStatusByCwd, refreshGitStatus, resetGitStatusStateForTests, - retainGitStatusSync, + watchGitStatus, } from "./gitStatusState"; function registerListener(listeners: Set<(event: T) => void>, listener: (event: T) => void) { @@ -51,9 +49,9 @@ afterEach(() => { }); describe("gitStatusState", () => { - it("shares one live status subscription per cwd and updates the cached snapshot", () => { - const releaseA = retainGitStatusSync("/repo", gitClient); - const releaseB = retainGitStatusSync("/repo", gitClient); + it("shares one live subscription per cwd and updates the per-cwd atom snapshot", () => { + const releaseA = watchGitStatus("/repo", gitClient); + const releaseB = watchGitStatus("/repo", gitClient); expect(gitClient.onStatus).toHaveBeenCalledOnce(); expect(getGitStatusSnapshot("/repo")).toEqual({ @@ -80,7 +78,7 @@ describe("gitStatusState", () => { }); it("restarts the live stream when explicitly refreshed", () => { - const release = retainGitStatusSync("/repo", gitClient); + const release = watchGitStatus("/repo", gitClient); emitGitStatus(BASE_STATUS); refreshGitStatus("/repo"); @@ -95,21 +93,4 @@ describe("gitStatusState", () => { release(); }); - - it("prunes stale cwd entries when the tracked cwd list shrinks", () => { - const current = new Map([ - ["/repo/a", BASE_STATUS], - ["/repo/b", { ...BASE_STATUS, branch: "feature/other" }], - ]); - - expect(pruneStatusByCwd(current, ["/repo/b"])).toEqual( - new Map([["/repo/b", { ...BASE_STATUS, branch: "feature/other" }]]), - ); - }); - - it("keeps the same subscription key when the tracked cwd set is unchanged", () => { - expect(getGitStatusSubscriptionKey(["/repo/b", "/repo/a", "/repo/a"])).toBe( - getGitStatusSubscriptionKey(["/repo/a", "/repo/b"]), - ); - }); }); diff --git a/apps/web/src/lib/gitStatusState.ts b/apps/web/src/lib/gitStatusState.ts index 7ef013f538..b468686f00 100644 --- a/apps/web/src/lib/gitStatusState.ts +++ b/apps/web/src/lib/gitStatusState.ts @@ -2,7 +2,7 @@ import { useAtomValue } from "@effect/atom-react"; import { type GitManagerServiceError, type GitStatusResult } from "@t3tools/contracts"; import { Cause } from "effect"; import { Atom } from "effect/unstable/reactivity"; -import { useEffect, useMemo, useState } from "react"; +import { useEffect } from "react"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { getWsRpcClient, type WsRpcClient } from "../wsRpcClient"; @@ -18,10 +18,8 @@ export interface GitStatusState { type GitStatusClient = Pick; -interface GitStatusEntry { - readonly atom: typeof EMPTY_GIT_STATUS_STATE_ATOM; - client: GitStatusClient | null; - retainCount: number; +interface WatchedGitStatus { + refCount: number; unsubscribe: () => void; } @@ -32,40 +30,130 @@ const EMPTY_GIT_STATUS_STATE = Object.freeze({ isPending: false, }); -const EMPTY_GIT_STATUS_STATE_ATOM = makeStateAtom("git-status-empty", EMPTY_GIT_STATUS_STATE); const NOOP: () => void = () => undefined; -const gitStatusEntries = new Map(); +const watchedGitStatuses = new Map(); +const knownGitStatusCwds = new Set(); -function makeStateAtom(label: string, initialValue: A) { - return Atom.make(initialValue).pipe(Atom.keepAlive, Atom.withLabel(label)); -} +let sharedGitStatusClient: GitStatusClient | null = null; -function getGitStatusEntry(cwd: string): GitStatusEntry { - const existing = gitStatusEntries.get(cwd); - if (existing) { - return existing; +const gitStatusStateAtom = Atom.family((cwd: string) => { + knownGitStatusCwds.add(cwd); + return Atom.make(EMPTY_GIT_STATUS_STATE).pipe( + Atom.keepAlive, + Atom.withLabel(`git-status:${cwd}`), + ); +}); + +export function getGitStatusSnapshot(cwd: string | null): GitStatusState { + if (cwd === null) { + return EMPTY_GIT_STATUS_STATE; } - const entry: GitStatusEntry = { - atom: makeStateAtom(`git-status:${cwd}`, EMPTY_GIT_STATUS_STATE), - client: null, - retainCount: 0, - unsubscribe: NOOP, - }; - gitStatusEntries.set(cwd, entry); - return entry; + return appAtomRegistry.get(gitStatusStateAtom(cwd)); } -function connectGitStatusEntry(cwd: string, entry: GitStatusEntry): void { - if (!entry.client) { +export function watchGitStatus( + cwd: string | null, + client: GitStatusClient = getWsRpcClient().git, +): () => void { + if (cwd === null) { + return NOOP; + } + + ensureGitStatusClient(client); + + const watched = watchedGitStatuses.get(cwd); + if (watched) { + watched.refCount += 1; + return () => unwatchGitStatus(cwd); + } + + watchedGitStatuses.set(cwd, { + refCount: 1, + unsubscribe: subscribeToGitStatus(cwd), + }); + + return () => unwatchGitStatus(cwd); +} + +export function refreshGitStatus(cwd: string | null): void { + if (cwd === null) { return; } - markGitStatusPending(entry.atom); - entry.unsubscribe = entry.client.onStatus( + const watched = watchedGitStatuses.get(cwd); + if (!watched) { + return; + } + + watched.unsubscribe(); + watched.unsubscribe = subscribeToGitStatus(cwd); +} + +export function resetGitStatusStateForTests(): void { + for (const watched of watchedGitStatuses.values()) { + watched.unsubscribe(); + } + watchedGitStatuses.clear(); + sharedGitStatusClient = null; + + for (const cwd of knownGitStatusCwds) { + appAtomRegistry.set(gitStatusStateAtom(cwd), EMPTY_GIT_STATUS_STATE); + } + knownGitStatusCwds.clear(); +} + +export function useGitStatus(cwd: string | null): GitStatusState { + useEffect(() => watchGitStatus(cwd), [cwd]); + + return cwd === null ? EMPTY_GIT_STATUS_STATE : useAtomValue(gitStatusStateAtom(cwd)); +} + +function ensureGitStatusClient(client: GitStatusClient): void { + if (sharedGitStatusClient === client) { + return; + } + + if (sharedGitStatusClient !== null) { + resetLiveGitStatusSubscriptions(); + } + + sharedGitStatusClient = client; +} + +function resetLiveGitStatusSubscriptions(): void { + for (const watched of watchedGitStatuses.values()) { + watched.unsubscribe(); + } + watchedGitStatuses.clear(); +} + +function unwatchGitStatus(cwd: string): void { + const watched = watchedGitStatuses.get(cwd); + if (!watched) { + return; + } + + watched.refCount -= 1; + if (watched.refCount > 0) { + return; + } + + watched.unsubscribe(); + watchedGitStatuses.delete(cwd); +} + +function subscribeToGitStatus(cwd: string): () => void { + const client = sharedGitStatusClient; + if (!client) { + return NOOP; + } + + markGitStatusPending(cwd); + return client.onStatus( { cwd }, (status) => { - appAtomRegistry.set(entry.atom, { + appAtomRegistry.set(gitStatusStateAtom(cwd), { data: status, error: null, cause: null, @@ -74,20 +162,16 @@ function connectGitStatusEntry(cwd: string, entry: GitStatusEntry): void { }, { onResubscribe: () => { - markGitStatusPending(entry.atom); + markGitStatusPending(cwd); }, }, ); } -function disconnectGitStatusEntry(entry: GitStatusEntry): void { - entry.unsubscribe(); - entry.unsubscribe = NOOP; -} - -function markGitStatusPending(atom: typeof EMPTY_GIT_STATUS_STATE_ATOM): void { +function markGitStatusPending(cwd: string): void { + const atom = gitStatusStateAtom(cwd); const current = appAtomRegistry.get(atom); - const nextState = + const next = current.data === null ? { ...EMPTY_GIT_STATUS_STATE, isPending: true } : { @@ -98,160 +182,13 @@ function markGitStatusPending(atom: typeof EMPTY_GIT_STATUS_STATE_ATOM): void { }; if ( - current.data === nextState.data && - current.error === nextState.error && - current.cause === nextState.cause && - current.isPending === nextState.isPending + current.data === next.data && + current.error === next.error && + current.cause === next.cause && + current.isPending === next.isPending ) { return; } - appAtomRegistry.set(atom, nextState); -} - -export function getGitStatusSnapshot(cwd: string | null): GitStatusState { - if (cwd === null) { - return EMPTY_GIT_STATUS_STATE; - } - - return appAtomRegistry.get(getGitStatusEntry(cwd).atom); -} - -export function retainGitStatusSync( - cwd: string | null, - client: GitStatusClient = getWsRpcClient().git, -): () => void { - if (cwd === null) { - return NOOP; - } - - const entry = getGitStatusEntry(cwd); - entry.client = client; - entry.retainCount += 1; - - if (entry.retainCount === 1) { - connectGitStatusEntry(cwd, entry); - } - - return () => { - if (entry.retainCount === 0) { - return; - } - - entry.retainCount -= 1; - if (entry.retainCount === 0) { - disconnectGitStatusEntry(entry); - } - }; -} - -export function refreshGitStatus(cwd: string | null): void { - if (cwd === null) { - return; - } - - const entry = gitStatusEntries.get(cwd); - if (!entry || entry.retainCount === 0) { - return; - } - - disconnectGitStatusEntry(entry); - connectGitStatusEntry(cwd, entry); -} - -export function resetGitStatusStateForTests(): void { - for (const entry of gitStatusEntries.values()) { - disconnectGitStatusEntry(entry); - } - gitStatusEntries.clear(); -} - -export function useGitStatus(cwd: string | null): GitStatusState { - useEffect(() => retainGitStatusSync(cwd), [cwd]); - - const atom = useMemo( - () => (cwd === null ? EMPTY_GIT_STATUS_STATE_ATOM : getGitStatusEntry(cwd).atom), - [cwd], - ); - - return useAtomValue(atom); -} - -export function useGitStatuses(cwds: ReadonlyArray): ReadonlyMap { - const [statusByCwd, setStatusByCwd] = useState>( - () => new Map(), - ); - const subscriptionKey = getGitStatusSubscriptionKey(cwds); - const trackedCwds = useMemo>( - () => (subscriptionKey.length === 0 ? [] : subscriptionKey.split("\u0000")), - [subscriptionKey], - ); - - useEffect(() => { - const releaseSubscriptions = trackedCwds.map((cwd) => retainGitStatusSync(cwd)); - setStatusByCwd((current) => pruneStatusByCwd(current, trackedCwds)); - - const cleanups = trackedCwds.map((cwd) => - appAtomRegistry.subscribe( - getGitStatusEntry(cwd).atom, - (state) => { - setStatusByCwd((current) => { - const next = new Map(current); - if (state.data) { - next.set(cwd, state.data); - } else { - next.delete(cwd); - } - return next; - }); - }, - { immediate: true }, - ), - ); - - return () => { - for (const cleanup of cleanups) { - cleanup(); - } - for (const release of releaseSubscriptions) { - release(); - } - }; - }, [trackedCwds]); - - return statusByCwd; -} - -export function getGitStatusSubscriptionKey(cwds: ReadonlyArray): string { - return normalizeTrackedGitStatusCwds(cwds).join("\u0000"); -} - -function normalizeTrackedGitStatusCwds(cwds: ReadonlyArray): ReadonlyArray { - return [...new Set(cwds)].toSorted(); -} - -export function pruneStatusByCwd( - current: ReadonlyMap, - cwds: ReadonlyArray, -): ReadonlyMap { - const cwdSet = new Set(cwds); - let shouldPrune = false; - for (const key of current.keys()) { - if (!cwdSet.has(key)) { - shouldPrune = true; - break; - } - } - - if (!shouldPrune) { - return current; - } - - const next = new Map(); - for (const [key, value] of current) { - if (cwdSet.has(key)) { - next.set(key, value); - } - } - return next; + appAtomRegistry.set(atom, next); }