Skip to content

perf(ui): avoid repeated work while streaming replies - #182993

Merged
steipete merged 23 commits into
mainfrom
solid2/w-stream-cadence
Oct 25, 2026
Merged

steipete merged 23 commits into
mainfrom
solid2/w-stream-cadence

Conversation

@steipete

@steipete steipete commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Streaming replies repeatedly redo Markdown and transcript work for text-only deltas, wasting browser CPU and leaving newly started paragraphs below the viewport for a frame.

User Impact

New text remains visible on the next frame while safe Markdown formatting catches up within a fixed 50 ms window. Reader scroll-up, syntax, media, replacement, and final rendering retain their existing behavior.

Why This Change Was Made

A narrow live-text source keeps text-only deltas out of structural transcript and position projections. Literal text appends through the existing Markdown island; syntax, block boundaries, and completion remain canonical. The old live overlay/index replacement machinery is removed. Measured row growth reconciles through the existing end-anchor owner before paint, retaining reader authority and cancellation checks.

This head incorporates current main's prepared-DOM renderer and lazy transcript rows. The two optimizations share one renderer. Whole changed-file LOC is production 8,953 → 9,191 (+238), tests/support 5,973 → 6,399 (+426), docs 470 → 474 (+4), config 5 → 5. Effects/listeners/queries/flush/owner API counts are unchanged.

The coordinator explicitly approved the CPU/bytes tradeoff under the newer allowance for a clean ≥5% CPU win and up to approximately 2 KB gzip growth. After main’s dormant-chat deferral landed, the only merge conflict was the startup baseline. Fresh same-host builds preserve that reduction: startup 272,577 → 272,544 B (−33 B), Chat 1,247,947 → 1,248,649 B (+702 B), New Session 761,622 → 761,641 B (+19 B). Chat is 54 B above the previously approved +648 B, within the 64 B build-variance allowance. Requests and CSS are unchanged. The official checker ratchets startup to the measured 272,544 B.

Evidence

Current head: f6d1985f71a; current bundle base: 9794c6abbb6. CPU and visual proof used production 3f327131d31 against 8e7fedf560c. Eighteen of nineteen lane production UI files remain byte-identical; the remaining change is main’s annotation-editor lazy load in chat-view-frame.ts, outside the streaming path. The later test assertions, Talk fixture repair, and baseline updates do not change runtime behavior.

Proof Result
Markdown lifecycle/highlighting 18 passed
Streaming lifecycle and formatting deadline 43 Chromium tests pass after replacing obsolete DOMParser-call counts with visible autolink deadline assertions
Live-DOM security corpus 71 passed; safe intermediate DOM and final one-shot content equality, excluding renderer comments
First-paint follow regression Red at 88 px before repair; 48 follow/geometry/anchor cases passed at 1b1fb96d018; integrated production visibility probes below cover the final repair
Production next-frame visibility 136/136 sampled text updates visible on integrated head; all four previously late paragraph starts pass on frame one
Burst latest-in-frame visibility 27/27 on integrated head, versus 4/27 on base; superseded same-frame deltas are not treated as the current visible state
Talk handshake regression Prior CI40156938097 failed one reduced-motion Talk test. The test could acknowledge the mock latest socket before the provider existed; CI remained in connecting. It now holds provider creation through the connecting assertions, waits for the actual provider setup frame, and acknowledges that socket; all10 targeted E2E tests, format and lint pass.
Types, changed-file lint, independent review UI types/lint pass; no actionable P0–P2 findings
Production Knip Fails identically on current head and exact base 9794c6abbb6: one unlisted binary, scripts/generate-social-preview.mts: ffmpeg. No UI orphan is reported; the prior measured head passed.
Canonical production builds and strict size comparison Fresh base/head builds pass on current main; baseline set by official checker; prior measured production source-map provenance retained
Full CI 40158671607 passed on final head f6d1985f71a, including every ci:full UI unit, E2E, browser-extension, and real-Gateway shard

The two Gateway type jobs in the prior CI run have the same sole diagnostic on the clean merge base: src/gateway/server-methods/session-catalog.test-helpers.ts(122,5) TS2739 ({} lacks minProtocol, maxProtocol, and client). Both pnpm tsgo:core and the Gateway-methods test typecheck reproduce it at 8e7fedf560c. UI, extension, and UI test type leaves passed. That prior run also identified two cadence assertions counting DOMParser calls, obsolete after main’s prepared-DOM renderer; these now assert the visible autolink deadline, and all 43 streaming browser tests pass locally. Earlier real scroll/Markdown regressions were repaired; they are not classified as inherited.

Performance acceptance

Each workload runs 20 serial interleaved base/A-A/head triplets on this Mac, using production bundles, 400 history messages, 645 deterministic deltas, and native typing. Standard: 30 deltas/s; burst: 150/s in groups of five. Renderer thread CPU, input latency, frame gaps, dropped-frame estimates, structural counters, final output, and host load are retained. The A/A candidate is an identical base bundle.

