Skip to content
Source
Sign inSign up
pingdotgg/t3code

perf(web): markdown replies no longer re-render on reconnects and config pushes #20852

Mergedjuliusmarmingemerged 1 commit intomain fromrefs/pull/20852/headmerged by juliusmarminge View on GitHub

juliusmarmingecommented

Problem

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:

  • useRemoteOpenResolution subscribed to the whole environment presentation (entry, connection, serverConfig). It returned a new { state, isResolved } object on each push. That object keyed canUseShellActions, then fileLinkChip, and through it the renderer context.
  • usePreparedConnection returned a new Option after each reconnect. That keyed openMarkdownMedia, openMarkdownFileInPreview and fileLinkChip.
  • usePullRequestLinking subscribed to the whole server config map (useServerConfigs) when all it needs is the link mode. Its result keyed resolveThreadPullRequest, linkedThreadPullRequestFor and updateThreadPullRequestLink.

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: remoteOpenResolutionAtom is 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. useRemoteOpenResolution subscribes to that atom. This also helps ChatView, OpenInPicker and FilePreviewPanel, which use useRemoteOpenState.
  • Prepared connection: ChatMarkdown no longer subscribes to it. Opening media or a file preview is an event, so both handlers call readPreparedConnection(environmentId) when clicked.
  • usePullRequestLinking: subscribes to linkModeAtom(environmentId), an atom holding the mode string ("multiple" | "single" | "unsupported"), which Object.is compares by value. changeLink reads capabilities from the registry when it runs.
  • Server config fields: the existing useState adjust-during-render compare is replaced by markdownServerConfigFieldsAtom. It keeps its previous object while pullRequestsEnabled, revealInFileManagerLabel and the availableEditors contents are equal. The old check compared availableEditors by 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. preparedConnection is 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] !== environmentId and returns the same object while the fields are equal.
  • canUseShellActions: $[16] !== canOperateHost || $[17] !== environmentId || $[18] !== remoteOpen. remoteOpen now keeps its identity because the atom returns previous.
  • usePullRequestLinking: every handler is keyed on mode, a string, plus environmentProjects, environmentId and 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 pullRequests capability or of the reveal label, or a grant change (useEnvironmentScope still subscribes to the session state).
  • useProjects and useClientSettings subscriptions are unchanged. A project list change still re-renders every reply. Projects aren't pushed during a reconnect when they're unchanged (projectsAtom keeps its array).
  • SkillInlineText props:skills (248 in the audit) comes from ChatView's timelineSkills, 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

    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted

    3. 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).
    4. 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: 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.tsx
      • apps/web/src/components/ChatMarkdown.permissions.test.tsx
      • apps/web/src/components/ChatMarkdown.test.tsx
      • apps/web/src/components/ChatMarkdown.tsx
      • apps/web/src/hooks/usePullRequestLinking.ts
      • apps/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.tsx
      ChatMarkdown 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 AtomRegistry and provide server-state atoms.

      Pull-request linking

      Layer / File(s)Summary
      Environment link mode and mutation planning
      apps/web/src/hooks/usePullRequestLinking.ts
      The hook derives link mode from an environment-keyed atom family. Mutation planning reads capabilities from appAtomRegistry for the thread’s environment.

      Remote-open resolution

      Layer / File(s)Summary
      Environment-specific resolution
      apps/web/src/remoteOpen.ts
      An 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: Passed 4
      Check nameStatusExplanation
      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.
      Title checkPassedThe title clearly and concisely identifies the main performance change: preventing unnecessary markdown re-renders during reconnects and configuration pushes.
      Description checkPassedThe 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
      Comment `@coderabbitai help` to get the list of available commands.
    5. 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 for welcome, 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).

      scenariomainthis PR
      prose/links thread (Evaluate Markdown Renderer), idle across a reconnect: commits / renders52 / 542952 / 4824
      ↳ timeline renders1224647
      ↳ ChatMarkdown / MarkdownParagraph / SkillInlineText104 / 66 / 12049 / 24 / 42
      list-heavy thread (a 200-line numbered reply), idle across a reconnect: commits / renders45 / 1271247 / 4873
      ↳ MarkdownListItem / SkillInlineText4320 / 4356360 / 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 the ChatMarkdown that receives it rebuilds its context. That's also where the 360 MarkdownListItem context renders come from. #20855 fixes this at the source, and with both PRs it should mostly go away.
      • ChatMarkdown state#12 and state#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 #16979 opens the preview card ("pingdotgg/t3code #16979 · Merged · feat(mobile): replace custom Markdown rendering with Enriched"). External links and inline code render as before.

    6. juliusmarminge merged this1d00edb

    7. juliusmarminge closed this

Sign in to join this conversation.