Skip to content

perf(ui): reuse normalization and tool turns while loading older history - #160215

Merged
steipete merged 8 commits into
mainfrom
steipete/incremental-paging
Sep 28, 2026
Merged

steipete merged 8 commits into
mainfrom
steipete/incremental-paging

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: every time an older page of history loads in a long chat, the chat item builder re-normalizes every loaded message and re-coalesces every tool turn, so page-load stalls grow with the history already loaded.

User Impact

User impact: scrolling up through long chats stalls less on each older-history page, especially deep into the history. Order, grouping, live output, and presentation are unchanged.

Why This Change Was Made

After #160030, profiling history paging on a real 6,972-message session showed buildChatItems at ~110 ms per page once ~6k messages were loaded. Of that, ~31 ms was normalizing every message again and ~46 ms was coalescing every tool turn again. Already-loaded message objects keep their identity across page loads (verified with instrumentation), so both results can be reused at their owners:

  • Normalization (message-normalizer.ts): normalizeMessage caches its result per original message object when the message has a finite timestamp. Messages without one still take the current-clock fallback on every call. An audit (file:line evidence in the review record) found no settings, locale, or other outside inputs, and no consumer that mutates normalized output. Tests freeze cached results to prove that.
  • Tool-turn coalescing (chat-tool-activity-coalesce.ts): each message-only turn's output is memoized in one long-lived WeakMap keyed by the turn's first message. Reuse requires identical ordered inputs: kind, key, message, content array and blocks, duplicateCount, and startsTurn. Turns with live tool streams, streams, notices, or other transient wrappers are never cached. Hits and misses both return fresh shallow wrapper copies, so grouping and duplicate annotations cannot write into the cache. Split panes and other transcript surfaces share the map without evicting each other's entries, which die with their messages.

A prepended page recomputes only its own turns and the seam turn. The builder's global passes (placement, canvas, search, live items, grouping) still run over the whole history, but their per-message work is now mostly cache hits.

Test fixtures in chat-thread-grouping.test.ts and chat-thread.test.ts that mutated already-admitted message objects in place now publish replacement messages instead, matching how the application's owners update messages (history merge, session projection, tool stream). All their original assertions are unchanged.

Evidence

Real 6,972-message session through the mocked Gateway with production paging, bundled Control UI, Chromium 1280×900, scrolling up until all history was loaded. Main (1fe560c198c2) and this branch were built alternately (main, branch, branch, main, main, branch), 3 runs per build, with a fresh bundle for every invocation.

History paging, 1× CPU main this PR
Per-page long tasks, request → first frame after response (median, 63 pages/side) 135.6 ms 118.4 ms (−12.7%, p = 0.002)
Late pages, ≥4k messages loaded (median, 27 pages/side) 136.6 ms 117.8 ms (−13.8%, p < 0.001)
Long tasks per paging run (median, 9 runs/side) 1,236 ms 1,098 ms (−11.2%, lower in all 81 cross-pairs)
fps (median) 43.4 44.8 (p = 0.03)

Tests:

  • chat-thread-incremental.test.ts (new): a mixed fixture (tools, canvas, compaction, duplicates, live streams, reading indicator, queued-input placement, search with tools shown and hidden). Warm builds with the caches equal cold builds from cloned inputs, before and after a prepend. Cached normalized output is recursively frozen.
  • chat-tool-activity-coalesce.test.ts: repeated turns do no extraction work; a prepend recomputes only incoming and seam turns; replacing a message or block invalidates only its turn; mutating a returned wrapper cannot poison the cache; interleaved builds of two transcripts both keep their hits. Fails on main.
  • message-normalizer.test.ts: retained messages normalize once; replacements re-normalize; clock-fallback timestamps still advance under a fake clock. Fails on main.
  • Test cost with node scripts/run-vitest.mjs run <file> --maxWorkers=1: chat-thread-incremental.test.ts 4.0 s warm / 14.8 s cold wall (4 tests, ~28 ms of test time), chat-tool-activity-coalesce.test.ts 4.2 s (8 tests), message-normalizer.test.ts 2.1 s (80 tests). No real timers or sleeps.
  • 58 related test files (1,075 tests) passed: chat thread, grouping, tool activity, tool cards, normalizer, history, snapshot, canvas, and live streams. Also pnpm tsgo:ui, oxfmt, and git diff --check. An independent Codex review of the full branch was scoped-clean.

