Skip to content
Source
Sign inSign up
pingdotgg/t3code

perf(web): the open thread's chat chrome no longer re-renders on every streaming tick #20860

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

juliusmarmingecommented

Problem

Render audit, thread view while its own thread streams with the composer idle: 1942 renders in 12s (40 commits). While a run streams, the server bumps the thread shell's updatedAt, runtime.updatedAt and item counts several times a second. threadShellAtom emits a new shell per tick, and every useThreadShell(ref) reader of the active thread re-rendered, though none of them show those fields. ChatView alone re-rendered on about 10 ticks in 14s, and each of those cascaded into 80 to 200 renders: ThreadDetailsPanel and its sections, BranchToolbar, ThreadDetailsControl, dialog and popover roots.

Fix

  • createEnvironmentThreadShellAtoms gains quietThreadShellAtom(ref). While the thread's run is active, it keeps the previous shell when the wire shell differs only in updatedAt, item counts (unless one crosses zero, which threadHasStarted reads) or latestVisibleMessage. The comparison uses the schema equivalence over the wire shell. Once the run stops, every field counts again, so snooze wakes, usage-limit stop times and the local-dispatch acknowledgement still see current values.
  • useQuietThreadShell in state/entities.ts. ChatView (route shell, active shell, parent-subagent shell), BranchToolbar, BranchToolbarBranchSelector, GitActionsControl, DiffPanel, ThreadRouteView, PersistentThreadTerminals, useThreadTerminalActions, useHandleNewThread (mounted in Sidebar, the chat-route shortcuts, CommandPalette and SnapShotCoordinator) and the favicon hook read it. None of them read updatedAt, source or raw item counts.
  • The visit-watermark effect is the only part of ChatView that follows updatedAt, so it moved into a ThreadVisitWatermark leaf that keeps the full shell. Its behaviour is unchanged: it still re-renders per tick and still throttles dispatch.

Compiled output (oxc-transform-react, same options as reactCompilerCoverage.test.ts) shows why consumers now bail out. BranchToolbar's derived values are cached on the shell's identity:

