Skip to content
Source
Sign inSign up
pingdotgg/t3code

perf(client): provider status pushes no longer re-render environment presentation consumers #20821

Mergedjuliusmarmingemerged 2 commits intomain fromrefs/pull/20821/headmerged by juliusmarminge View on GitHub

juliusmarmingecommented

Problem

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.serverConfig is now Omit<ServerConfig, "providers"> (EnvironmentServerConfig). presentationAtom drops providers and keeps the previous object when entry, connection (compared by phase, error and traceId) and every remaining top-level config field are unchanged. A provider push now leaves the presentation, presentationsAtom and useEnvironments().environments at the same reference.
  • Provider readers use a separate providersByEnvironmentAtom (Map<EnvironmentId, providers>, reused when no array changed). On web that is the useEnvironmentProviders() hook. Callers: ChatView, CommandPalette, ProviderUpdatesAction, ProviderUpdateLaunchNotification, ProjectDefaultsSettings, useScopedModelAvailability, SettingsPanels, SourceControlWritingSettings, ChatGptWelcomeCoordinator, UsagePage, plus mobile's provider accounts screen. NewThreadLinkView only needs providers in a handler, so it reads them from appAtomRegistry when the handler runs.
  • Usage-limit surfaces (web UsageLimits, mobile UsageLimitsPooled, ChatGptUsageSummary and the widget snapshot) read limits from providers, so they use presentationsWithProvidersAtom. That atom reattaches the full config. LimitPresentations.providers is 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:

  • useSidebarLookups rebuilt each environment's provider entry map from config.providers, so every memoized row got a new providerEntryByInstanceId.
  • useSupportsMultiplePullRequests (in each row, its tooltip and useLinkedThreadPullRequest) subscribed to the whole map to read one capability.

Fix:

  • environmentPresentations.serverConfigsAtom is the enabled environments' EnvironmentServerConfig (no providers) built from the presentations, so it keeps its identity across provider pushes. Web useServerConfigs() now returns it. That covers every web capability reader (sidebar, PR rows and panels, CommandOutputPanel, RightPanelTabs, ...). The one reader that needs providers, ThreadRelationshipsPanel, now uses useEnvironmentProviders(). environmentServerConfigsAtom itself is unchanged, so mobile is unaffected.
  • sidebarProviderEntriesAtom derives 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 by reuseUnchanged when 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).
  • primaryServerConfigAtom consumers (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

    2. juliusmarminge added labelsmacroscope-review

    3. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      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).
    4. github-actions[bot](GitHub profile, opens in a new tab)commented

      Thread transfer impact

      ✅ Thread transfer remains within every enforced ceiling.

      ProviderMetricMain baselineThis PRImpactPR ceiling
      CodexTotal thread wire5.0 KiB4.9 KiB−23 B (−0.5%)6.8 KiB✅
      CodexThread snapshot wire3.8 KiB3.8 KiB0 B (0.0%)4.9 KiB✅
      CodexLive turn WebSocket wire1.2 KiB1.2 KiB−23 B (−1.9%)2.0 KiB✅
      CodexLive turn WebSocket decoded20.9 KiB20.8 KiB−41 B (−0.2%)29.3 KiB✅
      CodexLive turn messages21−1 (−50.0%)8✅
      ClaudeTotal thread wire5.0 KiB5.0 KiB+24 B (+0.5%)6.8 KiB✅
      ClaudeThread snapshot wire3.8 KiB3.8 KiB0 B (0.0%)4.9 KiB✅
      ClaudeLive turn WebSocket wire1.2 KiB1.2 KiB+24 B (+2.0%)2.0 KiB✅
      ClaudeLive turn WebSocket decoded21.2 KiB21.2 KiB+41 B (+0.2%)29.3 KiB✅
      ClaudeLive turn messages12+1 (+100.0%)8✅

      Baseline: edb2155 · PR result: cc8b47f · Source CI: success

      Scenario 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.

    5. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      Review in Change Stack →

      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.tsx
      • apps/web/src/components/CommandPalette.tsx
      • apps/web/src/components/chat/ThreadRelationshipsControl.agents.test.tsx
      • apps/web/src/components/chat/ThreadRelationshipsControl.tsx
      • apps/web/src/components/usage/UsagePage.tsx
      • apps/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.ts
      Base 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.tsx
      Web 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.tsx
      Settings 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.ts
      Usage 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: Passed 3 · Failed 1
      Failed Failed checks: 1 warning
      Check nameStatusExplanationResolution
      Description checkWarningThe 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 Passed checks: 3 passed
      Check nameStatusExplanation
      Title checkPassedThe title clearly and concisely describes the main performance change: provider-status pushes no longer re-render environment presentation consumers.
      Linked Issues checkPassedCheck skipped because no linked issues were found for this pull request.
      Out of Scope Changes checkPassedCheck 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
      Comment `@coderabbitai help` to get the list of available commands.
    6. 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 providerStatuses pushes per window. Server runs without --watch and there were no reconnects. Numbers are renders in the commit that follows each push (median push).

      scenariomainthis PR
      Settings > General, renders per push370106
      Settings > General, 15s window (4 pushes)1470414
      thread view, renders per push400390

      Settings: a 71% drop. On main, each push re-rendered RootRouteView, 40 SettingsRows 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, FirstRunGate and GeneralSettingsPanel look like primaryServerConfigAtom readers (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>, the AssistantTimelineRow / UserTimelineRow / MessageMeta / ForkButton / RevertUserMessageButton ×5-6 rows, and the sidebar rows (SidebarThreadRow#31, SidebarThreadTooltip). That comes through a context that ChatView provides 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.

    7. 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 in ChatView.tsx with #20854. So I measured the PR head 9946bf7a4f against its merge-base 130f4a2457, 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 4 providerStatuses pushes. "Per push" counts the renders in the commits within 300 ms of each push.

      scenariomain 2fae0f98merge-base 130f4a24this PR
      Settings > General, renders per push370372105
      Settings > General, 15 s window14701492424
      thread view, renders per push311323146
      thread view, 15 s window12401294580
      2 environments: env2 offline 12 s then back, thread in env1, whole window1938 (1926 / 1938 / 2877)2031 (2031 / 2031 / 2673)1207 (1207 / 1207 / 1495)
      ↳ ChatView renders in that window15157
      ↳ EnvironmentPermissionNotice renders313115

      (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, RootRouteView and the settings nav no longer render. What's left (~105) starts at DocumentTitleSync, ChatGptWelcomeCoordinator, FirstRunGate#25, EventRouter, ProviderUpdatePrimaryNotification, CommandPalette, SidebarUpdateControl, GeneralSettingsPanel and ProjectDefaultsSettings, 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#34 x8, SidebarThreadTooltip x8, about 38 TooltipTrigger). They now don't render at all. The 146 that's left is the same set of root coordinators plus Sidebar#24, SidebarProviderUpdatePill and 8 SortableThreadRow (which bail out below).

      Two environments: halved. ChatView now renders 7 times instead of 15 while env2 drops and comes back. The remaining cost is the sidebar (SortableThreadRow parent-same-props<-SortableContext, ~112 TooltipTrigger), with 24 SidebarThreadRow renders 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's timelineProviders change). It needs a rebase before it can land.

      Screenshot (PR, thread view after the pushes): /home/julius/.cache/audit/remeasure/20821-after.png

    8. juliusmarminge merged this4a5dade

    9. juliusmarminge closed this

Sign in to join this conversation.