Production lines: +52 / −4. The growth is the two identity-keyed caches, finite-timestamp admission, and the explicit turn-input list. The inputs are listed out on purpose, because an omitted input is how a cache like this goes stale.

Memoize finite-timestamp normalization by immutable message identity and
reuse unchanged message-only turns across older-page prepends. Copy output
wrappers so duplicate and grouping annotations cannot poison cached turns;
keep transient turns and time-dependent normalization on the existing path.

Align grouping fixtures with replacement-based message ownership. Prove
normalization counts, seam-only coalescing, frozen-output safety, and mixed
cold/warm build equivalence before and after prepends.

Control UI release-note context: reduce repeated work while loading older
chat history without changing message order, grouping, or live presentation.

Validation: 1075 tests across 58 files; UI typecheck, formatter, whitespace;
Codex review through P2 clean. Lite paging sanity: three complete runs.
Keep one latest coalesced turn per owner message in a long-lived WeakMap.
Alternating split panes and other transcript builds no longer evict each
other's cached work; changed inputs replace only their owner's entry.

Replace the empty-pass eviction assertion with extraction-count coverage
for interleaved transcripts, empty builds, and same-owner replacement.

Control UI release-note context: preserve history paging cache reuse while
multiple chat panes or transcript surfaces render.

Validation: 391 tests across 13 files, UI typecheck, formatter, whitespace,
and full-branch Codex review through P2.
@clawsweeper

clawsweeper Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@steipete
steipete marked this pull request as ready for review September 28, 2026 06:41
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 28, 2026
@clawsweeper

clawsweeper Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 28, 2026, 1:54 PM ET / 17:54 UTC (Revision 4).

ClawSweeper review

What this changes

The Control UI reuses normalized messages and unchanged tool turns while loading older chat history, with tests for replacement, grouping, and cold-versus-warm output.

Merge readiness

✅ Ready for maintainer review

Keep this PR open. Current main still repeats message normalization and tool-turn coalescing during history rebuilds; the earlier merged paging optimization addressed a different parsing cost. The branch has focused coverage and measured browser-paging evidence, with no concrete correctness finding.

Priority: P2
Reviewed head: d2d7014f4a394f0558af34b36c55e601d6bebc35

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Measured browser paging, focused invalidation coverage, and a bounded implementation provide strong review confidence.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The changed normalization and coalescing owners are exercised by bundled Control UI history paging in Chromium with a mocked Gateway and a 6,972-message session; the PR reports improved late-page long tasks in alternating main/branch runs. The integration test supplements that observation with cold-versus-warm output checks. No stored-data contract changes.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The changed normalization and coalescing owners are exercised by bundled Control UI history paging in Chromium with a mocked Gateway and a 6,972-message session; the PR reports improved late-page long tasks in alternating main/branch runs. The integration test supplements that observation with cold-versus-warm output checks. No stored-data contract changes.
Evidence reviewed 7 items Introduced cache behavior: The pinned introduced diff adds a finite-timestamp message cache and an ordered-input tool-turn cache; transient turns bypass the latter and cached item wrappers are copied before grouping.
Current-main gap: Current main's tool-turn path calls coalescing for each turn on every build and has no turn reuse map. Its normalizer likewise has no normalized-message cache.
History owner boundary: History hydration reconciles incoming pages with previous messages before publishing the displayed transcript, supporting reuse of retained message identities.
Findings None None.
Security None None.

How this fits together

The Control UI receives chat-history pages from the Gateway and turns them into ordered message, tool, and live-status rows. Normalization and tool-turn coalescing run before the chat view groups and renders those rows.