Burst measurement is complete. Across 20 base/A-A/head sets, renderer-thread script CPU median is 636.6 → 531.8 ms (−16.5%; paired median −17.9%), and its p95 is 1,057.1 → 946.9 ms. Median per-run p95 input latency is 19.54 → 18.05 ms; p95 frame gap stays 33.4 ms. Dropped-frame median is 53.5 → 55.5, with p95 76.75 → 76.1; the A/A median is 61.5, showing shared-host frame-count noise. Position-rail observations fall 207.5 → 145 per stream; pane renders stay at one on the head. Every run ends at bottom gap 0 with the same comment-normalized final HTML hash.

Standard streaming is also complete: renderer-thread script CPU median is 1,736.95 → 1,375.20 ms (−20.8%; paired median −20.45%), with p95 1,891.60 → 1,401.00 ms. Renderer task CPU falls 4,652.78 → 4,297.64 ms. Median per-run p95 typing latency is 20.91 → 20.14 ms, and p95 frame gap remains 33.4 ms. Dropped-frame median is 247.5 → 255 (A/A 259), with p95 319.05 → 315.6. Rail observations fall 535.5 → 317 (−40.8%). All runs again have bottom gap 0 and identical comment-normalized final HTML.

The head improves script CPU in 20/20 standard pairs and 18/20 burst pairs. Burst run 30 remains an outlier at 1,828 ms script CPU, 1,529 HTML parses, and 3.37M parsed characters; it represents extra browser work, not just scheduling delay. A/A has parser/CPU outliers too. Publications and row resize deliveries remain roughly unchanged; the reliable structural reduction is position-rail work.

Neither the ≤1.0 s standard target nor the 50% burst CPU target is reached. These remain goals, not landing gates. The A/A dropped-frame and latency spreads exceed the timing band on this shared host (load roughly 50–90), so wall/frame outliers are treated as noise; twenty interleaved renderer-thread CPU pairs show the gain, and structural rail work falls in both workloads. Acceptance uses the campaign's ≤5% median/p95 band and noisy-host A/A rule. Earlier timing results are superseded because merging main changed the Markdown renderer itself.

Bundle comparison

Gzip surface Base Head Requests
Startup JS 272,577 B 272,544 B 7 unchanged
Chat JS 1,247,947 B 1,248,649 B 26 unchanged
New Session JS 761,622 B 761,641 B 20 unchanged

CSS bytes and requests are unchanged, including one startup CSS request. No new dependency or eager import was added by this lane.

Visual proof

Inspected synthetic fixtures only. The failed-check labels are fixture content. The before/after completion captures retain code highlighting and tables. The contact sheet shows base above head, at delta 162, delta 323, and completion. Full burst captures contain 335/214 frames; the standard filmstrip reaches Chromium's 450-frame capture limit, while the independent visibility probe covers the entire stream.

Before: completed streaming reply

After: completed streaming reply

Burst filmstrip: base above head

The first landing attempt stopped before dispatch because main’s lower startup baseline conflicted. No request or intent was retained. Main was merged; the lower baseline was preserved and measured afresh. Independent review of the merged candidate is clean through P2. UI typecheck and the fresh strict size check pass. Native review/preparation completed for the test-only Talk handshake repair at f6d1985f71a. Full CI40158671607 passed and native auto-merge landed this head as 1d0d6db702187d833f1c3e0cde8ac859cb33a1e4. CI40156938097 completed with that single E2E failure; it is repaired rather than classified as inherited, because the latest scheduled main shard passed.

@steipete steipete added the ci:full Keep ordinary native-locale CI selection on the next PR run. label Oct 24, 2026
@clawsweeper

clawsweeper Bot commented Oct 24, 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.

@openclaw-barnacle openclaw-barnacle Bot added app: web-ui App: web-ui scripts Repository scripts size: XL labels Oct 24, 2026
@steipete
steipete marked this pull request as ready for review October 24, 2026 22:54
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-25T03:36:45.206924Z f6d1985 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 24, 2026
@clawsweeper

clawsweeper Bot commented Oct 24, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR separates live reply text from transcript structure and defers eligible Markdown formatting within a 50 ms window.

Example: A reply grows from “A growing reply” to “A growing reply with more text”.

  • Before: Each update prepares Markdown and refreshes the live transcript projection.
  • After: The retained text node updates immediately while formatting catches up and structural indexes remain stable.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The direction is useful and completed rendering has visual evidence, but two concrete defects block merging and performance acceptance remains unfinished.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor-proof gate; inspected production-browser screenshots establish completed rendering only, and the body explicitly leaves streaming performance acceptance in progress.
Patch quality 🦪 silver shellfish (2/6) 2 actionable review findings remain.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Long streaming replies repeatedly perform formatting and transcript work, consuming CPU while users read and type.
Reason: The maintainer-authored direction continues established streaming optimizations and reuses the authoritative renderer, transcript cache, and scroll owners.

Regression provenance

Possible regression — probable (reviewed change; failure trace). No predecessor PR is attributed.

Merge readiness

⛔ Blocked before merge - 4 items remain

Keep this PR open for repair: the optimization is useful, but the patch introduces reader-position jumps and leaves a Markdown caller broken.

Priority: P2
Reviewed head: 94ce962bb39f5dc787d95fe2a4c97101e47bb66b
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should the coordinator accept the recorded 908-byte Chat boot increase above this wave’s approximately 0.5 KB allowance?
  • Recommendation: Stay within the approved allowance: Reduce bundle growth while retaining the useful optimization.
  • Why: The PR explicitly leaves this exception pending; approval of the optimization’s direction does not resolve that separate recorded gate.

Before merge

  • Preserve the captured-anchor requirement when recovering end follow (P1) - The virtualizer enables recoverDisplacedEnd whenever a canFollowEnd callback exists, so this branch now calls follow even when the captured offset is absent or reader movement invalidated it. After restoring a saved history position, pending restoration can settle while the callback still permits following; the next reconciliation then snaps the viewport to the bottom. Exact-head browser CI demonstrates the saved 400 px position moving to 960 px and also fails native-departure cases. Retain the captured-anchor condition and distinguish actual layout displacement from a restored or departed reader.
  • Migrate the remaining consumer of callable Markdown parts (P2) - Changing parts from a tuple to a function leaves ui/src/components/markdown-highlight.test.tsx:38 calling .parts.join(""). That existing consumer now throws before the lazy-highlighting scenario completes, and the reviewed-head UI check records the exact TypeError. Update it to consume .parts() and retain its highlighting and corpus assertions.
  • Await maintainer action - The campaign coordinator must resolve the explicitly pending Chat boot bundle exception before landing.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.

Findings

  • [P1] Preserve the captured-anchor requirement when recovering end follow — ui/src/pages/chat/components/chat-transcript-end-anchor.ts:179-183
  • [P2] Migrate the remaining consumer of callable Markdown parts — ui/src/pages/chat/components/chat-message-text-preparation.ts:75

Tests

  • Missing end-to-end proof: The supplied captures show completion only; streaming-time formatting, reader takeover, and completed paired CPU/input/frame acceptance are not demonstrated.
Agent review details

How this fits together

Gateway stream updates enter the Control UI chat owners, which project transcript rows and navigation markers, reconcile Markdown DOM, and maintain viewport position.

flowchart LR
  A[Gateway stream updates] --> B[Chat state owner]
  B --> C[Transcript structure]
  B --> D[Live text projection]
  C --> E[Rows and position rail]
  D --> F[Markdown reconciler]
  F --> G[Measured geometry and end anchor]
  E --> G
Loading

Technical review

Best possible solution:

Retain the existing Markdown and transcript owners while preserving captured reader anchors, completing the lazy-parts cutover, and meeting the recorded performance acceptance.

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

Current main eagerly prepares streaming Markdown and refreshes live-owner projections; source inspection establishes the repeated work, while exact-head CI independently records the introduced caller and scroll failures.

Is this the best way to solve the issue?

Separating live text from structural indexes fits the existing owners, but unconditional anchor recovery violates reader-position preservation and the lazy-parts contract must reach every consumer.

Full review comments:

  • [P1] Preserve the captured-anchor requirement when recovering end follow — ui/src/pages/chat/components/chat-transcript-end-anchor.ts:179-183
    The virtualizer enables recoverDisplacedEnd whenever a canFollowEnd callback exists, so this branch now calls follow even when the captured offset is absent or reader movement invalidated it. After restoring a saved history position, pending restoration can settle while the callback still permits following; the next reconciliation then snaps the viewport to the bottom. Exact-head browser CI demonstrates the saved 400 px position moving to 960 px and also fails native-departure cases. Retain the captured-anchor condition and distinguish actual layout displacement from a restored or departed reader.
    Confidence: 0.99
  • [P2] Migrate the remaining consumer of callable Markdown parts — ui/src/pages/chat/components/chat-message-text-preparation.ts:75
    Changing parts from a tuple to a function leaves ui/src/components/markdown-highlight.test.tsx:38 calling .parts.join(""). That existing consumer now throws before the lazy-highlighting scenario completes, and the reviewed-head UI check records the exact TypeError. Update it to consume .parts() and retain its highlighting and corpus assertions.
    Confidence: 1

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 6c33f5ff5ee0.

Provenance checked

  • Markdown formatting and reconciliation changes intended behavior with a stated reason (d04bba0: The earlier incremental pipeline was removed because its bookkeeping offset sanitizer savings and failed the end-to-end performance bar.)
  • Immutable transcript structure and live overlays keeps the original intent (259d8ae: Share structural arrays across deltas while retaining immutable snapshots, current previews, navigation markers, and row identity.)
  • Geometric end anchoring changes intended behavior with a stated reason (796adff: Page-owned permission and a retained geometric anchor jointly preserve reader intent instead of reacquiring follow after departure.)
  • Suppressed row measurement during scroll cancellation keeps the original intent (169c8fe: Settle skipped measurements without compensating after native scrolling has returned to the reader.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Vyctor H. Brzezowski: Raw commit 5f55b2a adds ui/src/pages/chat/components/chat-transcript-end-anchor.ts:90 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 5f55b2a98583; files: ui/src/pages/chat/components/chat-transcript-end-anchor.ts)
  • Marvinthebored: Raw commit d51f360 adds ui/src/pages/chat/components/chat-transcript-end-anchor.ts:109 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: d51f3607b978; files: ui/src/pages/chat/components/chat-transcript-end-anchor.ts)

PR surface

Source +182, Tests +420, Docs +4, Other +27. Total +633 across 26 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 17 370 188 +182
Tests 7 448 28 +420
Docs 1 5 1 +4
Config 0 0 0 0
Generated 0 0 0 0
Other 1 32 5 +27
Total 26 855 222 +633

Review metrics

Metric Value Why it matters
Production versus test growth Production +402/−193; tests/support +448/−28 Growth implements bounded formatting and independent live-text consumption, with distinct formatting, projection, and geometry regressions; the old live-overlay/index machinery is removed.

Labels

Label changes:

  • add P2: This is a useful Control UI performance improvement with limited scope; the introduced correctness defects must be repaired before merging.
  • add proof: 📸 screenshot: Contributor real behavior proof includes screenshot evidence.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: This is a useful Control UI performance improvement with limited scope; the introduced correctness defects must be repaired before merging.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • proof: 📸 screenshot: Contributor real behavior proof includes screenshot evidence.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 24, 2026, 7:11 PM ET / 23:11 UTC.

Reconcile the existing end anchor after the measured range commits, retaining the frame fallback and reader ownership checks. Prove the first-paint gap at the real ResizeObserver boundary and target the latest non-space glyph in the visibility probe.
Merge current main while preserving its direct DOM Markdown content, lazy transcript rows, and media admission. Keep safe text previews and callable formatting preparation over the same canonical renderer. Retain both security corpora and the pre-paint anchor repair.
Replace obsolete DOMParser call counts with visible autolink timing and retain immediate text and completion coverage after prepared-DOM rendering.
@steipete
steipete enabled auto-merge (squash) October 25, 2026 03:41
@steipete
steipete merged commit 1d0d6db into main Oct 25, 2026
114 of 116 checks passed
@steipete
steipete deleted the solid2/w-stream-cadence branch October 25, 2026 03:46
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash auto-merge.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 25, 2026
* perf(ui): decouple live text from transcript formatting and layout

* perf(ui): follow measured content through the page scroll policy

Keep live row and marker structure immutable between visibility changes, notify the page scroll owner on observed row-size changes, and avoid per-text scroll work. Preserve first-publication follow and locked-reader behavior. Extend streaming evidence with post-layout text visibility and fast-provider bursts.

* test(ui): record streaming benchmark timeout diagnostics

* perf(ui): let captured transcript anchors own content growth

* perf(ui): preserve visible text during formatting catch-up

* perf(ui): coalesce formatting with arriving stream text

* perf(ui): coalesce streaming formatting before paint

* perf(ui): coalesce only stream deltas that share a frame

* perf(ui): keep stream following in the existing end anchor

* perf(ui): bound streaming formatting to fifty milliseconds

* refactor(ui): keep suppressed row measurement in its owner

* perf(ui): keep inline syntax out of streaming previews

* perf(ui): isolate startup labels from streamed text

* fix(ui): preserve measured transcript scroll ownership

* fix(ui): preserve measured streaming scroll ownership

* refactor(ui): inline the transcript settled-position check

* fix(ui): follow measured streaming growth before paint

Reconcile the existing end anchor after the measured range commits, retaining the frame fallback and reader ownership checks. Prove the first-paint gap at the real ResizeObserver boundary and target the latest non-space glyph in the visibility probe.

* test(ui): assert streaming formatting at the visible boundary

Replace obsolete DOMParser call counts with visible autolink timing and retain immediate text and completion coverage after prepared-DOM rendering.

* perf(ui): record approved streaming cadence baseline

* test(ui): acknowledge the actual Talk provider handshake
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 ci:full Keep ordinary native-locale CI selection on the next PR run. P2 Normal backlog priority with limited blast radius. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant