perf(web): markdown replies no longer re-render on reconnects and config pushes #20852
main fromrefs/pull/20852/head·merged by juliusmarminge View on GitHubProblem#
Render audit, lane 1, scenario: thread view idle for 20s across an environment reconnect or presentation push (welcome/ready, snapshot, usageLimitSourcesUpdated, environmentThemesUpdated). Result: 45 commits and 7554 renders. The top causes were 1000 MarkdownListItem context renders, 800 SkillInlineText renders under them, and 160 MarkdownParagraph context renders, all traced to ChatMarkdown#18 useSyncExternalStore {entry,connection,serverConfig}.
Every visible ChatMarkdown subscribed to three values that change on these pushes even when nothing markdown reads has changed:
useRemoteOpenResolutionsubscribed to the whole environment presentation (entry,connection,serverConfig). It returned a new{ state, isResolved }object on each push. That object keyedcanUseShellActions, thenfileLinkChip, and through it the renderer context.usePreparedConnectionreturned a newOptionafter each reconnect. That keyedopenMarkdownMedia,openMarkdownFileInPreviewandfileLinkChip.usePullRequestLinkingsubscribed to the whole server config map (useServerConfigs) when all it needs is the link mode. Its result keyedresolveThreadPullRequest,linkedThreadPullRequestForandupdateThreadPullRequestLink.
Each of these is a cache key of componentState, which is the ChatMarkdownRendererContext value. So every push re-rendered every heading, paragraph, list item, code span, anchor and image in every visible reply.
Fix#
remoteOpen.ts:remoteOpenResolutionAtomis an atom family per environment. It derives the resolution from the presentation and returns the previous value (get.self) while the mode and host are equal.useRemoteOpenResolutionsubscribes to that atom. This also helpsChatView,OpenInPickerandFilePreviewPanel, which useuseRemoteOpenState.- Prepared connection:
ChatMarkdownno longer subscribes to it. Opening media or a file preview is an event, so both handlers callreadPreparedConnection(environmentId)when clicked. usePullRequestLinking: subscribes tolinkModeAtom(environmentId), an atom holding the mode string ("multiple" | "single" | "unsupported"), whichObject.iscompares by value.changeLinkreads capabilities from the registry when it runs.- Server config fields: the existing
useStateadjust-during-render compare is replaced bymarkdownServerConfigFieldsAtom. It keeps its previous object whilepullRequestsEnabled,revealInFileManagerLabeland theavailableEditorscontents are equal. The old check comparedavailableEditorsby identity, so a snapshot carrying an identical editor list still re-rendered everything. Atom-side equality also means the markdown component doesn't render at all for those pushes.
No useMemo, useCallback, memo or "use memo" was added. This change stands on its own without #20821: a presentation object with a new identity now stops at the derived atoms.
Proof from compiled output#
From oxc-transform-react with reactCompiler: { reportDiagnostics: true }, the same call reactCompilerCoverage.test.ts makes. All three files compile with 0 bailouts.
useChatMarkdownState before → after:
openMarkdownMedia:$[20] !== createAssetUrl || … || $[23] !== preparedConnection || $[24] !== threadRef→$[20] !== createAssetUrl || $[21] !== cwd || $[22] !== environmentId || $[23] !== expandMedia || $[24] !== threadRef.preparedConnectionis no longer a key.openMarkdownFileInPreview:… $[62] !== preparedConnection || $[63] !== threadRef→$[56] !== canOperatePreview || $[57] !== createAssetUrl || $[58] !== cwd || $[59] !== openPreview || $[60] !== threadRef.- Config fields: the block keyed on
$[28] !== serverConfig(the whole config object) is gone.useAtomValue(markdownServerConfigFieldsAtom(environmentId))is cached on$[26] !== environmentIdand returns the same object while the fields are equal. canUseShellActions:$[16] !== canOperateHost || $[17] !== environmentId || $[18] !== remoteOpen.remoteOpennow keeps its identity because the atom returnsprevious.usePullRequestLinking: every handler is keyed onmode, a string, plusenvironmentProjects,environmentIdand the command runners. Nothing in it is keyed on a config object.
With every input to the componentState block ($[88] … $[118]) stable across a push, componentState keeps its identity and the context consumers don't re-render. In practice ChatMarkdown itself doesn't render for these pushes, because none of its subscriptions emits a new value.
Tests: the three ChatMarkdown unit test files used to mock useAtomValue to return a fixed value. They now evaluate the new derived atoms in a real AtomRegistry over a mocked config atom, so they exercise the real derivation. I didn't add a browser test: the guarded behaviour is "returns the previous object when equal", which the compiled-key proof above covers, and the orchestrator re-measures it in the app.
What still renders#
- A change markdown actually reads re-renders the replies: a real change of remote-open mode or host, of the PR link mode, of the editors list, of
pullRequestscapability or of the reveal label, or a grant change (useEnvironmentScopestill subscribes to the session state). useProjectsanduseClientSettingssubscriptions are unchanged. A project list change still re-renders every reply. Projects aren't pushed during a reconnect when they're unchanged (projectsAtomkeeps its array).SkillInlineText props:skills(248 in the audit) comes fromChatView'stimelineSkills, derived from the provider status. That's a ChatView/provider identity issue and is out of scope here. #20821 covers the presentation side.SortableTab/ right-panel tab churn on the same pushes is a separate root cause and isn't touched here.
After:
Opus 5.5 in Claude Code.
🤖 Generated with Claude Code
- 1
juliusmarminge added labelsmacroscope-review
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
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:
beb18147-a305-4945-a5fa-bd401e5b40f2
📥 Commits
-
Reviewing files that changed from the base of the PR and between 2fbd4318fc5b610c3e7fcfcbd5bbd80b73521d8f and 6b474b7ed8361cca448bf988be2aa85f8e84220c.
📒 Files selected for processing: 6
-
apps/web/src/components/ChatMarkdown.assets.test.tsxapps/web/src/components/ChatMarkdown.permissions.test.tsxapps/web/src/components/ChatMarkdown.test.tsxapps/web/src/components/ChatMarkdown.tsxapps/web/src/hooks/usePullRequestLinking.tsapps/web/src/remoteOpen.ts
Limit details: You’ve used all 10 included reviews currently available.
-
📝 Walkthrough
-
ChatMarkdown, pull-request linking, and remote-open resolution now use atom-backed state reads. ChatMarkdown reads prepared connections when preview actions occur. Test mocks were updated to support the atom-based reads.
Changes: ChatMarkdown
Layer / File(s) Summary Markdown configuration and preview reads
apps/web/src/components/ChatMarkdown.tsx,apps/web/src/components/ChatMarkdown.*.test.tsxChatMarkdown derives selected server-config fields through atoms and reads prepared connections when media or file previews open. The test mocks now read named atoms through an AtomRegistryand provide server-state atoms.Pull-request linking
Layer / File(s) Summary Environment link mode and mutation planning
apps/web/src/hooks/usePullRequestLinking.tsThe hook derives link mode from an environment-keyed atom family. Mutation planning reads capabilities from appAtomRegistryfor the thread’s environment.Remote-open resolution
Layer / File(s) Summary Environment-specific resolution
apps/web/src/remoteOpen.tsAn environment-keyed Effect atom derives remote-open resolution and reuses the prior result when the resolved state is equal. The hook uses an unresolved atom when the environment ID is null. Priority: ⬇️ Low
Estimated code review effort: 3 (Moderate) | ~20 minutes
Change: Bug fix
Suggested reviewers:
maria-rcks,yash-singh1
Merge Risk: ⚪ Minimal · up to
6b474-
This change reduces unnecessary markdown re-renders on reconnects and config pushes. No concrete merge-blocking risk was identified. The render-count improvement is not yet measured, which does not affect correctness.
Pre-merge checks:
4-
Check name Status Explanation 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. Title check The title clearly and concisely identifies the main performance change: preventing unnecessary markdown re-renders during reconnects and configuration pushes. Description check The description is detailed and relevant. It clearly explains the problem, implementation, affected behavior, verification approach, and out-of-scope items. It does not provide a scope or approval ref… Full details: Description check
-
Explanation
The description is detailed and relevant. It clearly explains the problem, implementation, affected behavior, verification approach, and out-of-scope items. It does not provide a scope or approval reference, and the post-change render measurement remains pending, but the overall description is mostly complete.
-
✨ 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):
Measured against main at 489d08a054, with this PR's commit cherry-picked onto that same commit (it applies cleanly). The server ran without
--watch. Every window deliberately includes one reconnect: I restarted only my own server process group 2 s into the window, waited forwelcome, and settled for 10 s. I counted only windows where the reconnect actually happened and the page didn't reload. Both sides saw the same frames (2 welcome/ready, 6 snapshots, usage-limit, themes, remoteUpdated).scenario main this PR prose/links thread (Evaluate Markdown Renderer), idle across a reconnect: commits / renders 52 / 5429 52 / 4824 ↳ timeline renders 1224 647 ↳ ChatMarkdown/MarkdownParagraph/SkillInlineText104 / 66 / 120 49 / 24 / 42 list-heavy thread (a 200-line numbered reply), idle across a reconnect: commits / renders 45 / 12712 47 / 4873 ↳ MarkdownListItem/SkillInlineText4320 / 4356 360 / 370 ChatMarkdown#18 useSyncExternalStore(the presentation/prepared-connection/server-config subscription) is gone from both threads. On the list-heavy thread, a reconnect goes from 12.7k renders to 4.9k.What still renders:
SkillInlineText props:skills(20 on the prose thread, 244 on the list thread). Each reconnect snapshot gives the skills array a new identity, so theChatMarkdownthat receives it rebuilds its context. That's also where the 360MarkdownListItem contextrenders come from. #20855 fixes this at the source, and with both PRs it should mostly go away.ChatMarkdown state#12andstate#8: 12 to 32 per window. These are small per-message state changes after the snapshot, and they don't fan out.- Outside the timeline (~4000): the sidebar, composer, ChatView and the details panel all re-render on the reconnect frames. That's out of scope here (#20821 and others).
Behaviour check (after a reconnect on this PR): PR links still render with their GitHub icon. Hovering
#16979opens the preview card ("pingdotgg/t3code #16979 · Merged · feat(mobile): replace custom Markdown rendering with Enriched"). External links and inline code render as before.juliusmarminge merged this1d00edb
juliusmarminge closed this
Sign in to join this conversation.
Approvability#
Verdict: Needs Human Approval
Macroscope's review found this PR requires human approval — This PR changes existing production subscription and rendering behavior across markdown replies and other remote-open and pull-request-linking surfaces. The new atom-based caching and event-time reads are reasonably scoped but sufficiently non-trivial and cross-component to merit human review.
You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).