The best way to control Claude Code, Codex and more from any computer or phone
perf(clients): lease sidebar status by visibility (#9052)
Co-authored-by: Theo Browne <me@t3.gg> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Wout Stiens committed
Sep 2, 2026 at 03:13 UTC
fc53b273039cf5e0a932582b1fbb56e7223ad4ab
6 files changed
+181
-34
apps/mobile/src/state/use-thread-pr.ts
+75
-18
@@ -1,15 +1,33 @@
1
+import { useAtomValue } from "@effect/atom-react";
2
+import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
3
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
4
import {
5
createLinkedPullRequestDetailAtomFamily,
6
pullRequestDetailToVcsStatus,
7
} from "@t3tools/client-runtime/state/pull-requests";
8
+import { Atom } from "effect/unstable/reactivity";
9
+import { useCallback, useEffect, useMemo } from "react";
10
11
import { connectionAtomRuntime } from "../connection/runtime";
12
+import { appAtomRegistry } from "./atom-registry";
13
import { useEnvironmentQuery } from "./query";
14
import { presentThreadPr, type ThreadPrPresentation } from "./thread-pr-presentation";
15
import { vcsEnvironment } from "./vcs";
16
17
const linkedPullRequestDetailAtom = createLinkedPullRequestDetailAtomFamily(connectionAtomRuntime);
18
+const MAX_THREAD_PR_SNAPSHOTS = 500;
19
+
20
+interface ThreadPrSnapshot {
21
+ readonly identity: string;
22
+ readonly presentation: ThreadPrPresentation;
23
+}
24
+
25
+// One bounded cache survives row virtualization without retaining one live
26
+// atom for every thread, branch, directory, or linked pull request ever seen.
27
+const threadPrSnapshotsAtom = Atom.make<ReadonlyMap<string, ThreadPrSnapshot>>(new Map()).pipe(
28
+ Atom.keepAlive,
29
+ Atom.withLabel("mobile:thread-pr-snapshots"),
30
+);
31
32
export {
33
presentThreadPr,
@@ -28,6 +46,19 @@ export function useThreadPr(
46
projectCwd: string | null,
47
): ThreadPrPresentation | null {
48
const cwd = thread.worktreePath ?? projectCwd;
49
+ const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
50
+ const snapshotIdentity = JSON.stringify(
51
+ thread.linkedPullRequest ?? { branch: thread.branch, cwd },
52
+ );
53
+ // Select this row's entry so writes for other rows do not re-render it.
54
+ const snapshotEntry = useAtomValue(
55
+ threadPrSnapshotsAtom,
56
+ useCallback(
57
+ (current: ReadonlyMap<string, ThreadPrSnapshot>) => current.get(threadKey),
58
+ [threadKey],
59
+ ),
60
+ );
61
+ const snapshot = snapshotEntry?.identity === snapshotIdentity ? snapshotEntry.presentation : null;
62
const gitStatus = useEnvironmentQuery(
63
thread.linkedPullRequest == null && thread.branch !== null && cwd !== null
64
? vcsEnvironment.status({
@@ -49,23 +80,49 @@ export function useThreadPr(
80
}),
81
);
82
52
- if (thread.linkedPullRequest != null) {
53
- const detail = linkedPullRequest.data;
54
- return detail === null
55
- ? null
56
- : presentThreadPr(pullRequestDetailToVcsStatus(detail), {
57
- kind: detail.provider,
58
- name: detail.provider,
59
- baseUrl: "",
60
- });
61
- }
83
+ const live = useMemo<ThreadPrPresentation | null | undefined>(() => {
84
+ if (thread.linkedPullRequest != null) {
85
+ const detail = linkedPullRequest.data;
86
+ return detail === null
87
+ ? undefined
88
+ : presentThreadPr(pullRequestDetailToVcsStatus(detail), {
89
+ kind: detail.provider,
90
+ name: detail.provider,
91
+ baseUrl: "",
92
+ });
93
+ }
94
+
95
+ const status = gitStatus.data;
96
+ if (thread.branch === null) return null;
97
+ if (status === null) return undefined;
98
+ if (status.refName !== thread.branch || !status.pr) return null;
99
+ return presentThreadPr(status.pr, status.sourceControlProvider);
100
+ }, [gitStatus.data, linkedPullRequest.data, thread.branch, thread.linkedPullRequest]);
101
+
102
+ useEffect(() => {
103
+ if (live === undefined) return;
104
+ appAtomRegistry.modify(threadPrSnapshotsAtom, (current) => {
105
+ const existing = current.get(threadKey);
106
+ if (live === null) {
107
+ if (existing === undefined) return [false, current];
108
+ const next = new Map(current);
109
+ next.delete(threadKey);
110
+ return [true, next];
111
+ }
112
+ if (existing?.identity === snapshotIdentity && existing.presentation === live) {
113
+ return [false, current];
114
+ }
115
+ const next = new Map(current);
116
+ next.delete(threadKey);
117
+ next.set(threadKey, { identity: snapshotIdentity, presentation: live });
118
+ while (next.size > MAX_THREAD_PR_SNAPSHOTS) {
119
+ const oldestKey = next.keys().next().value;
120
+ if (oldestKey === undefined) break;
121
+ next.delete(oldestKey);
122
+ }
123
+ return [true, next];
124
+ });
125
+ }, [live, snapshotIdentity, threadKey]);
126
63
- const status = gitStatus.data;
64
- if (status === null || thread.branch === null || status.refName !== thread.branch) {
65
- return null;
66
- }
67
- if (!status.pr) {
68
- return null;
69
- }
70
- return presentThreadPr(status.pr, status.sourceControlProvider);
127
+ return live === undefined ? snapshot : live;
128
}
apps/web/src/components/LegacySidebar.tsx
+21
-6
@@ -185,6 +185,8 @@ import {
185
orderItemsByPreferredIds,
186
shouldClearThreadSelectionOnMouseDown,
187
sortProjectsForSidebar,
188
+ useRetainedValue,
189
+ useSidebarRowSubscriptionLease,
190
useThreadJumpHintVisibility,
191
ThreadStatusPill,
192
} from "./Sidebar.logic";
@@ -376,6 +378,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
378
} = props;
379
const threadRef = scopeThreadRef(thread.environmentId, thread.id);
380
const threadKey = scopedThreadKey(threadRef);
381
+ const { leaseLiveStatus, rowRef } = useSidebarRowSubscriptionLease(isActive);
382
const lastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]);
383
const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey));
384
const runningTerminalIds = useThreadRunningTerminalIds({
@@ -417,7 +420,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
420
const threadProjectCwd = threadProject?.workspaceRoot ?? null;
421
const gitCwd = thread.worktreePath ?? threadProjectCwd ?? props.projectCwd;
422
const gitStatus = useEnvironmentQuery(
420
- thread.linkedPullRequest == null && thread.branch != null && gitCwd !== null
423
+ leaseLiveStatus && thread.linkedPullRequest == null && thread.branch != null && gitCwd !== null
424
? vcsEnvironment.status({
425
environmentId: thread.environmentId,
426
input: { cwd: gitCwd },
@@ -459,16 +462,27 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
462
},
463
});
464
const linkedPullRequestStatus = useLinkedThreadPullRequest(
462
- thread.environmentId,
463
- thread.linkedPullRequest,
465
+ leaseLiveStatus ? thread.environmentId : null,
466
+ leaseLiveStatus ? thread.linkedPullRequest : null,
467
+ );
468
+ const visibleGitStatus = useRetainedValue(
469
+ JSON.stringify([thread.environmentId, gitCwd]),
470
+ gitStatus.data,
471
+ );
472
+ const visibleLinkedPullRequestStatus = useRetainedValue(
473
+ thread.linkedPullRequest === null
474
+ ? null
475
+ : JSON.stringify([thread.environmentId, thread.linkedPullRequest]),
476
+ linkedPullRequestStatus,
477
);
478
const pr =
479
thread.linkedPullRequest == null
467
- ? resolveThreadPr({ threadBranch: thread.branch, gitStatus: gitStatus.data })
468
- : (linkedPullRequestStatus?.pr ?? null);
480
+ ? resolveThreadPr({ threadBranch: thread.branch, gitStatus: visibleGitStatus })
481
+ : (visibleLinkedPullRequestStatus?.pr ?? null);
482
const prStatus = prStatusIndicator(
483
pr,
471
- linkedPullRequestStatus?.sourceControlProvider ?? gitStatus.data?.sourceControlProvider,
484
+ visibleLinkedPullRequestStatus?.sourceControlProvider ??
485
+ visibleGitStatus?.sourceControlProvider,
486
);
487
const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
488
const isConfirmingArchive = confirmingArchiveThreadKey === threadKey && !isThreadRunning;
@@ -681,6 +695,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
695
696
return (
697
<SidebarMenuSubItem
698
+ ref={rowRef}
699
className="w-full"
700
data-thread-item
701
onMouseLeave={handleMouseLeave}
apps/web/src/components/Sidebar.logic.ts
+51
@@ -23,6 +23,57 @@ export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 200;
23
// so this limit is a direct renderer-heap and server-load multiplier — keep
24
// it small; cold opens still render instantly from the cached snapshot.
25
export const SIDEBAR_THREAD_PREWARM_LIMIT = 3;
26
+// A small buffer keeps the next few rows warm without leasing every row that
27
+// content-visibility leaves mounted below the scroll viewport.
28
+export const SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX = 160;
29
+
30
+export function useSidebarRowSubscriptionLease(isActive: boolean): {
31
+ readonly leaseLiveStatus: boolean;
32
+ readonly rowRef: React.Dispatch<React.SetStateAction<HTMLElement | null>>;
33
+} {
34
+ const [row, setRow] = React.useState<HTMLElement | null>(null);
35
+ const [isNearViewport, setIsNearViewport] = React.useState(isActive);
36
+
37
+ React.useEffect(() => {
38
+ if (isActive) {
39
+ setIsNearViewport(true);
40
+ return;
41
+ }
42
+ if (row === null) return;
43
+ if (typeof IntersectionObserver === "undefined") {
44
+ setIsNearViewport(true);
45
+ return;
46
+ }
47
+
48
+ const scrollRoot = row.closest<HTMLElement>('[data-slot="scroll-area-viewport"]');
49
+ const observer = new IntersectionObserver(
50
+ ([entry]) => setIsNearViewport(entry?.isIntersecting === true),
51
+ {
52
+ root: scrollRoot,
53
+ rootMargin: `${SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX}px 0px`,
54
+ },
55
+ );
56
+ observer.observe(row);
57
+ return () => observer.disconnect();
58
+ }, [isActive, row]);
59
+
60
+ return {
61
+ leaseLiveStatus: isActive || isNearViewport,
62
+ rowRef: setRow,
63
+ };
64
+}
65
+
66
+// A row keeps the last live value it rendered so a released lease never
67
+// blanks its badge. The value is bound to `key`, so a different worktree or
68
+// linked pull request cannot reuse the previous one.
69
+export function useRetainedValue<T>(key: string | null, value: T | null): T | null {
70
+ const retained = React.useRef<{ readonly key: string; readonly value: T } | null>(null);
71
+ if (key !== null && value !== null) {
72
+ retained.current = { key, value };
73
+ }
74
+ if (value !== null) return value;
75
+ return key !== null && retained.current?.key === key ? retained.current.value : null;
76
+}
77
78
// The list already reaches its destination through sortable transforms while
79
// the pointer is down. dnd-kit's default also animates the committed DOM order
apps/web/src/components/Sidebar.tsx
+27
-10
@@ -143,6 +143,8 @@ import {
143
sortPinnedThreadsForSidebar,
144
sortSettledThreadsForSidebar,
145
sortThreadsForSidebar,
146
+ useRetainedValue,
147
+ useSidebarRowSubscriptionLease,
148
useThreadJumpHintVisibility,
149
} from "./Sidebar.logic";
150
import { resolveLocalCheckoutBranchMismatch } from "./BranchToolbar.logic";
@@ -787,6 +789,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
789
[thread.environmentId, thread.id],
790
);
791
const threadKey = scopedThreadKey(threadRef);
792
+ const { leaseLiveStatus, rowRef } = useSidebarRowSubscriptionLease(props.isActive);
793
const isRegeneratingTitle = thread.titleRegeneration != null;
794
const lastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]);
795
const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey));
@@ -800,21 +803,25 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
803
804
const gitCwd = thread.worktreePath ?? props.projectCwd;
805
const linkedPullRequestStatus = useLinkedThreadPullRequest(
803
- thread.environmentId,
804
- thread.linkedPullRequest,
806
+ leaseLiveStatus ? thread.environmentId : null,
807
+ leaseLiveStatus ? thread.linkedPullRequest : null,
808
);
809
const gitStatus = useEnvironmentQuery(
807
- (thread.branch != null || thread.worktreePath !== null) && gitCwd !== null
810
+ leaseLiveStatus && (thread.branch != null || thread.worktreePath !== null) && gitCwd !== null
811
? vcsEnvironment.status({
812
environmentId: thread.environmentId,
813
input: { cwd: gitCwd },
814
})
815
: null,
816
);
817
+ const visibleGitStatus = useRetainedValue(
818
+ JSON.stringify([thread.environmentId, gitCwd]),
819
+ gitStatus.data,
820
+ );
821
const retainTerminalOnBranchMismatch = thread.worktreePath === null;
822
const pr = resolveDisplayedThreadPr({
823
threadBranch: thread.branch,
817
- gitStatus: gitStatus.data,
824
+ gitStatus: visibleGitStatus,
825
snapshot: changeRequestSnapshot,
826
retainTerminalOnBranchMismatch,
827
linkedPullRequest: thread.linkedPullRequest,
@@ -909,11 +916,11 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
916
effectiveEnvMode: thread.worktreePath === null ? "local" : "worktree",
917
activeWorktreePath: thread.worktreePath,
918
activeThreadBranch: thread.branch,
912
- currentGitBranch: gitStatus.data?.refName ?? null,
919
+ currentGitBranch: visibleGitStatus?.refName ?? null,
920
});
921
const prProvider = resolveDisplayedThreadPrProvider({
922
threadBranch: thread.branch,
916
- gitStatus: gitStatus.data,
923
+ gitStatus: visibleGitStatus,
924
snapshot: changeRequestSnapshot,
925
retainTerminalOnBranchMismatch,
926
linkedPullRequest: thread.linkedPullRequest,
@@ -924,7 +931,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
931
useEffect(() => {
932
const nextSnapshot = nextThreadChangeRequestSnapshot({
933
threadBranch: thread.branch,
927
- gitStatus: gitStatus.data,
934
+ gitStatus: visibleGitStatus,
935
snapshot: changeRequestSnapshot,
936
retainTerminalOnBranchMismatch,
937
linkedPullRequest: thread.linkedPullRequest,
@@ -934,7 +941,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
941
onChangeRequestSnapshot(threadKey, nextSnapshot);
942
}, [
943
changeRequestSnapshot,
937
- gitStatus.data,
944
+ visibleGitStatus,
945
linkedPullRequestStatus,
946
onChangeRequestSnapshot,
947
retainTerminalOnBranchMismatch,
@@ -1246,6 +1253,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
1253
<TooltipTrigger
1254
render={
1255
<div
1256
+ ref={rowRef}
1257
role="button"
1258
tabIndex={0}
1259
data-testid="sidebar-row-slim"
@@ -1407,6 +1415,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
1415
<TooltipTrigger
1416
render={
1417
<div
1418
+ ref={rowRef}
1419
role="button"
1420
tabIndex={0}
1421
data-testid="sidebar-row-card"
@@ -1635,22 +1644,29 @@ const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: {
1644
onSelect: () => void;
1645
}) {
1646
const { thread } = props;
1647
+ const { leaseLiveStatus, rowRef } = useSidebarRowSubscriptionLease(
1648
+ props.isHighlighted || props.isRouteActive,
1649
+ );
1650
// Same details tooltip as the regular rows: a search hit is still a thread,
1651
// and the hover card is how you disambiguate identically-titled results.
1652
const gitCwd = thread.worktreePath ?? props.projectCwd;
1653
const gitStatus = useEnvironmentQuery(
1642
- (thread.branch != null || thread.worktreePath !== null) && gitCwd !== null
1654
+ leaseLiveStatus && (thread.branch != null || thread.worktreePath !== null) && gitCwd !== null
1655
? vcsEnvironment.status({
1656
environmentId: thread.environmentId,
1657
input: { cwd: gitCwd },
1658
})
1659
: null,
1660
);
1661
+ const visibleGitStatus = useRetainedValue(
1662
+ JSON.stringify([thread.environmentId, gitCwd]),
1663
+ gitStatus.data,
1664
+ );
1665
const branchMismatch = resolveLocalCheckoutBranchMismatch({
1666
effectiveEnvMode: thread.worktreePath === null ? "local" : "worktree",
1667
activeWorktreePath: thread.worktreePath,
1668
activeThreadBranch: thread.branch,
1653
- currentGitBranch: gitStatus.data?.refName ?? null,
1669
+ currentGitBranch: visibleGitStatus?.refName ?? null,
1670
});
1671
const modelInstanceId = thread.session?.providerInstanceId ?? thread.modelSelection.instanceId;
1672
const providerEntry = props.providerEntryByInstanceId.get(modelInstanceId) ?? null;
@@ -1674,6 +1690,7 @@ const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: {
1690
<TooltipTrigger
1691
render={
1692
<button
1693
+ ref={rowRef}
1694
id={props.resultId}
1695
type="button"
1696
role="option"
packages/client-runtime/src/state/pullRequests.ts
+3
@@ -26,6 +26,8 @@ export class EnvironmentHttpConnectionNotReadyError extends Data.TaggedError(
26
"EnvironmentHttpConnectionNotReadyError",
27
)<{ readonly message: string }> {}
28
29
+export const LINKED_PULL_REQUEST_DETAIL_IDLE_TTL_MS = 5_000;
30
+
31
/** Refresh a linked PR while its thread is visible so merges update the sidebar. */
32
export function createLinkedPullRequestDetailAtomFamily<R, E>(
33
runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
@@ -35,6 +37,7 @@ export function createLinkedPullRequestDetailAtomFamily<R, E>(
37
tag: WS_METHODS.pullRequestsDetail,
38
staleTimeMs: 15_000,
39
refreshIntervalMs: 30_000,
40
+ idleTtlMs: LINKED_PULL_REQUEST_DETAIL_IDLE_TTL_MS,
41
});
42
}
43
packages/client-runtime/src/state/vcs.ts
+4
@@ -31,6 +31,9 @@ import {
31
32
const OFFLINE_BRANCH_LIST_LIMIT = 100;
33
const VCS_REFS_IDLE_TTL_MS = 30_000;
34
+// Rows keep the last status they rendered, so the live stream only needs a
35
+// short grace period when virtualization or scrolling releases its consumer.
36
+export const VCS_STATUS_IDLE_TTL_MS = 10_000;
37
const VCS_REFS_RETRY_SCHEDULE = Schedule.exponential("1 second").pipe(
38
Schedule.modifyDelay(({ duration }) =>
39
Effect.succeed(Duration.min(duration, Duration.seconds(30))),
@@ -275,6 +278,7 @@ export function createVcsEnvironmentAtoms<R, E>(
278
listRefs,
279
status: createEnvironmentSubscriptionAtomFamily(runtime, {
280
label: "environment-data:vcs:status",
281
+ idleTtlMs: VCS_STATUS_IDLE_TTL_MS,
282
subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.subscribeVcsStatus>) =>
283
subscribe(WS_METHODS.subscribeVcsStatus, input).pipe(
284
Stream.mapAccum(