perf(client): provider status pushes no longer re-render environment presentation consumers #20821
main fromrefs/pull/20821/head·merged by juliusmarminge View on GitHubProblem#
Render audit, every settings page, idle across one providerStatuses push: 184 renders in 2 commits. Top causes were 24 SidebarMenuItem, 22 SidebarMenuButton, SettingsSidebarNav, RootRouteView, FirstRunGate, EventRouter and about 20 root coordinators (ProviderAuthCallbackCoordinator, PermissionUpdateNotice, ProjectCloneToastCoordinator, ProviderUpdateLaunchNotification, CommandPalette, SettingsScopeProvider, ...).
The hook-slot diff showed {entry, connection, serverConfig} getting a new identity on each push. EnvironmentPresentation.serverConfig was the full ServerConfig. The projection already keeps unchanged providers through reuseUnchanged (#20392), but a push still builds a new config object with fresh checkedAt stamps. So presentationAtom built a new presentation, presentationsAtom built a new map, and every useEnvironments() / usePrimaryEnvironment() subscriber re-rendered, though none of them reads providers.
Fix#
EnvironmentPresentation.serverConfigis nowOmit<ServerConfig, "providers">(EnvironmentServerConfig).presentationAtomdropsprovidersand keeps the previous object whenentry,connection(compared by phase, error and traceId) and every remaining top-level config field are unchanged. A provider push now leaves the presentation,presentationsAtomanduseEnvironments().environmentsat the same reference.- Provider readers use a separate
providersByEnvironmentAtom(Map<EnvironmentId, providers>, reused when no array changed). On web that is theuseEnvironmentProviders()hook. Callers: ChatView, CommandPalette, ProviderUpdatesAction, ProviderUpdateLaunchNotification, ProjectDefaultsSettings, useScopedModelAvailability, SettingsPanels, SourceControlWritingSettings, ChatGptWelcomeCoordinator, UsagePage, plus mobile's provider accounts screen.NewThreadLinkViewonly needs providers in a handler, so it reads them fromappAtomRegistrywhen the handler runs. - Usage-limit surfaces (web
UsageLimits, mobileUsageLimitsPooled,ChatGptUsageSummaryand the widget snapshot) read limits from providers, so they usepresentationsWithProvidersAtom. That atom reattaches the full config.LimitPresentations.providersis now required, so a caller that passes a provider-less presentation fails to typecheck instead of quietly showing no limits.
The type change makes the compiler list every reader that needs providers, so none of them can quietly get an empty list.
Why consumers now bail out (compiled output, oxc-transform-react)#
useEnvironments compiles to:
const presentationById = useAtomValue(environmentPresentations.presentationsAtom);
if ($[0] !== presentationById) { t0 = [...presentationById.entries()].map(_temp); ... } else { t0 = $[1]; }
if ($[2] !== catalog.isReady || $[3] !== environments || $[4] !== networkStatus || $[5] !== presentationById) { t1 = {...} } else { t1 = $[6]; }
Before, presentationById changed on every push, which invalidated $[0], then environments, then the returned object. After, presentationsAtom returns the same map, so the atom does not notify and the subscriber does not re-render. Even when a component re-renders for another reason, environments and the returned object stay cached.
In useAvailableSettingsSearchItems (SettingsSidebarNav), the cache keys $[2], $[4] and $[6] (environments) no longer change, so the filtered nav list and its 11 SidebarMenuButtons keep their props.
All 14 touched web files compile with 0 React Compiler diagnostics.
presentation.test.ts has a new test. When only providers change, presentationsAtom keeps its reference and does not notify subscribers, while providersByEnvironmentAtom notifies exactly once. A change to any other config field still updates the presentation.
Sidebar thread rows (second commit)#
The re-measure showed the settings win (370 to 106 renders per push) but no change on the thread view (400 to 390). Of what was left there, the timeline rows come from the providerStatuses context in MessagesTimeline (#20854), and ChatMarkdown comes from its config subscriptions (#20852). Neither PR, nor the merged #20814 (minute tick), covers the sidebar part: per push, 5 SidebarThreadRow#31<useSyncExternalStore>, SidebarThreadTooltip#0, SidebarProviderStack props:providerEntryByInstanceId and their ~140 tooltip renders.
Two causes, both the full environmentServerConfigsAtom map, which changes on every provider push:
useSidebarLookupsrebuilt each environment's provider entry map fromconfig.providers, so every memoized row got a newproviderEntryByInstanceId.useSupportsMultiplePullRequests(in each row, its tooltip anduseLinkedThreadPullRequest) subscribed to the whole map to read one capability.
Fix:
environmentPresentations.serverConfigsAtomis the enabled environments'EnvironmentServerConfig(no providers) built from the presentations, so it keeps its identity across provider pushes. WebuseServerConfigs()now returns it. That covers every web capability reader (sidebar, PR rows and panels,CommandOutputPanel,RightPanelTabs, ...). The one reader that needs providers,ThreadRelationshipsPanel, now usesuseEnvironmentProviders().environmentServerConfigsAtomitself is unchanged, so mobile is unaffected.sidebarProviderEntriesAtomderives the sidebar's per-environment entries and keeps each environment's map while the fields rows show (instance id, driver, name, accent, registry icon, models) are unchanged. The models array is already reused byreuseUnchangedwhen nothing in it changed.
Compiled (oxc-transform-react): useSidebarLookups now reads useAtomValue(sidebarProviderEntriesAtom) directly, so the row prop providerEntriesByEnvironment.get(thread.environmentId) keeps its reference on a checkedAt-only push and the memo row bails out. Sidebar.tsx, ThreadRelationshipsControl.tsx and entities.ts compile with 0 diagnostics.
What still renders on a provider push#
- Thread view: the timeline rows and
ChatMarkdown. They are fixed in #20854 and #20852, so the thread-view gain needs those PRs as well as this one. - Components that read providers: ChatView, CommandPalette's provider entry map, the provider update pill and actions, provider settings, and usage limits. Their data really changed (at minimum
checkedAt). primaryServerConfigAtomconsumers (DocumentTitleSync,FirstRunGate,GeneralSettingsPanel) still get the full config on each push. That atom is not part of this change.
After: settings pages 370 to 106 renders per push (first commit, re-measured). Thread view: to be re-measured with the second commit.
Checks run: typecheck for apps/web, apps/mobile, packages/client-runtime and packages/shared; reactCompilerCoverage, the Sidebar.logic, ThreadRelationshipsControl.agents, ThreadStatusIndicators.subscriptions, ThreadDetailsPrRow, PullRequestDetailPanel, ProviderSettingsPanel.environment and useHandleNewThread tests; presentation.test.ts, usageLimits.test.ts, the UsagePage, WelcomeWizard, ProjectSettingsPanel, SourceControlWritingSettings, IntegrationsSettings and ProviderUpdateEnvironmentRows tests, and the mobile usage and widget tests; scoped lint on the changed files.
Opus 5.5 via Claude Code.
🤖 Generated with Claude Code
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
juliusmarminge added labelsmacroscope-review
Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Provider Metric Main baseline This PR Impact PR ceiling Codex Total thread wire 5.0 KiB 4.9 KiB −23 B (−0.5%) 6.8 KiB ✅ Codex Thread snapshot wire 3.8 KiB 3.8 KiB 0 B (0.0%) 4.9 KiB ✅ Codex Live turn WebSocket wire 1.2 KiB 1.2 KiB −23 B (−1.9%) 2.0 KiB ✅ Codex Live turn WebSocket decoded 20.9 KiB 20.8 KiB −41 B (−0.2%) 29.3 KiB ✅ Codex Live turn messages 2 1 −1 (−50.0%) 8 ✅ Claude Total thread wire 5.0 KiB 5.0 KiB +24 B (+0.5%) 6.8 KiB ✅ Claude Thread snapshot wire 3.8 KiB 3.8 KiB 0 B (0.0%) 4.9 KiB ✅ Claude Live turn WebSocket wire 1.2 KiB 1.2 KiB +24 B (+2.0%) 2.0 KiB ✅ Claude Live turn WebSocket decoded 21.2 KiB 21.2 KiB +41 B (+0.2%) 29.3 KiB ✅ Claude Live turn messages 1 2 +1 (+100.0%) 8 ✅ Baseline:
edb2155· PR result:cc8b47f· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
- Codex decoded thread snapshot: 108.5 KiB
- Claude decoded thread snapshot: 108.8 KiB
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
-
⚙️ Run configuration
-
- Configuration used: Path: .coderabbit.config.ts
- Review profile: CHILL
- Plan: Team
- Run ID:
78b54a65-6860-449b-9cee-aadeea10c684
📥 Commits
-
Reviewing files that changed from the base of the PR and between 9946bf7a4fd83bdc3bdc83077547f792ee323a7b and cc8b47f59adfa21ced22376e71163dc92d5951cc.
📒 Files selected for processing: 6
-
apps/web/src/components/ChatView.tsxapps/web/src/components/CommandPalette.tsxapps/web/src/components/chat/ThreadRelationshipsControl.agents.test.tsxapps/web/src/components/chat/ThreadRelationshipsControl.tsxapps/web/src/components/usage/UsagePage.tsxapps/web/src/state/entities.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.
-
📝 Walkthrough
-
Provider data now has separate state from base environment presentations. Web and mobile provider-selection, settings, account, sidebar, relationship, and usage paths read provider maps or provider-enriched presentations.
Changes: Provider state and consumers
Layer / File(s) Summary Separate provider state from presentations
packages/client-runtime/src/connection/presentation.ts,packages/client-runtime/src/state/presentation.ts,packages/client-runtime/src/state/presentation.test.ts,apps/web/src/state/environments.ts,apps/web/src/state/entities.tsBase presentations use provider-free server configuration. Separate atoms expose server configurations, providers by environment, and presentations with providers. Tests cover provider-only updates and reference reuse. Web provider consumers
apps/web/src/components/ChatView.tsx,apps/web/src/components/CommandPalette.tsx,apps/web/src/components/Sidebar.tsx,apps/web/src/components/chat/*,apps/web/src/components/Provider*,apps/web/src/components/promptLinks/*,apps/web/src/components/usage/UsagePage.tsxWeb chat, prompt, provider-update, sidebar, relationship, and sharing paths read provider data by environment. Sidebar derives narrowed provider entries and reuses unchanged maps. Settings and account provider consumers
apps/web/src/components/settings/*,apps/web/src/components/cloud/CloudEnvironmentConnectList.tsx,apps/mobile/src/features/settings/SettingsProviderAccountsRouteScreen.tsxSettings and mobile account screens use mapped providers for provider lists and model checks. Some server configuration inputs now require only the environment field. Usage data and provider requirements
apps/web/src/components/usage/*,apps/mobile/src/features/usage/*,apps/mobile/src/widgets/SubscriptionUsageCoordinator.tsx,packages/shared/src/usageLimits.ts,packages/shared/src/usageLimits.test.tsUsage views read provider-enriched presentations or provider maps. Usage-limit inputs require provider arrays, and fixtures include empty arrays. Priority: ➖ Normal
Estimated code review effort: 3 (Moderate) | ~25 minutes
Change: Refactor
Suggested reviewers:
maria-rcks
Merge Risk: ⚪ Minimal · up to
cc8b4-
No actionable merge-blocking risk is established for the provider-state change; it is ready for normal merge checks.
Pre-merge checks:
3 · 1-
Failed checks: 1 warningCheck name Status Explanation Resolution Description check The description gives detailed problem, implementation, performance results, limitations, and verification details. However, it omits the required Scope and approval section and does not provide the r… Add a Scope and approval section with the linked issue or maintainer approval, or explain why this focused fix qualifies for an exemption. Add before/after UI evidence as required, or state why screenshots and recordings are not applicable. Passed checks: 3 passed-
Check name Status Explanation Title check The title clearly and concisely describes the main performance change: provider-status pushes no longer re-render environment presentation consumers. Linked Issues check Check skipped because no linked issues were found for this pull request. Out of Scope Changes check Check skipped because no linked issues were found for this pull request.
Full details: Description check
-
Explanation
The description gives detailed problem, implementation, performance results, limitations, and verification details. However, it omits the required Scope and approval section and does not provide the required UI evidence or explain why that evidence is not applicable.
Resolution
Add a Scope and approval section with the linked issue or maintainer approval, or explain why this focused fix qualifies for an exemption. Add before/after UI evidence as required, or state why screenshots and recordings are not applicable.
-
- Fix all pre-merge checks with AI
✨ Finishing Touches
-
📝 Generate docstrings
-
- Commit to this branch
- Create a new PR
🧪 Generate unit tests (beta)
-
- Commit to this branch
- Create a new PR
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
-
Re-measured in the app (seeded data, same scenario, median of 3):
The page sits idle while a second tab clicks Settings > Providers "Refresh", which gives 3-5
providerStatusespushes per window. Server runs without--watchand there were no reconnects. Numbers are renders in the commit that follows each push (median push).scenario main this PR Settings > General, renders per push 370 106 Settings > General, 15s window (4 pushes) 1470 414 thread view, renders per push 400 390 Settings: a 71% drop. On main, each push re-rendered
RootRouteView, 40SettingsRows and the whole settings sidebar nav. With this PR none of those render. What's left (~106) starts at components that still read the full config or providers:DocumentTitleSync,ChatGptWelcomeCoordinator,FirstRunGate#25,EventRouter,ProviderUpdatePrimaryNotification,CommandPalette,SidebarUpdateControl,GeneralSettingsPanel,ProjectDefaultsSettings. The provider-reading ones are legitimate.DocumentTitleSync,FirstRunGateandGeneralSettingsPanellook likeprimaryServerConfigAtomreaders (out of scope per the PR body).Thread view: almost unchanged (400 → 390). The push still re-renders the whole timeline: 11
ChatMarkdown#8<useContext>, theAssistantTimelineRow/UserTimelineRow/MessageMeta/ForkButton/RevertUserMessageButton×5-6 rows, and the sidebar rows (SidebarThreadRow#31,SidebarThreadTooltip). That comes through a context thatChatViewprovides from provider data, and this PR doesn't address it. One PR run had a reconnect-free but noisy first window (40 commits, a router/MatchImpl churn unrelated to the push), so I added a 4th run. The 3 clean runs were 390/390/390.Behaviour: Settings > Providers still shows each provider's version and auth status, and "Checked just now" updates after Refresh. Usage limits and the provider update pill still render.
Merge state: conflicts with main.
Re-measured the reworked PR in the app (seeded data, median of 3 per side):
This PR no longer cherry-picks onto today's main (
2fae0f9841). It conflicts inChatView.tsxwith #20854. So I measured the PR head9946bf7a4fagainst its merge-base130f4a2457, and also measured main fresh for reference. The server ran without--watch, and none of the push windows had a reconnect. Each push window: the page sits idle while a second tab clicks Settings > Providers "Refresh", which gives 4providerStatusespushes. "Per push" counts the renders in the commits within 300 ms of each push.scenario main 2fae0f98merge-base 130f4a24this PR Settings > General, renders per push 370 372 105 Settings > General, 15 s window 1470 1492 424 thread view, renders per push 311 323 146 thread view, 15 s window 1240 1294 580 2 environments: env2 offline 12 s then back, thread in env1, whole window 1938 (1926 / 1938 / 2877) 2031 (2031 / 2031 / 2673) 1207 (1207 / 1207 / 1495) ↳ ChatViewrenders in that window15 15 7 ↳ EnvironmentPermissionNoticerenders31 31 15 (The env2 server ran from a copy of lane 4's second data dir on port 14299, paired through Settings > Connections. The high outlier in each column is a window where provider pushes landed during the reconnect.)
Settings: a 72% drop, the same as round 1. On a push, the 40
SettingsRows,RootRouteViewand the settings nav no longer render. What's left (~105) starts atDocumentTitleSync,ChatGptWelcomeCoordinator,FirstRunGate#25,EventRouter,ProviderUpdatePrimaryNotification,CommandPalette,SidebarUpdateControl,GeneralSettingsPanelandProjectDefaultsSettings, which are the provider and server-config readers.Thread view: this is the new part, and it works. The sidebar rows used to re-render on every push (
SidebarThreadRow#34x8,SidebarThreadTooltipx8, about 38TooltipTrigger). They now don't render at all. The 146 that's left is the same set of root coordinators plusSidebar#24,SidebarProviderUpdatePilland 8SortableThreadRow(which bail out below).Two environments: halved.
ChatViewnow renders 7 times instead of 15 while env2 drops and comes back. The remaining cost is the sidebar (SortableThreadRow parent-same-props<-SortableContext, ~112TooltipTrigger), with 24SidebarThreadRowrenders on both sides. Those come from env2's threads leaving and coming back in the list, which is real content.Behaviour check: Settings > Providers still shows each provider's version and auth status ("Codex v0.163.0, Authenticated", "Claude v2.1.301, Authenticated"), and "Checked …" updates after Refresh. The sidebar rows still show their provider marks. Settings > Connections shows env2 as "Reconnecting…" while it's down and "Connected" after it comes back.
Merge state: conflicts with main (
ChatView.tsx, against #20854'stimelineProviderschange). It needs a rebase before it can land.Screenshot (PR, thread view after the pushes):
/home/julius/.cache/audit/remeasure/20821-after.pngjuliusmarminge merged this4a5dade
juliusmarminge closed this
Sign in to join this conversation.
Approvability#
Verdict: Needs Human Approval
Macroscope's review found this PR requires human approval — This is a broad shared-state refactor that changes environment presentation contracts and rerender/subscription behavior across web and mobile consumers. The intended performance gain is clear and tests were added, but the cross-cutting runtime impact warrants human review.
You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).