const serverThread = useQuietThreadShell(threadRef);
if ($[6] !== draftThread || $[7] !== serverThread) {
  t7 = serverThread ? scopeProjectRef(serverThread.environmentId, serverThread.projectId) : ...

With the quiet shell, serverThread keeps its identity across streaming ticks, useAtomValue does not schedule a render, and the cached slots hold. ChatView follows the same pattern.

What still renders per tick

  • ThreadVisitWatermark (a leaf that renders null).
  • The sidebar row for the thread, which reads the full shell list.
  • ChatView renders driven by the thread projection itself: streamed items, runs and the ChatView#499 double render tracked in the autoBalance banner finding.

Test: threadShell.test.ts covers that the quiet shell holds through streaming ticks, follows a title change mid-run, and follows every updatedAt change once the run stops.

After:

🤖 Generated with Claude Code

Update

Rebased onto main (including #20847, the autoBalance double render). The DiffPanel.tsx conflict kept main's useThreadRouteRef() and this PR's useQuietThreadShell.

The re-measure showed ThreadDetailsPanel and BranchToolbar still re-rendering on each tick with a new availableEnvironments. Two causes:

  • ChatView built logicalProjectEnvironments inline from environmentById, which is a new Map on every render, so the compiler rebuilt the list each time ChatView rendered. It now comes from useLogicalProjectEnvironments (hooks/useLogicalProjectEnvironments.ts), which reads only the environments, projects, primary environment id, and useClientSettings(selectProjectGroupingSettings). The compiled hook caches the list on activeProject, allProjects, environments, primaryEnvironmentId, projectGroupingSettings and scratchDraft, and a streaming tick changes none of them.
  • threadDetailsPanelProps was a plain object spread into ChatView's outer JSX, which is never cached, so the panel got a new element on every ChatView render, whatever its props were. The props are now written inline on <ThreadDetailsPanel>. The compiled output caches that element on its own inputs ($[1414] !== activeThread.environmentId || … || $[1424] !== logicalProjectEnvironments || …), and those inputs are now all atom values, primitives or stable callbacks.

What still makes ChatView render per tick: useThreadProjection and useThreadVisibleTurnItems (the streamed items themselves). They feed the timeline, run state and composer status, which do change each tick. Narrowing them means splitting the timeline out of ChatView, which belongs in its own PR. With this change those renders should stop at ChatView and the timeline, and no longer reach the panel and toolbar.

Tests: threadShell.test.ts, BranchToolbar.panel.test.tsx, BranchToolbar.logic.test.ts, React Compiler coverage for ChatView.tsx and the new hook. Lint and the apps/web typecheck are clean. After: needs a new in-app measurement.

    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 PR introduces shared quiet-shell state semantics and rewires many production thread consumers to retain data during active streaming, while moving visit tracking to a separate live-shell leaf. The cross-cutting runtime update behavior warrants human review despite targeted tests and a clear performance objective.

      No code changes detected at 33cc35e. Prior analysis still applies.

      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: 898419d8-47fa-4519-bad7-d73c37598cf8
      📥 Commits

      Reviewing files that changed from the base of the PR and between fb621e4c12e67ab39f87561e4e8e85933600ca96 and 9a063bfadf5af570f4288ad5978687625172ab4f.

      📒 Files selected for processing: 4
      • apps/web/src/components/ChatView.tsx
      • apps/web/src/components/DiffPanel.tsx
      • apps/web/src/hooks/useHandleNewThread.ts
      • apps/web/src/hooks/useLogicalProjectEnvironments.ts

      Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.

      📝 Walkthrough

      The client runtime adds quiet thread-shell atoms that retain references during qualifying streaming-only updates. Web components use them for thread reads. ChatView moves visit tracking into ThreadVisitWatermark and extracts environment selection into useLogicalProjectEnvironments.

      Changes: Quiet Thread Shells and ChatView Refactoring

      Layer / File(s)Summary
      Quiet shell atom and comparison
      packages/client-runtime/src/state/threadShell.ts, packages/client-runtime/src/state/threadShell.test.ts
      The runtime adds quiet-shell comparison and per-thread atoms. Tests cover active-run updates and post-completion timestamp updates.
      Web quiet-shell adoption
      apps/web/src/state/entities.ts, apps/web/src/browserFaviconStore*, apps/web/src/components/*, apps/web/src/hooks/useHandleNewThread.ts
      The web hook and thread-related components now use useQuietThreadShell. Test mocks expose the new hook.
      ChatView visit tracking and environment selection
      apps/web/src/components/ChatView.tsx, apps/web/src/hooks/useLogicalProjectEnvironments.ts
      ChatView renders ThreadVisitWatermark and delegates environment-option construction to useLogicalProjectEnvironments.

      Priority: ➖ Normal

      Estimated code review effort: 3 (Moderate) | ~20 minutes

      Change: Refactor

      Sequence Diagram(s)

      sequenceDiagram
        participant ThreadShellAtoms
        participant useQuietThreadShell
        participant ChatView
        ThreadShellAtoms->>useQuietThreadShell: provide quiet shell for thread reference
        useQuietThreadShell->>ChatView: return shell excluding qualifying streaming updates
        ChatView->>ChatView: render ThreadVisitWatermark and environment options

      Suggested reviewers: maria-rcks

      Merge Risk: ⚪ Minimal · up to 9a063

      The inspected diff and visit-tracking paths retain the updates they need. No issue identified here requires a fix before merge.

      Pre-merge checks: Passed 3 · Failed 1
      Failed Failed checks: 1 warning
      Check nameStatusExplanationResolution
      Description checkWarningThe description clearly explains the problem, implementation, remaining renders, measurements, and verification. It does not include the required Scope and approval section, UI before/after screenshot…Add a Scope and approval section with the linked issue or explicit maintainer approval, or explain why this focused fix qualifies for an exemption. Add before/after UI screenshots and identify the model and harness used with Claude Code.
      Passed Passed checks: 3 passed
      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 describes the main performance change: preventing open-thread chat chrome from re-rendering on every streaming tick.
      Full details: Description check

      Explanation

      The description clearly explains the problem, implementation, remaining renders, measurements, and verification. It does not include the required Scope and approval section, UI before/after screenshots, or the model and harness used for the agent-generated work.

      Resolution

      Add a Scope and approval section with the linked issue or explicit maintainer approval, or explain why this focused fix qualifies for an exemption. Add before/after UI screenshots and identify the model and harness used with Claude Code.

      • Fix all pre-merge checks with AI
      ✨ Finishing Touches: 💡 2
      ⚔️ Resolve merge conflicts: 💡
      • Resolve merge conflict in branch `fix/active-thread-shell-narrow`
      🛠️ Fix failing CI checks: 💡
      • Commit to this branch
      • Create a new PR
      📝 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):

      This PR conflicts with main (apps/web/src/components/DiffPanel.tsx), so it can't be cherry-picked onto current main. I measured the PR head (fb621e4c12) against its merge-base 2fbd4318fc instead. The server ran without --watch, and no window had a reconnect. In both cases the first run after a server restart streamed slowly (3 to 4 chunks instead of 10 to 12), so I dropped it and used runs 2 to 4.

      Scenario: send a long reply request in a Claude Haiku thread and keep that thread open, with the composer blurred. After 4 s of streaming, measure a 12 s window. Both sides saw 10 to 12 stream chunks per window.

      scenariobasethis PR
      stream 12 s in the open thread: commits / renders34 / 279128 / 2007
      renders outside the timeline (chrome, composer, sidebar)21171717
      ChatView / BranchToolbar / ThreadDetailsPanel renders19 / 24 / 1915 / 19 / 15

      The timeline total isn't comparable between the two (651 vs 187). It depends on whether the window caught a markdown list growing (200 MarkdownListItem renders), and that changes from run to run. I compared everything outside the timeline instead.

      What still renders:

      • The chat chrome still re-renders on most ticks. Each window had 11 ThreadDetailsPanel props:availableEnvironments and 11 BranchToolbar props:availableEnvironments renders, along with ThreadDetailsControl and ThreadDetailsSection. They follow ChatView, which still renders about once per tick: state#58 (6) and state#56 (4) come from the thread projection, and state#488 (4) is the useAutoBalanceUpdateBanner double render that #20847 removes. ChatView passes a new availableEnvironments each time, so the panel can't bail out. The PR removes the shell-driven ChatView renders (19 → 15), but the panel stays tied to ChatView. That's why the drop is about 19% and not the near-zero the title suggests.
      • The sidebar (~540): WorkingDuration ticks and the row for the streaming thread. Both are legitimate.

      Behaviour check: I renamed the thread mid-run ("Numbers mid-run rename"), and the breadcrumb and sidebar row updated while it streamed. Stop generation still works, and the "Working" state and timer clear when the run stops. After an interrupt the composer shows "Resume thread". The base does the same, so that comes from main and not from this PR.

      Needs a rebase onto main before it can land.

    6. Thread transfer impact

      ⚠️ The latest CI run did not produce a thread transfer result for 9a063bf.

      This comment will update automatically after the next completed run.

    7. Re-measured after the availableEnvironments fix (round 3). I used seeded data and took the median of 3 runs per side, after one warm-up run each.

      This PR still conflicts with main (apps/web/src/components/ChatView.tsx), so it can't be cherry-picked onto main 2fae0f9841. I measured the PR head 9a063bfadf against its merge-base 812b7006f8 instead. The server ran without --watch, and no window had a reconnect.

      Scenario: send a long reply request in a Claude Haiku thread and keep that thread open, with the composer blurred. After 4 s of streaming, measure a 12 s window. Base windows saw 7, 10 and 10 stream chunks; PR windows saw 13, 11 and 10.

      scenario (median)basethis PR
      commits / renders31 / 176632 / 1716
      renders outside the timeline1124 (113 per chunk)1085 (101 per chunk)
      ThreadDetailsPanel subtree382305
      ChatView / BranchToolbar / ThreadDetailsPanel renders10 / 14 / 1011 / 8 / 4

      What improved: the availableEnvironments fix works. On the base, ThreadDetailsPanel props:availableEnvironments and BranchToolbar props:availableEnvironments showed up 10 and 6 times per window. With the PR they don't show up at all. ThreadDetailsSection and ThreadDetailsCard re-renders fall from 20/10 to 8/4.

      What still renders: ChatView still re-renders about once per stream chunk (10 vs 11, or 1.0 per chunk on both sides). The causes are ChatView state#73 (6) and state#71 (4) from the thread projection. These are the same on base and PR, so the PR doesn't remove ChatView's per-tick render. Everything under ChatView that has no memo boundary still re-renders with it:

      • the composer: 280 → 307, with ChatComposer props:activeThread,activeThreadShell,promptHistoryMessages,queuedRunsControl
      • the root chrome: ~125 to 139 (ChatCanvas, ThreadFindProvider, ProviderStatusBanner, ThreadErrorBanner)
      • ThreadDetailsControl (20 per window): its onClick and handler props are new each time
      • BranchToolbar state#5 (8 per window), which is unchanged

      The sidebar (~330) is WorkingDuration plus the streaming row, which is expected. Overall, renders outside the timeline drop about 4% per window (about 11% per chunk), much less than the title suggests.

      Behaviour check: mid-stream, the right panel showed cups / master / Publish repository / Changes correctly. I opened the branch menu while the stream was running: it listed master (current) and stayed open across ticks. Stop generation worked, and the sidebar row went from Working to "now".

      20860-after.png

      Needs a rebase onto main before it can land.

    8. juliusmarminge merged this4b1024d

    9. juliusmarminge closed this

Sign in to join this conversation.