flowchart LR
  A[Gateway history pages] --> B[Reconciled messages]
  B --> C[Normalization reuse check]
  C --> D[Normalized messages]
  D --> E[Tool-turn reuse check]
  E --> F[Grouped chat rows]
  F --> G[Chat view]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +51, Tests +381. Total +432 across 9 files.

View PR surface stats
Area Files Added Removed Net
Source 3 55 4 +51
Tests 6 405 24 +381
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 9 460 28 +432

Review metrics

Metric Value Why it matters
Late-page long tasks 136.6 ms to 117.8 ms median, a 13.8% reduction The reported browser measurement covers paging deep into a 6,972-message session.
Production and test growth production +55/-4 lines; tests +405/-24 lines Production growth implements the two reuse checks; most added lines cover cache invalidation and output equivalence.

Technical review

Best possible solution:

Keep identity reuse in the normalization and coalescing owners, with message replacement as the invalidation contract and cold-versus-warm transcript coverage at the chat-build boundary.

Do we have a high-confidence way to reproduce the issue?

Yes. The PR documents a concrete Chromium paging scenario with a 6,972-message session, and current-main source shows the repeated work; this read-only review did not execute that scenario.

Is this the best way to solve the issue?

Yes. The caches sit at the existing preparation owners, while ordered-input checks, transient bypass, and replacement-based tests address the relevant invalidation paths.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 01747d9b2b11.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a measured improvement to long-chat history paging with limited blast radius.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The changed normalization and coalescing owners are exercised by bundled Control UI history paging in Chromium with a mocked Gateway and a 6,972-message session; the PR reports improved late-page long tasks in alternating main/branch runs. The integration test supplements that observation with cold-versus-warm output checks. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The changed normalization and coalescing owners are exercised by bundled Control UI history paging in Chromium with a mocked Gateway and a 6,972-message session; the PR reports improved late-page long tasks in alternating main/branch runs. The integration test supplements that observation with cold-versus-warm output checks. No stored-data contract changes.

Evidence

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • RoboClaw: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (3 earlier review cycles)
  • reviewed 2026-09-28T06:49:08.665Z sha 0b1d85b :: needs maintainer review before merge. :: none
  • reviewed 2026-09-28T16:43:47.740Z sha 476b635 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-28T17:11:51.618Z sha 694e1e9 :: needs maintainer review before merge. :: none

@steipete steipete self-assigned this Sep 28, 2026
The normalization cache relies on history owners replacing edited messages. Keep the unchanged question object and replace the edited response, preserving the navigation-visibility assertions.
@steipete

Copy link
Copy Markdown
Contributor Author

CI note for run 36452341516 (head 476b635):

  • checks-ui (1/3): chat-position-projection.test.ts > "refreshes navigation visibility when retained message content changes" mutated a retained message in place (response.content = ...). This PR's normalization cache relies on the immutable-snapshot contract its history owners already follow: edited messages are published as replacements. Fixed in 67b8374: the fixture keeps the unchanged question object and publishes replacement response objects, with all three visibility assertions unchanged. The file passes 10/10.
  • checks-ui-e2e (4/9): chat-model-controls.e2e.test.ts:88 (poll timeout) and github-link-hovercard.e2e.test.ts:518 (30 s waitForFunction timeout). Both files pass locally on this head (34/34). Neither appears in the UI E2E annotations of the last 40 failed CI runs on other branches. The cause is not established; the next head's CI will show whether they recur.

