perf(web): turn-fold rows scan only their own entries #26688
main fromrefs/pull/26688/head·opened View on GitHubProblem#
deriveMessagesTimelineRows re-runs on every structural timeline change (each tool or command item update in a live turn, each new item). For every turn-fold row it built deferredWorkItemIds by scanning all timeline entries and checking membership in the fold's id set, so the cost was O(folds × entries). On a 600-turn thread (5,400 entries) one derive took ~90 ms, about 90% of it in that scan.
Fix#
TurnFold now carries its segment's entries (already in timeline order: deriveTurnFolds pushes them during a forward scan and segments are contiguous slices) instead of an entryIds set. The turn-fold row walks only its own entries, and collapsedFoldMemberIds reads ids from the same array. Output is unchanged, including order.
Measurements#
Harness: the real deriveTimelineEntriesFromVisibleTurnItems and deriveMessagesTimelineRows, bundled with esbuild and run in plain Node 24.18 (Apple Silicon). Synthetic thread: N turns, each with 1 user message, 7 items (command, read_file dynamic tool, intermediate assistant message), and a final assistant message. Old and new builds ran interleaved, 5 process runs each. Each run: warmup, then 30 timed calls (per-run median), plus allocation from the heapUsed delta around one call, after gc() with --max-semi-space-size=1024, counting only samples with no GC. The table shows the median across runs.
| Thread | Before | After | Alloc before | Alloc after |
|---|---|---|---|---|
| 100 turns (900 entries) | 3.64 ms | 0.90 ms | 5.4 MB | 2.2 MB |
| 600 turns (5,400 entries) | 91.1 ms | 5.2 ms | 46.5 MB | 11.8 MB |
| 600 turns, live last turn | 89.9 ms | 4.8 ms | 46.5 MB | 11.3 MB |
| 1,200 turns (10,800 entries) | 369 ms | 13.3 ms | 36.6 MB | 22.8 MB |
What limits the new number: the remaining linear passes in the derive (fold derivation, row building, attachTrailingToolGroupsToAssistant). It now scales linearly with entries.
Benchmark harness
// timeline-fixture.ts: makeLongThread(turns, tools) builds OrchestrationV2ProjectedTurnItem[]
// (user_message, command_execution / dynamic_tool / assistant_message x7, final assistant_message per turn)
import { deriveTimelineEntriesFromVisibleTurnItems } from "~/session-logic";
import * as NEW from "~/components/chat/MessagesTimeline.logic";
import * as OLD from "~/components/chat/__orig_MessagesTimeline.logic"; // copy of main
const { visibleTurnItems, lastRunId } = makeLongThread(turns, 7, { liveLast: live });
const entries = deriveTimelineEntriesFromVisibleTurnItems({ visibleTurnItems, optimisticMessages: [] });
const input = { timelineEntries: entries, isWorking: live,
latestRun: live ? { runId: lastRunId, status: "running", startedAt: "...", completedAt: null, turnEnded: false } : null,
turnDiffSummaries: [], supportsConversationRollback: true, threadStartCheckpointReady: true };
const impl = process.env.IMPL === "old" ? OLD : NEW;
measure("deriveMessagesTimelineRows", () => impl.deriveMessagesTimelineRows(input));
// measure(): 10 warmup calls, 30 timed calls with performance.now() (median),
// then 5x { gc(); h0 = heapUsed; fn(); h1 = heapUsed } keeping samples with no GC event.
// Bundled: esbuild --bundle --platform=node --alias:~=./src; run: node --expose-gc --max-semi-space-size=1024
Validation#
vp run check:changed: format, lint, knip, typecheck, and tests pass.MessagesTimeline.logic.test.tsandMessagesTimeline.active-tools.test.ts: 91 tests pass. They already coverdeferredWorkItemIds.- Differential fuzz (not committed): old and new
deriveMessagesTimelineRowsandtimelineTurnFoldRunIdsByEntryId, compared as JSON on 9,000 random timelines. The inputs mixed steers, superseded attempts, runless turns, deferred-work items, compaction, interrupts, live and settled runs, and expanded runs and groups. Zero differences across about 38k turn folds, about 17k of them with deferred ids.
Not checked: the old code could also pick up an entry outside the segment that shares an id with a segment entry. Timeline entry ids are unique item and message ids, and rows are keyed by them elsewhere, so this path never occurs. I did not profile in a real browser; the numbers above come from Node.
Authored with Claude Opus 5.5 via the Claude Code harness in T3 Code.
🤖 Generated with Claude Code
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:S
Approvability#
Verdict: Approved at
bd47bd7Macroscope's review found this PR approvable — Turn-fold rows now scan only their own ordered entries instead of the full chat timeline. This is a localized presentation-performance optimization with existing folding rules unchanged and no evident material risk.
You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).No actionable comments were generated in the recent review.
Recent review info-
Run configuration-
- Source mode: Auto
- Repository: pingdotgg/t3code
- Branch: main
- File: .coderabbit.config.ts
- Commit: 9826dbb
- Layers: Repository TS config
- Review profile: CHILL
- Plan: Advanced
- Run ID:
d66edeaa-a5d1-4ead-9131-c70239c6e356
Commits-
Reviewing files that changed from the base of the PR and between 9826dbb9904b2591bfbf60d1317486b59132f56b and bd47bd75808f95ccdece44954e7328d7dcc29531.
Files selected for processing: 1-
apps/web/src/components/chat/MessagesTimeline.logic.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
-
Turn fold segments now retain their ordered
TimelineEntryobjects. Collapsed-fold membership and deferred work-item collection use those entries directly.Changes: Turn fold entry storage and consumers
Priority:Layer / File(s) Summary Store and consume turn fold entries
apps/web/src/components/chat/MessagesTimeline.logic.tsTurn fold segments store their entries directly. Collapsed-fold member IDs and deferred work-item IDs are derived from those entries. Existing hidden-entry, work-item, and superseded-item handling remains. LowEstimated code review effort: 2 (Simple) | ~10 minutes
Change: Refactor
Possibly related issues
- pingdotgg/t3code#24120: This change reduces turn-fold work during timeline derivation, but does not add a text-only fast path or reduce how often derivation runs.
Possibly related PRs
- pingdotgg/t3code#26240: This PR adds deferred-work IDs to turn-fold rows; the current change uses stored fold entries to collect those IDs.
- pingdotgg/t3code#26255: This PR keeps pending approval entries outside collapsed folds; the current change updates the fold membership representation.
- pingdotgg/t3code#24692: This PR introduces response-group and steer-segment turn folds, which the current change continues to use.
Suggested reviewers:
t3dotgg,yash-singh1
Merge Risk:
Minimal · up tobd47b-
No actionable merge-blocking risk is established for this optimization.
Pre-merge checks:
4-
Check name Status Explanation Title check The title clearly and concisely describes the primary performance change: turn-fold rows scan only their own entries. Description check The description clearly documents the problem, implementation, performance measurements, validation results, limitations, and tooling used. It does not include the template's explicit Scope and approv… 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 clearly documents the problem, implementation, performance measurements, validation results, limitations, and tooling used. It does not include the template's explicit Scope and approval section or issue/approval reference, but the focused fix and rationale are sufficiently explained.
-
Finishing Touches
-
🧪 Generate unit tests (beta)
-
- Create a new PR
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
-
@juliusmarminge ready for review. Turn-fold row derivation no longer rescans every timeline entry per fold: 5.4k entries 91 ms to 5.2 ms, 46.5 MB to 11.8 MB; 10.8k entries 369 ms to 13.3 ms. Output is identical on 9,000 random timelines. Related to #26018. CI workflows on this fork PR show
action_required, so they are waiting on a maintainer to approve the run. CodeRabbit and Macroscope are done with no open findings.Closing as superseded by #26727, which landed the same optimisation on main (the turn-fold lookup now walks only the fold's own entry ids via an id map instead of rescanning every timeline entry). Rebasing would only duplicate it.
hieu-lee(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) approved these changes