TypeScript
perf(clients): lease sidebar status by visibility (#9052)
Wout Stiensfc53b273039c
diff --git a/apps/mobile/src/state/use-thread-pr.ts b/apps/mobile/src/state/use-thread-pr.tsindex 0c10d7b3fa4..869d37e587c 100644--- a/apps/mobile/src/state/use-thread-pr.ts+++ b/apps/mobile/src/state/use-thread-pr.ts@@ -1,15 +1,33 @@+import { useAtomValue } from "@effect/atom-react";+import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";import {createLinkedPullRequestDetailAtomFamily,pullRequestDetailToVcsStatus,} from "@t3tools/client-runtime/state/pull-requests";+import { Atom } from "effect/unstable/reactivity";+import { useCallback, useEffect, useMemo } from "react";import { connectionAtomRuntime } from "../connection/runtime";+import { appAtomRegistry } from "./atom-registry";import { useEnvironmentQuery } from "./query";import { presentThreadPr, type ThreadPrPresentation } from "./thread-pr-presentation";import { vcsEnvironment } from "./vcs";const linkedPullRequestDetailAtom = createLinkedPullRequestDetailAtomFamily(connectionAtomRuntime);+const MAX_THREAD_PR_SNAPSHOTS = 500;++interface ThreadPrSnapshot {+ readonly identity: string;+ readonly presentation: ThreadPrPresentation;+}++// One bounded cache survives row virtualization without retaining one live+// atom for every thread, branch, directory, or linked pull request ever seen.+const threadPrSnapshotsAtom = Atom.make<ReadonlyMap<string, ThreadPrSnapshot>>(new Map()).pipe(+ Atom.keepAlive,+ Atom.withLabel("mobile:thread-pr-snapshots"),+);export {presentThreadPr,@@ -28,6 +46,19 @@ export function useThreadPr(projectCwd: string | null,): ThreadPrPresentation | null {const cwd = thread.worktreePath ?? projectCwd;+ const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));+ const snapshotIdentity = JSON.stringify(+ thread.linkedPullRequest ?? { branch: thread.branch, cwd },+ );+ // Select this row's entry so writes for other rows do not re-render it.+ const snapshotEntry = useAtomValue(+ threadPrSnapshotsAtom,+ useCallback(+ (current: ReadonlyMap<string, ThreadPrSnapshot>) => current.get(threadKey),+ [threadKey],+ ),+ );+ const snapshot = snapshotEntry?.identity === snapshotIdentity ? snapshotEntry.presentation : null;const gitStatus = useEnvironmentQuery(thread.linkedPullRequest == null && thread.branch !== null && cwd !== null? vcsEnvironment.status({@@ -49,23 +80,49 @@ export function useThreadPr(}),);- if (thread.linkedPullRequest != null) {- const detail = linkedPullRequest.data;- return detail === null- ? null- : presentThreadPr(pullRequestDetailToVcsStatus(detail), {- kind: detail.provider,- name: detail.provider,- baseUrl: "",- });- }+ const live = useMemo<ThreadPrPresentation | null | undefined>(() => {+ if (thread.linkedPullRequest != null) {+ const detail = linkedPullRequest.data;+ return detail === null+ ? undefined+ : presentThreadPr(pullRequestDetailToVcsStatus(detail), {+ kind: detail.provider,+ name: detail.provider,+ baseUrl: "",+ });+ }++ const status = gitStatus.data;+ if (thread.branch === null) return null;+ if (status === null) return undefined;+ if (status.refName !== thread.branch || !status.pr) return null;+ return presentThreadPr(status.pr, status.sourceControlProvider);+ }, [gitStatus.data, linkedPullRequest.data, thread.branch, thread.linkedPullRequest]);++ useEffect(() => {+ if (live === undefined) return;+ appAtomRegistry.modify(threadPrSnapshotsAtom, (current) => {+ const existing = current.get(threadKey);+ if (live === null) {+ if (existing === undefined) return [false, current];+ const next = new Map(current);+ next.delete(threadKey);+ return [true, next];+ }+ if (existing?.identity === snapshotIdentity && existing.presentation === live) {+ return [false, current];+ }+ const next = new Map(current);+ next.delete(threadKey);+ next.set(threadKey, { identity: snapshotIdentity, presentation: live });+ while (next.size > MAX_THREAD_PR_SNAPSHOTS) {+ const oldestKey = next.keys().next().value;+ if (oldestKey === undefined) break;+ next.delete(oldestKey);+ }+ return [true, next];+ });+ }, [live, snapshotIdentity, threadKey]);- const status = gitStatus.data;- if (status === null || thread.branch === null || status.refName !== thread.branch) {- return null;- }- if (!status.pr) {- return null;- }- return presentThreadPr(status.pr, status.sourceControlProvider);+ return live === undefined ? snapshot : live;}diff --git a/apps/web/src/components/LegacySidebar.tsx b/apps/web/src/components/LegacySidebar.tsxindex 6514f7b4d59..d3a86c118c8 100644--- a/apps/web/src/components/LegacySidebar.tsx+++ b/apps/web/src/components/LegacySidebar.tsx@@ -185,6 +185,8 @@ import {orderItemsByPreferredIds,shouldClearThreadSelectionOnMouseDown,sortProjectsForSidebar,+ useRetainedValue,+ useSidebarRowSubscriptionLease,useThreadJumpHintVisibility,ThreadStatusPill,} from "./Sidebar.logic";@@ -376,6 +378,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr} = props;const threadRef = scopeThreadRef(thread.environmentId, thread.id);const threadKey = scopedThreadKey(threadRef);+ const { leaseLiveStatus, rowRef } = useSidebarRowSubscriptionLease(isActive);const lastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]);const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey));const runningTerminalIds = useThreadRunningTerminalIds({@@ -417,7 +420,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThrconst threadProjectCwd = threadProject?.workspaceRoot ?? null;const gitCwd = thread.worktreePath ?? threadProjectCwd ?? props.projectCwd;const gitStatus = useEnvironmentQuery(- thread.linkedPullRequest == null && thread.branch != null && gitCwd !== null+ leaseLiveStatus && thread.linkedPullRequest == null && thread.branch != null && gitCwd !== null? vcsEnvironment.status({environmentId: thread.environmentId,input: { cwd: gitCwd },@@ -459,16 +462,27 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr},});const linkedPullRequestStatus = useLinkedThreadPullRequest(- thread.environmentId,- thread.linkedPullRequest,+ leaseLiveStatus ? thread.environmentId : null,+ leaseLiveStatus ? thread.linkedPullRequest : null,+ );+ const visibleGitStatus = useRetainedValue(+ JSON.stringify([thread.environmentId, gitCwd]),+ gitStatus.data,+ );+ const visibleLinkedPullRequestStatus = useRetainedValue(+ thread.linkedPullRequest === null+ ? null+ : JSON.stringify([thread.environmentId, thread.linkedPullRequest]),+ linkedPullRequestStatus,);const pr =thread.linkedPullRequest == null- ? resolveThreadPr({ threadBranch: thread.branch, gitStatus: gitStatus.data })- : (linkedPullRequestStatus?.pr ?? null);+ ? resolveThreadPr({ threadBranch: thread.branch, gitStatus: visibleGitStatus })+ : (visibleLinkedPullRequestStatus?.pr ?? null);const prStatus = prStatusIndicator(pr,- linkedPullRequestStatus?.sourceControlProvider ?? gitStatus.data?.sourceControlProvider,+ visibleLinkedPullRequestStatus?.sourceControlProvider ??+ visibleGitStatus?.sourceControlProvider,);const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);const isConfirmingArchive = confirmingArchiveThreadKey === threadKey && !isThreadRunning;@@ -681,6 +695,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThrreturn (<SidebarMenuSubItem+ ref={rowRef}className="w-full"data-thread-itemonMouseLeave={handleMouseLeave}diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.tsindex 2bcdaf76162..a4a2d57a8e9 100644--- a/apps/web/src/components/Sidebar.logic.ts+++ b/apps/web/src/components/Sidebar.logic.ts@@ -23,6 +23,57 @@ export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 200;// so this limit is a direct renderer-heap and server-load multiplier — keep// it small; cold opens still render instantly from the cached snapshot.export const SIDEBAR_THREAD_PREWARM_LIMIT = 3;+// A small buffer keeps the next few rows warm without leasing every row that+// content-visibility leaves mounted below the scroll viewport.+export const SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX = 160;++export function useSidebarRowSubscriptionLease(isActive: boolean): {+ readonly leaseLiveStatus: boolean;+ readonly rowRef: React.Dispatch<React.SetStateAction<HTMLElement | null>>;+} {+ const [row, setRow] = React.useState<HTMLElement | null>(null);+ const [isNearViewport, setIsNearViewport] = React.useState(isActive);++ React.useEffect(() => {+ if (isActive) {+ setIsNearViewport(true);+ return;+ }+ if (row === null) return;+ if (typeof IntersectionObserver === "undefined") {+ setIsNearViewport(true);+ return;+ }++ const scrollRoot = row.closest<HTMLElement>('[data-slot="scroll-area-viewport"]');+ const observer = new IntersectionObserver(+ ([entry]) => setIsNearViewport(entry?.isIntersecting === true),+ {+ root: scrollRoot,+ rootMargin: `${SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX}px 0px`,+ },+ );+ observer.observe(row);+ return () => observer.disconnect();+ }, [isActive, row]);++ return {+ leaseLiveStatus: isActive || isNearViewport,+ rowRef: setRow,+ };+}++// A row keeps the last live value it rendered so a released lease never+// blanks its badge. The value is bound to `key`, so a different worktree or+// linked pull request cannot reuse the previous one.+export function useRetainedValue<T>(key: string | null, value: T | null): T | null {+ const retained = React.useRef<{ readonly key: string; readonly value: T } | null>(null);+ if (key !== null && value !== null) {+ retained.current = { key, value };+ }+ if (value !== null) return value;+ return key !== null && retained.current?.key === key ? retained.current.value : null;+}// The list already reaches its destination through sortable transforms while// the pointer is down. dnd-kit's default also animates the committed DOM orderdiff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsxindex 18e19712930..98f2f997875 100644--- a/apps/web/src/components/Sidebar.tsx+++ b/apps/web/src/components/Sidebar.tsx@@ -143,6 +143,8 @@ import {sortPinnedThreadsForSidebar,sortSettledThreadsForSidebar,sortThreadsForSidebar,+ useRetainedValue,+ useSidebarRowSubscriptionLease,useThreadJumpHintVisibility,} from "./Sidebar.logic";import { resolveLocalCheckoutBranchMismatch } from "./BranchToolbar.logic";@@ -787,6 +789,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {[thread.environmentId, thread.id],);const threadKey = scopedThreadKey(threadRef);+ const { leaseLiveStatus, rowRef } = useSidebarRowSubscriptionLease(props.isActive);const isRegeneratingTitle = thread.titleRegeneration != null;const lastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]);const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey));@@ -800,21 +803,25 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {const gitCwd = thread.worktreePath ?? props.projectCwd;const linkedPullRequestStatus = useLinkedThreadPullRequest(- thread.environmentId,- thread.linkedPullRequest,+ leaseLiveStatus ? thread.environmentId : null,+ leaseLiveStatus ? thread.linkedPullRequest : null,);const gitStatus = useEnvironmentQuery(- (thread.branch != null || thread.worktreePath !== null) && gitCwd !== null+ leaseLiveStatus && (thread.branch != null || thread.worktreePath !== null) && gitCwd !== null? vcsEnvironment.status({environmentId: thread.environmentId,input: { cwd: gitCwd },}): null,);+ const visibleGitStatus = useRetainedValue(+ JSON.stringify([thread.environmentId, gitCwd]),+ gitStatus.data,+ );const retainTerminalOnBranchMismatch = thread.worktreePath === null;const pr = resolveDisplayedThreadPr({threadBranch: thread.branch,- gitStatus: gitStatus.data,+ gitStatus: visibleGitStatus,snapshot: changeRequestSnapshot,retainTerminalOnBranchMismatch,linkedPullRequest: thread.linkedPullRequest,@@ -909,11 +916,11 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {effectiveEnvMode: thread.worktreePath === null ? "local" : "worktree",activeWorktreePath: thread.worktreePath,activeThreadBranch: thread.branch,- currentGitBranch: gitStatus.data?.refName ?? null,+ currentGitBranch: visibleGitStatus?.refName ?? null,});const prProvider = resolveDisplayedThreadPrProvider({threadBranch: thread.branch,- gitStatus: gitStatus.data,+ gitStatus: visibleGitStatus,snapshot: changeRequestSnapshot,retainTerminalOnBranchMismatch,linkedPullRequest: thread.linkedPullRequest,@@ -924,7 +931,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {useEffect(() => {const nextSnapshot = nextThreadChangeRequestSnapshot({threadBranch: thread.branch,- gitStatus: gitStatus.data,+ gitStatus: visibleGitStatus,snapshot: changeRequestSnapshot,retainTerminalOnBranchMismatch,linkedPullRequest: thread.linkedPullRequest,@@ -934,7 +941,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {onChangeRequestSnapshot(threadKey, nextSnapshot);}, [changeRequestSnapshot,- gitStatus.data,+ visibleGitStatus,linkedPullRequestStatus,onChangeRequestSnapshot,retainTerminalOnBranchMismatch,@@ -1246,6 +1253,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {<TooltipTriggerrender={<div+ ref={rowRef}role="button"tabIndex={0}data-testid="sidebar-row-slim"@@ -1407,6 +1415,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {<TooltipTriggerrender={<div+ ref={rowRef}role="button"tabIndex={0}data-testid="sidebar-row-card"@@ -1635,22 +1644,29 @@ const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: {onSelect: () => void;}) {const { thread } = props;+ const { leaseLiveStatus, rowRef } = useSidebarRowSubscriptionLease(+ props.isHighlighted || props.isRouteActive,+ );// Same details tooltip as the regular rows: a search hit is still a thread,// and the hover card is how you disambiguate identically-titled results.const gitCwd = thread.worktreePath ?? props.projectCwd;const gitStatus = useEnvironmentQuery(- (thread.branch != null || thread.worktreePath !== null) && gitCwd !== null+ leaseLiveStatus && (thread.branch != null || thread.worktreePath !== null) && gitCwd !== null? vcsEnvironment.status({environmentId: thread.environmentId,input: { cwd: gitCwd },}): null,);+ const visibleGitStatus = useRetainedValue(+ JSON.stringify([thread.environmentId, gitCwd]),+ gitStatus.data,+ );const branchMismatch = resolveLocalCheckoutBranchMismatch({effectiveEnvMode: thread.worktreePath === null ? "local" : "worktree",activeWorktreePath: thread.worktreePath,activeThreadBranch: thread.branch,- currentGitBranch: gitStatus.data?.refName ?? null,+ currentGitBranch: visibleGitStatus?.refName ?? null,});const modelInstanceId = thread.session?.providerInstanceId ?? thread.modelSelection.instanceId;const providerEntry = props.providerEntryByInstanceId.get(modelInstanceId) ?? null;@@ -1674,6 +1690,7 @@ const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: {<TooltipTriggerrender={<button+ ref={rowRef}id={props.resultId}type="button"role="option"diff --git a/packages/client-runtime/src/state/pullRequests.ts b/packages/client-runtime/src/state/pullRequests.tsindex 22d44336ab0..b74553e57a9 100644--- a/packages/client-runtime/src/state/pullRequests.ts+++ b/packages/client-runtime/src/state/pullRequests.ts@@ -26,6 +26,8 @@ export class EnvironmentHttpConnectionNotReadyError extends Data.TaggedError("EnvironmentHttpConnectionNotReadyError",)<{ readonly message: string }> {}+export const LINKED_PULL_REQUEST_DETAIL_IDLE_TTL_MS = 5_000;+/** Refresh a linked PR while its thread is visible so merges update the sidebar. */export function createLinkedPullRequestDetailAtomFamily<R, E>(runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,@@ -35,6 +37,7 @@ export function createLinkedPullRequestDetailAtomFamily<R, E>(tag: WS_METHODS.pullRequestsDetail,staleTimeMs: 15_000,refreshIntervalMs: 30_000,+ idleTtlMs: LINKED_PULL_REQUEST_DETAIL_IDLE_TTL_MS,});}diff --git a/packages/client-runtime/src/state/vcs.ts b/packages/client-runtime/src/state/vcs.tsindex 04254833672..a932e7398d0 100644--- a/packages/client-runtime/src/state/vcs.ts+++ b/packages/client-runtime/src/state/vcs.ts@@ -31,6 +31,9 @@ import {const OFFLINE_BRANCH_LIST_LIMIT = 100;const VCS_REFS_IDLE_TTL_MS = 30_000;+// Rows keep the last status they rendered, so the live stream only needs a+// short grace period when virtualization or scrolling releases its consumer.+export const VCS_STATUS_IDLE_TTL_MS = 10_000;const VCS_REFS_RETRY_SCHEDULE = Schedule.exponential("1 second").pipe(Schedule.modifyDelay(({ duration }) =>Effect.succeed(Duration.min(duration, Duration.seconds(30))),@@ -275,6 +278,7 @@ export function createVcsEnvironmentAtoms<R, E>(listRefs,status: createEnvironmentSubscriptionAtomFamily(runtime, {label: "environment-data:vcs:status",+ idleTtlMs: VCS_STATUS_IDLE_TTL_MS,subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.subscribeVcsStatus>) =>subscribe(WS_METHODS.subscribeVcsStatus, input).pipe(Stream.mapAccum(