Skip to content

perf(ui): defer syntax highlighting until code renders - #175105

Merged
steipete merged 5 commits into
mainfrom
solid2/w-perf-markdown
Oct 17, 2026
Merged

steipete merged 5 commits into
mainfrom
solid2/w-perf-markdown

Conversation

@steipete

@steipete steipete commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Chat loads the syntax highlighter and fourteen language grammars even when the conversation contains only prose. Reader documents also load a general emoji plugin to perform named-shortcode replacement.

User Impact

Plain chat boots with 23,232 fewer gzip bytes. The first code block loads highlighting on demand; code remains escaped, readable, and copyable while loading or if the optional chunk fails. Completed rendering preserves the previous HTML, including code controls, links, tables, and sanitization.

Why This Change Was Made

Split highlighting from the parser/sanitizer chunk, refresh cached and streamed markup when it becomes available, and keep the reader and plugin-readme consumers reactive. Reader emoji expansion now uses the existing catalog and token-replacement owner, without the general plugin runtime. Chat shortcode behavior and composer completion are unchanged.

The apparent second renderer is actually a separate source-ownership parser: MarkdownIt already owns transcript, reasoning, and document HTML; mdast/micromark owns exact code/reasoning offsets, container boundaries, and incremental retention. These contracts are not interchangeable, so the canonical source parser and all sanitizer boundaries remain. The full emoji catalog also remains necessary for completion and picker coverage. No dependency was added or upgraded.

Evidence

Final production builds use matching comparison metadata on the same machine and toolchain, checked with the strict --base-dist performance tool; base afc42329297a5134f023a2d51c5b61290b299aa6:

Metric Before After Saved
Chat boot JS gzip 1,564,730 B / 27 requests 1,541,498 B / 27 requests 23,232 B / 0 requests
New Session boot JS gzip 1,118,570 B / 22 requests 1,118,540 B / 22 requests 30 B / 0 requests

Startup is 337,449 B gzip / 7 JS requests / 1 CSS request. Chat's hard cap drops from 1,580,000 to 1,550,000 B; other byte/request caps stay unchanged. The generated boot manifest excludes all highlight.js modules.

Proof Result
Full PR CI Run 39008949041 passed on 60e418eb57d3b3fb4f20987a1a4895c49699dc57; hosted build-artifacts and workflow-sanity gates also passed
UI typecheck Passed on final source; core UI-components test typecheck leaf also passed
Focused unit tests, one worker Initial 40 passed across 3 files; final lazy-load/corpus and streaming files: 31 passed, including stream finalization, history, JSON controls, and linear streaming work
Attachment browser tests, one worker All 6 passed, including transport refresh and retained controls
Transcript corpus 12 sanitized HTML fixtures captured on the base, byte-identical after load
Emoji corpus Every catalog shortcode plus code, links, HTML, escapes, and unknown-name cases match the former plugin
Build and strict paired performance check Passed; final lowered cap also passed
Production Knip Passed
Synthetic browser capture Plain chat requests no highlighting chunks; first code requests them; skill preview stays open after highlighting at 390/768/1366/1440 px with all 400 lines
Before/after screenshot and transcript DOM Fresh final capture: byte-identical PNG; equivalent transcript DOM (only owner comments and class token order differ)
Independent review P0–P2 clean for the initial change, complete retention repair, and final invalidation/block-art repair; DOM/parser owner context supplied

Touched production TypeScript: 4,320 → 4,462 LOC (+142). Tests/fixtures: 2,356 → 2,641 LOC (+285). Solid checklist counts are unchanged: controllers 0, effects 4, render effects 0, untrack 0, native listeners 1, DOM queries 3, class-string patterns 0, flush 0, ownership capture 2.

CI run 39003243581 caught a missing NodeNext JSON import attribute and two control-retention regressions. The repair keeps provisional code in the incremental streaming tail until the first highlighting request settles, then lets the existing reconciler promote it normally. Markdown attachments opt into the same incremental reconciliation within their existing keyed source lifetime. A shared partition helper also covers loaded history, JSON, and finalizing a stream while highlighting is pending. The sidebar and attachment readers use incremental refs. The delayed-load regression exercises actual transcript preparation and JSON rendering, retaining code wrappers, expanded/wrapped state, and JSON raw mode; the DOM reconciler is unchanged. These failures are treated as attributable and repaired, not inherited.

Review also caught broad prose invalidation when highlighting loaded. Cache readiness now tracks only highlightable code. The next full-CI run (39006808932) exposed pending highlighting withholding literal block art and a synchronous sanitizer-work test that never yielded for the lazy import. The block-art path now stays independent of highlighting; the workload suite explicitly awaits the highlighter, while the controlled delayed-load test verifies prose does not rerender and block art stays literal before loading completes. Both failures reproduce on the repair head and pass on the original base; all 31 final focused cases pass. The copy E2E also assumed a paragraph’s first child was text; incremental rendering legitimately inserts comment markers. It now locates the same visible words with a text-node walker and still exercises the real browser selection and clipboard command. Its typecheck, lint, and independent review pass; its browser proof passed in full PR CI. The Debug event-log browser test also waits for its initial highlighted span before selecting it; Chromium then passes all node-identity and selected-text retention assertions across live prepend/eviction. This test-only adjustment passes lint, types, and independent review.

The added production code is the shared lazy-load/readiness boundary and the small reader emoji rule; the highlighter implementation and grammar set move intact. No rendering controllers, effects, listeners, DOM queries, or ownership-capture calls were added.

Screenshots below use only synthetic content.

Before: synthetic transcript with code and a table

After: identical synthetic transcript with lazy highlighting

The completed run 39007690123 has only the copy-test text-node assumption and initial Debug highlighting wait repaired in the final two test commits. Its skill-preview, remaining UI, browser-extension, and real-Gateway shards passed. The final full-CI run 39008949041 passed with both test repairs, including every UI, browser-extension, and real-Gateway shard.

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

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 17, 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-17T05:53:56.979464Z decaec8 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui scripts Repository scripts size: L labels Oct 17, 2026

@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: 96c2504720

ℹ️ 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 thread ui/src/components/markdown.ts Outdated

function markdownRenderKey(options: MarkdownRenderEnv): string {
return `${i18n.getLocale()}\0${options.assistantTranscriptRoleHeaders}\0${options.codeBlockChrome}\0${options.codeBlockInteraction}\0${options.fileLinks}\0${JSON.stringify(options.githubRepo ? [options.githubRepo.owner, options.githubRepo.repo] : null)}\0${markdownGitHubAliasSignature(options.githubRepositories, options.githubRepo)}\0${options.interactiveImages}\0${options.linkFavicons}\0${options.progressBars}\0${options.mode}\0${options.remoteImages}\0${options.sessionLinks}\0${options.tableInteractions}\0${JSON.stringify(options.humanMentionTokens ?? [])}`;
return `${markdownHighlightingReady()}\0${i18n.getLocale()}\0${options.assistantTranscriptRoleHeaders}\0${options.codeBlockChrome}\0${options.codeBlockInteraction}\0${options.fileLinks}\0${JSON.stringify(options.githubRepo ? [options.githubRepo.owner, options.githubRepo.repo] : null)}\0${markdownGitHubAliasSignature(options.githubRepositories, options.githubRepo)}\0${options.interactiveImages}\0${options.linkFavicons}\0${options.progressBars}\0${options.mode}\0${options.remoteImages}\0${options.sessionLinks}\0${options.tableInteractions}\0${JSON.stringify(options.humanMentionTokens ?? [])}`;

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 Subscribe only code-bearing renders to highlighter readiness

When the first code block finishes loading the highlighter, this unconditional signal read invalidates every mounted Markdown computation, including prose-only transcript messages. Because readiness is also part of the cache key, those messages miss their existing false entries and are reparsed, sanitized, and reconciled together; a long chat can therefore incur a large main-thread spike exactly when the first code block appears. Gate this dependency on content that can actually invoke highlighting, so prose retains its cached rendering.

AGENTS.md reference: ui/AGENTS.md:L38-L42

Useful? React with 👍 / 👎.

@steipete
steipete enabled auto-merge (squash) October 17, 2026 04:47
@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. 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. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 17, 2026
@clawsweeper

clawsweeper Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR loads syntax highlighting on demand and replaces the reader’s emoji plugin runtime with shared shortcode replacement.

Example: Open a prose-only chat, then receive a TypeScript code block containing const answer = 42.

  • Before: Chat downloads the highlighter and fourteen grammars before any code appears.
  • After: Plain-chat boot saves a reported 23,232 gzip bytes; the first code block requests highlighting while remaining readable and copyable.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A useful optimization supported by inspected browser parity, paired-build measurements, and focused production-path retention coverage.
Proof confidence 🐚 platinum hermit (4/6) This maintainer-authored PR is outside the contributor-proof gate; inspected Control UI screenshots establish rendered parity, while the body records production-build savings and browser observations of on-demand loading.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Prose-only chat downloads syntax-highlighting code it does not yet need.
Reason: The maintainer-authored direction delivers measured transfer savings while preserving existing rendering and copy behavior.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it delivers a useful, maintainer-directed loading improvement that current main does not provide. The prior rendering findings are repaired, with no new actionable defect found; exact-head CI remains pending.

Priority: P2
Reviewed head: 60e418eb57d3b3fb4f20987a1a4895c49699dc57

Before merge

None.

Findings

None.

Agent review details

How this fits together

Control UI Markdown consumers turn transcript and document text into sanitized HTML, with shared code rendering and incremental DOM reconciliation preserving reader controls.

flowchart TD
  A[Transcript and document text] --> B[Markdown parser]
  B --> C[Shared code renderer]
  C --> D[Lazy highlighter]
  D --> C
  B --> E[HTML sanitizer]
  E --> F[Reactive views and DOM reconciler]
Loading

Technical review

Best possible solution:

Retain the shared lazy highlighter and existing sanitizer/reconciler owners, then land through the normal exact-head CI gates.

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

Current-main source directly imports the highlighter and fourteen grammars through the shared code renderer, establishing the eager-loading path without executing target code.

Is this the best way to solve the issue?

The change cuts loading at the existing shared renderer, preserves its grammar and sanitization contracts, and uses the existing incremental DOM owner to retain controls.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Highlighter loading and chunk placement changes intended behavior with a stated reason (28971b4: The earlier module split deliberately preserved synchronous rendering and the existing dependency chunk; the current PR explicitly changes loading to reduce prose-chat transfer cost.)
  • Markdown cache and streaming retention keeps the original intent (ebd12a0: Completed independent Markdown blocks retain parsed and sanitized output to keep long streams responsive.)
  • Reader document rendering and image lifetime keeps the original intent (b605d7c: The reader render lifetime owns image listeners and delayed completion; the reactive rendering split preserves its abort cleanup and URL/sanitization policies.)
  • Code controls during incremental updates keeps the original intent (c2c5519: Incremental Markdown updates preserve reader-owned disclosures, wrapping, and code-control identity.)
  • Chat boot budget keeps the original intent (7bb73b5: Measured route-specific byte and request caps prevent loading regressions; this PR tightens the chat byte cap after paired measurements.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Introduced change and current-main behavior: The pinned introduced diff moves the existing highlighter and grammar registration into a dynamic module; fetched main still imports those grammars synchronously. (ui/src/components/markdown-code-blocks.ts:26, 60e418eb57d3)
  • Prior findings resolved: Readiness invalidation is conditional on code-bearing cached HTML, and pending code remains in the mutable tail through history rendering, JSON rendering, and stream finalization; the delayed-load test checks retained controls and unchanged prose work counts. (ui/src/components/markdown.ts:639, 60e418eb57d3)
  • Inspected browser proof: The supplied synthetic Control UI before/after images show the same highlighted TypeScript, copy control, prose, and table; both downloaded PNGs have identical SHA-256 fb917babe2914bd45f632742a86ae9a721a6c682646311a1331c86b44223983e. The PR also reports paired production-build measurements and browser request observations. (60e418eb57d3)
  • Original highlighting contract: ui: highlight WebChat code blocks #83569 established bounded grammars, explicit-language and automatic highlighting, original copy payloads, and escaped HTML; this PR preserves those contracts after loading. (ui/src/components/markdown-highlight-runtime.ts:39, 1fbb4e4e6a9e)
  • Earlier loading optimization remains distinct: perf(ui): defer New Session transcript rendering #175036 deferred transcript rendering from empty New Session; this PR separately removes highlighting from prose-chat loading. (ui/config/control-ui-chunking.ts:110, 85082d969005)
  • Exact-head checks: Live checks for the reviewed head contain pending jobs and no failure, timed-out, or action-required conclusions; the CI gate is pending, and GitHub reports mergeable true with blocked merge state. (60e418eb57d3)

Likely related people:

  • Peter Steinberger: Raw commit 28971b4 adds ui/src/components/markdown-code-blocks.ts:136 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 28971b414331; files: ui/src/components/markdown-code-blocks.ts)

PR surface

Source +199, Tests +212, Docs +4, Other 0. Total +415 across 25 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 14 346 147 +199
Tests 9 220 8 +212
Docs 1 6 2 +4
Config 0 0 0 0
Generated 0 0 0 0
Other 1 2 2 0
Total 25 574 159 +415

Review metrics

Metric Value Why it matters
Production versus test growth Production TypeScript +142 LOC; tests and fixtures +285 LOC Growth supplies the shared loading/readiness boundary, reader emoji replacement, control retention, and independent parity coverage.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: This is a bounded Control UI loading improvement with preserved rendering behavior and no demonstrated urgent user failure.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • 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.

History

Review history (3 earlier review cycles)
  • reviewed 2026-10-17T04:51:43.790Z sha 96c2504 :: needs changes before merge. :: [P2] Subscribe only affected Markdown renders to highlighter readiness | [P2] Preserve code-block controls when highlighting becomes ready
  • reviewed 2026-10-17T05:41:07.514Z sha f1b6cbe :: needs changes before merge. :: [P2] Subscribe only affected Markdown renders to highlighter readiness
  • reviewed 2026-10-17T05:55:15.906Z sha decaec8 :: needs maintainer review before merge. :: none

Reviewed October 17, 2026, 2:17 AM ET / 06:17 UTC (Revision 4).

@steipete
steipete disabled auto-merge October 17, 2026 05:05
Keep pending highlighted HTML in the existing mutable DOM tail across streaming completion, loaded history, and JSON. Preserve attachment and sidebar controls with incremental reconciliation, and cover the real transcript entry points with a delayed-load regression.
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added the clawsweeper:intake:feature Preliminary submission classification; full source review pending. label Oct 17, 2026
Keep prose caches and literal block art independent of the optional highlighter. Preserve the synchronous streaming workload test after loading highlighting, and cover pending block art and prose work counts.
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot removed the clawsweeper:intake:feature Preliminary submission classification; full source review pending. label Oct 17, 2026
Keep the browser clipboard proof independent of incremental markdown comment boundaries while selecting the same visible words.
Keep the live-event selection retention proof while allowing the optional highlighter to load before selecting its output.
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed 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. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 17, 2026
@steipete
steipete merged commit 4a2c849 into main Oct 17, 2026
139 of 142 checks passed
@steipete
steipete deleted the solid2/w-perf-markdown branch October 17, 2026 06:28
@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 18, 2026
* perf(ui): defer markdown highlighting until code renders

* fix(ui): retain markdown controls while highlighting loads

Keep pending highlighted HTML in the existing mutable DOM tail across streaming completion, loaded history, and JSON. Preserve attachment and sidebar controls with incremental reconciliation, and cover the real transcript entry points with a delayed-load regression.

* fix(ui): scope lazy highlighting invalidation to code

Keep prose caches and literal block art independent of the optional highlighter. Preserve the synchronous streaming workload test after loading highlighting, and cover pending block art and prose work counts.

* test(ui): select transcript text across DOM markers

Keep the browser clipboard proof independent of incremental markdown comment boundaries while selecting the same visible words.

* test(ui): wait for lazy Debug payload highlighting

Keep the live-event selection retention proof while allowing the optional highlighter to load before selecting its output.
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. docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: L 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