@steipete
steipete enabled auto-merge (squash) September 28, 2026 17:11
Copy returned turn wrappers in a loop instead of spreading inside map, store fresh coalesced output without an extra copy, and use bracket access for OpenClaw metadata fields.
@steipete
steipete disabled auto-merge September 28, 2026 17:37
@steipete
steipete merged commit 5139b6a into main Sep 28, 2026
85 checks passed
@steipete
steipete deleted the steipete/incremental-paging branch September 28, 2026 17:56
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 29, 2026
…ory (openclaw#160215)

* perf(ui): reuse history normalization and coalesced turns

Memoize finite-timestamp normalization by immutable message identity and
reuse unchanged message-only turns across older-page prepends. Copy output
wrappers so duplicate and grouping annotations cannot poison cached turns;
keep transient turns and time-dependent normalization on the existing path.

Align grouping fixtures with replacement-based message ownership. Prove
normalization counts, seam-only coalescing, frozen-output safety, and mixed
cold/warm build equivalence before and after prepends.

Control UI release-note context: reduce repeated work while loading older
chat history without changing message order, grouping, or live presentation.

Validation: 1075 tests across 58 files; UI typecheck, formatter, whitespace;
Codex review through P2 clean. Lite paging sanity: three complete runs.

* fix(ui): retain turn caches across transcript surfaces

Keep one latest coalesced turn per owner message in a long-lived WeakMap.
Alternating split panes and other transcript builds no longer evict each
other's cached work; changed inputs replace only their owner's entry.

Replace the empty-pass eviction assertion with extraction-count coverage
for interleaved transcripts, empty builds, and same-owner replacement.

Control UI release-note context: preserve history paging cache reuse while
multiple chat panes or transcript surfaces render.

Validation: 391 tests across 13 files, UI typecheck, formatter, whitespace,
and full-branch Codex review through P2.

* test(ui): publish edited position messages as replacements

The normalization cache relies on history owners replacing edited messages. Keep the unchanged question object and replace the edited response, preserving the navigation-visibility assertions.

* fix(ui): satisfy lint in coalesced turn caching

Copy returned turn wrappers in a loop instead of spreading inside map, store fresh coalesced output without an extra copy, and use bracket access for OpenClaw metadata fields.
steipete added a commit that referenced this pull request Sep 30, 2026
…every render (#162092)

Pane renders repeatedly normalized both operands for every roster comparison,
and abortability could scan the roster twice. Every stream delta also filtered
the complete transcript to find persisted assistant messages for the active run.

Bound the pure session-key memo to 4,096 inputs, precompute the fixed default
main alias, and preserve false equivalence for blank keys. Share one roster
pass with one normalized target. Cache persisted assistant filtering by immutable
history-array identity and the latest run, using weak retention; keep all
stream-dependent reconciliation live. This builds on immutable message
replacement in #160215 and identity-keyed derivations in #162035.

Microbenchmarks against a58e5ba, Node v24.21.0, median of seven warm
samples after a first burst:
- hasAbortableSessionRun, 1,500 rows x 100 calls: 38.083 -> 3.471 ms.
- reconcilePersistedAssistantStream, 3,000 messages x 300 deltas:
  44.310 -> 0.309 ms.
First-burst times were 44.558 -> 4.302 ms and 49.742 -> 3.432 ms.
No production perf rig was used.

Protect bounded memo reuse, blank/opaque-key semantics, single-pass roster
checks, and history-cache invalidation on run/array changes without test-only
production hooks or timers. Control UI behavior remains unchanged.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 1, 2026
…every render (openclaw#162092)

Pane renders repeatedly normalized both operands for every roster comparison,
and abortability could scan the roster twice. Every stream delta also filtered
the complete transcript to find persisted assistant messages for the active run.

Bound the pure session-key memo to 4,096 inputs, precompute the fixed default
main alias, and preserve false equivalence for blank keys. Share one roster
pass with one normalized target. Cache persisted assistant filtering by immutable
history-array identity and the latest run, using weak retention; keep all
stream-dependent reconciliation live. This builds on immutable message
replacement in openclaw#160215 and identity-keyed derivations in openclaw#162035.

Microbenchmarks against af6e033, Node v24.21.0, median of seven warm
samples after a first burst:
- hasAbortableSessionRun, 1,500 rows x 100 calls: 38.083 -> 3.471 ms.
- reconcilePersistedAssistantStream, 3,000 messages x 300 deltas:
  44.310 -> 0.309 ms.
First-burst times were 44.558 -> 4.302 ms and 49.742 -> 3.432 ms.
No production perf rig was used.

Protect bounded memo reuse, blank/opaque-key semantics, single-pass roster
checks, and history-cache invalidation on run/array changes without test-only
production hooks or timers. Control UI behavior remains unchanged.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: web-ui App: web-ui P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant