Skip to content

perf(ui): construct live Markdown tails directly as DOM - #182875

Merged
steipete merged 8 commits into
mainfrom
solid2/w-markdown-arch
Oct 25, 2026
Merged

steipete merged 8 commits into
mainfrom
solid2/w-markdown-arch

Conversation

@steipete

@steipete steipete commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Live chat tails repeatedly serialize Markdown to HTML, parse it through DOMPurify, then parse it again for reconciliation. This change constructs supported Markdown syntax directly as allowlisted DOM only for the mutable streaming tail and carries that fragment through the existing reconciler.

User Impact

Settled messages, reload, history load, session switch, completed prefixes, and completion retain the existing HTML + DOMPurify path and string cache. Raw HTML, unsupported plugin tokens, and specialized renderers keep the full sanitizer boundary. Prepared fragments are cloned before consumer mutation. Appearance, links, reader controls, and lazy boundaries remain unchanged.

Peter accepted the additional code and chat bytes after the original experiment measured streaming script CPU −8.6% and HTML assignments 2,129 → 178. The broad direct-rendering candidate was rejected after a reload p95 regression, so this revision restricts direct construction to streaming. Three base and three broad-candidate diagnostic profiles did not establish per-node construction as the cause of that tail; no causal claim is made from those samples.

Evidence

Security proof is against the original pipeline at main 368b9dc52b98985dda08c2579fa1bff3e1809485; the newer fetched main has identical Markdown owners and budget inputs. All differential inputs match the current source hashes.

Proof Result
Independent explicit XSS/mXSS autoreview Scoped clean at P0–P2; allowlists, URL policy, raw HTML fallback, fragment isolation, callers, promotion, and completion reviewed
Narrowed corpus/fuzz differential 1,612 documents: 1,516 direct live tails, 96 fallback; zero DOM differences, unsafe DOM, reparsing mutations, or alerts
Narrowed streaming security differential 71 cases, 2,487 updates, 71 completions; zero differences, unsafe DOM, or alerts
Completion parity Actual settled chat preparation returns strings and matches bulk DOM byte-for-byte, removing only empty reconciler comment markers
Final API/test-cutover autoreview Scoped clean at P0–P2; deleted string API and real-DOM retention proof reviewed
Fragment ownership Mutating one consumer leaves the prepared fragment and a second consumer unchanged
Focused tests 85 security/chat tests plus 26 cutover tests pass; three cutover files exercised the real streaming API, stable-prefix budgets, node retention, and attachments
UI typecheck / targeted lint / production build Pass; lint uses boundary-free tsconfig.ui.json
Strict same-machine asset comparison Pass; no violations against measured base
Production Knip Same four unused files as the measured base; exact output matches, no new ignores
Startup gzip 281,717 → 281,465 B; 7 JS + 1 CSS unchanged
Chat boot gzip 1,271,846 → 1,274,050 B (+2,204 B); 19 JS + 3 CSS unchanged
New Session gzip 767,623 → 767,376 B; 16 JS + 3 CSS unchanged
CSS 303,561 B on both builds; inherited absolute cap overage retained
Exact-head ci:full 40145767702, success on f01cc6fd4d3a66ba00d8a4ad63b7e89958a8ea0f
Final streaming workload All 60 cells delivered 645 deltas/writes; one normalized final DOM across all variants; no harness warnings

Startup raw bytes are identical; its gzip movement is build variation, not a causal win. The supported --update-baseline --reason command records the accepted CPU/bytes tradeoff and measured startup baseline. Chat's cap is 1,274,861 B: measured head plus the existing 811 B headroom.

Final same-machine timing uses 20 serial base/base/head triplets (60 cells). Values below are median / nearest-rank p95 / min–max, in milliseconds unless noted.

CPU / work Base A/A control Streaming-only head
Streaming script CPU 1,838.361 / 2,025.458 / 1,681.824–2,154.721 1,823.193 / 1,883.413 / 1,737.818–2,144.218 1,712.024 / 1,780.806 / 1,629.428–2,100.217
Reload script CPU 528.444 / 556.223 / 445.246–557.612 521.883 / 611.013 / 460.011–621.389 530.238 / 591.923 / 446.782–613.996
Reload task CPU 1,102.911 / 1,355.079 / 997.925–1,418.720 1,105.361 / 1,331.230 / 1,041.008–1,378.931 1,138.467 / 1,287.940 / 1,012.920–1,307.421
Streaming HTML assignments (count) 2,114 / 2,191 / 2,005–2,254 2,113.5 / 2,177 / 1,936–2,252 236.5 / 317 / 229–824

Streaming script median improves 6.87% (A/A −0.83%) and p95 improves 12.08%. HTML assignments fall 88.81%. Reload script median changes +0.34%; its p95 is +6.42%, while the unchanged A/A p95 is +9.85%. Reload total-task median is +3.22% and p95 −4.95%. The shared host's one-minute load ranged 35.14–77.36; wall readiness is noisy (A/A median +30.26%) and is not treated as a speedup or regression. The raw p95 increase is disclosed: the unchanged control has a larger tail, so it does not establish a candidate-specific reload regression. Bulk source/cache behavior is restored, and reload script/task medians remain inside the 5% band. Reload style CPU is a disclosed exception among subphases: median +6.26%, p95 −2.08%; there is no CSS change and the bulk DOM path is unchanged. This is not a claim that every CPU submetric improved.

Touched UI production source: 1,999 → 2,444 lines (+445). All touched production/config/scripts: 2,795 → 3,241 (+446). Tests/support: 3,527 → 3,599 (+72). The simplification removes static prepared caching and the obsolete string-streaming production API; string assertions now serialize the real streaming result in test support. Effects 1 → 1, listeners 0 → 0, DOM queries 2 → 2, cleanup 1 → 1; owner APIs and reactive state counts unchanged. No Worker or dependency added.

Synthetic-only before/after captures were inspected. Both show the final streamed reply with identical code blocks, tables, and links.

Before: synthetic streamed Markdown

After: synthetic streamed Markdown

Workload, acceptance, and limits

The final acceptance run uses a 400-message synthetic chat and 645 deltas at 30/s: 20 serial base/base/head triplets, untraced renderer thread CPU, host load recorded. The second base copy is an A/A control. Reload uses persisted state and HTTP cache; it does not model a cold-network first visit. Acceptance requires streaming improvement and reload median regression ≤5% with no real p95 regression. On a noisy host, A/A and CPU over 20 pairs take precedence over wall timing. The original −40% / ≤1.0 s streaming and −40% settled targets are not achieved or claimed.

The corpus includes transcript Markdown, DOMPurify historical XSS/mXSS payloads, hostile attributes/language labels, URL schemes and decoded control bytes, generated links/favicons, nested grammar, deterministic prefixes, and syntax-boundary/random streaming splits. Raw authored HTML still uses DOMPurify.

Reproduce with scripts/bench-control-ui-cold-load.ts --bundle-dir <base> --compare-bundle-dir <base-copy> --compare-bundle-dir <head> --runs 60 --streaming-reply --transcript-messages 400 --face chat --untraced --thread-cpu-time. Builds use pnpm ui:build; strict asset comparison uses both same-machine bundles. No broad local E2E, Docker, or remote lease was used.

The first lint attempt used the editor UI graph and timed out in unrelated SDK declarations; the corrected documented lint graph passes. Knip's four inherited files are extensions/codex/src/app-server/protocol-validator-schemas.ts, src/gateway/mcp-app-standalone-host.ts, src/gateway/worker-environments/repository-node-requirement.ts, and src/sessions/runtime-context.ts.

@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
@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 24, 2026
@clawsweeper

clawsweeper Bot commented Oct 24, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR constructs ordinary chat Markdown as DOM nodes and passes them to the existing reconciler to avoid repeated HTML parsing.

Example: A streamed reply contains TypeScript fences, tables, and links.

  • Before: Markdown becomes HTML that DOMPurify and the reconciler parse separately.
  • After: Supported Markdown supplies prepared DOM; specialized content retains the existing sanitizer path.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful owner-supported optimization with inspected visual evidence, one concrete rendering regression, and incomplete performance acceptance evidence.
Proof confidence 🦐 gold shrimp (3/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Long streamed replies repeatedly parse HTML while updating the chat transcript.
Reason: The existing area owner supports this direction and explicitly accepts its code and boot-size costs.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep this PR open: the optimization has owner support, but the direct renderer introduces a session-link regression.

Priority: P2
Reviewed head: dfd261d6960b120f3269d48355e2390406593909

Before merge

  • Preserve session metadata on inline-code tokens (P2) - With sessionLinks enabled, render https://chat.example/control/chat/roboclaw/d0effac9 inside backticks while viewing the UI on another origin under /control. The existing session-link plugin attaches data-session-href to this code_inline token so a configured public Gateway origin can receive session title registration, previews, and navigation. This branch constructs the code element with {}, dropping that attribute; markdown-it's existing renderer preserves it through renderAttrs. Consequently the chat path leaves this session reference as inert code. Apply the shared allowlisted attribute handling to inline-code tokens, or fall back when they carry attributes, and cover this case through the new production path.

Findings

  • [P2] Preserve session metadata on inline-code tokens — ui/src/components/markdown-tokens.ts:244-246

Tests

  • Missing end-to-end proof: Complete the declared current-head streaming performance comparison and exercise a public-origin session URL in inline code through chat preparation and reconciliation.
Agent review details

How this fits together

Chat message preparation passes parsed Markdown through rendering and sanitization into the framework-neutral DOM reconciler, which retains interactive transcript content.

flowchart TD
  A[Chat Markdown] --> B[Markdown parser]
  B --> C[Allowlisted DOM construction]
  B --> D[HTML renderer and DOMPurify]
  C --> E[Prepared content]
  D --> E
  E --> F[Existing DOM reconciler]
  F --> G[Chat transcript]
Loading

Technical review

Best possible solution:

Preserve sanitized inline-token metadata within the existing construction path while retaining one sanitizer policy and one reconciler.

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

Source tracing establishes both repeated HTML parsing on main and the introduced inline-session metadata loss; no target code was executed.

Is this the best way to solve the issue?

Carrying prepared DOM through the existing reconciler follows the performance guidance, but inline code must preserve the metadata already produced by parser plugins.

Full review comments:

  • [P2] Preserve session metadata on inline-code tokens — ui/src/components/markdown-tokens.ts:244-246
    With sessionLinks enabled, render https://chat.example/control/chat/roboclaw/d0effac9 inside backticks while viewing the UI on another origin under /control. The existing session-link plugin attaches data-session-href to this code_inline token so a configured public Gateway origin can receive session title registration, previews, and navigation. This branch constructs the code element with {}, dropping that attribute; markdown-it's existing renderer preserves it through renderAttrs. Consequently the chat path leaves this session reference as inert code. Apply the shared allowlisted attribute handling to inline-code tokens, or fall back when they carry attributes, and cover this case through the new production path.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Markdown sanitization and link decoration keeps the original intent (perf(ui): defer syntax highlighting until code renders #175105: Preserve rendering, sanitization, and lazy highlighting while avoiding eager highlighter loading.)
  • Prepared DOM handoff changes intended behavior with a stated reason (d04bba0: The previous incremental pipeline was removed because bookkeeping offset its sanitization savings.)
  • Code-block layout and copy payloads keeps the original intent (0e17e08: Keep long-block controls reachable and preserve existing code interactions.)
  • Chat boot budget changes intended behavior with a stated reason (e89e5ad: Budget reflected deferred composer suggestions and person-card content; this PR records owner acceptance of the additional renderer bytes.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Introduced regression: The code_inline branch creates code elements with an empty attribute object, discarding metadata supplied by parser plugins. (ui/src/components/markdown-tokens.ts:246, dfd261d6960b)
  • Existing session-link contract: The session-link plugin deliberately attaches data-session-href to code_inline tokens for session URLs on another origin; session title registration, hover targeting, and navigation consume this metadata. (ui/src/components/markdown-session-links.ts:118, dfd261d6960b)
  • Pinned renderer contract: OpenClaw pins markdown-it 15.0.3; its code_inline renderer preserves token attributes through renderAttrs, confirming that the new branch changes existing behavior. (src/renderer.ts:26, a8c00d474ec9)
  • Attribute-policy verification: The new construction path imports DOMPurify and relies on isValidAttribute; the pinned 3.4.17 implementation applies unsafe attribute-value checks, including comment and raw-text closers. (src/purify.ts:3303, a77a3e78b59f)
  • Owner direction and supplied proof: The PR records acceptance of additional renderer code and 2,374 gzip bytes of chat boot growth. Both downloaded screenshots were inspected and show matching rendered content; the body still marks the rebased performance comparison as running. (dfd261d6960b)
  • Current-main behavior and prior rollback: Fetched main retains the existing HTML rendering path. The earlier rollback at refactor(ui): remove ineffective incremental Markdown pipeline #181856 removed incremental sanitizer bookkeeping because its measured benefit was insufficient; this PR instead constructs ordinary Markdown directly. (ui/src/components/markdown.ts:590, aaecd52e6bff)

Likely related people:

  • Peter Steinberger: Raw commit 7bdba03 adds ui/src/lib/markdown-dom-reconciler.ts:89 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 7bdba03c22d3; files: ui/src/lib/markdown-dom-reconciler.ts)

PR surface

Source +483, Tests +66, Other +1. Total +550 across 13 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 9 996 513 +483
Tests 2 72 6 +66
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 5 4 +1
Total 13 1073 523 +550

Labels

Label changes:

  • add P2: The optimization addresses long-reply rendering cost, with a bounded regression affecting session references rendered as inline code.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦐 gold shrimp.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: The optimization addresses long-reply rendering cost, with a bounded regression affecting session references rendered as inline code.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

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, 5:14 PM ET / 21:14 UTC.

@steipete
steipete marked this pull request as ready for review October 24, 2026 21:23
@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-25T00:14:38.184967Z f01cc6f 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.

@steipete
steipete enabled auto-merge (squash) October 24, 2026 21:25

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: dfd261d696

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +244 to +246
if (token.type === "code_inline") {
parent.append(
element("code", {}, [token.content.replaceAll("\0", "").replace(/\r\n?/gu, "\n")]),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve session-link attributes on inline code

When a message contains a backtick-wrapped session URL on the configured public origin rather than the current browser origin, this branch discards the token's data-session-href attribute. installMarkdownSessionLinks deliberately adds that attribute to code_inline tokens in markdown-session-links.ts:112–118, and both session-title registration and session navigation use it to recognize these references. Consequently, the new chat rendering path leaves these URLs as inert code instead of providing the existing session title, hovercard, and navigation behavior. Preserve allowlisted token attributes here, or fall back to the existing renderer for attributed inline-code tokens.

Useful? React with 👍 / 👎.

@steipete
steipete disabled auto-merge October 24, 2026 21:51
@steipete steipete changed the title perf: avoid repeated HTML parsing for chat Markdown perf(ui): construct live Markdown tails directly as DOM Oct 25, 2026
@steipete
steipete merged commit b688518 into main Oct 25, 2026
121 of 123 checks passed
@steipete
steipete deleted the solid2/w-markdown-arch branch October 25, 2026 00:45
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 25, 2026
)

* perf: render ordinary chat Markdown directly to DOM

* test(ui): type Markdown content mocks and serialize prepared prose

* perf(ui): ratchet Markdown budgets to the refreshed build

* perf(ui): refresh Markdown budgets after main merge

* perf(ui): limit token DOM construction to live Markdown tails
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. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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