Skip to content

feat(android): render LaTeX display math in chat via bundled KaTeX - #101435

Merged
steipete merged 4 commits into
mainfrom
feat/android-chat-math-nash
Jul 7, 2026
Merged

steipete merged 4 commits into
mainfrom
feat/android-chat-math-nash

Conversation

@steipete

@steipete steipete commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Related: #100699

What Problem This Solves

Delivers the declared Android math follow-up: $$…$$ and \[…\] blocks in assistant responses rendered as typeset math instead of raw TeX, matching the iOS display-math behavior from #100829.

Why This Change Was Made

Dependency decision first: jlatexmath-android (the only native Android LaTeX library lineage) is GPL-2.0 and archived since 2023 — unusable for store distribution. Instead, KaTeX v0.17.0 (MIT) ships as bundled assets (minified js/css + required woff2 fonts only; no Gradle dependency): the release archive's SHA-256 matches GitHub's published digest, per-file hashes are recorded in an assets README, and the licenses screen gains a KaTeX entry (MIT + SIL OFL font note) per the Android licenses policy.

Rendering keeps WebViews out of the transcript entirely: one process-singleton offscreen WebView (attached as a transparent 1px view per Android's visible-state contract, lifecycle-detached) renders queued math jobs into bitmaps that transcript rows display as plain Images, cached in a byte-bounded LRU keyed by latex/width/dark-mode, with negative caching and a 3s per-job timeout falling back to code-style raw text. The WebView is locked down: an asset-allowlist request interceptor returns empty responses for anything not under file:///android_asset/katex/, LaTeX reaches KaTeX only as a JSON-encoded evaluateJavascript argument (never HTML concatenation) with trust:false, throwOnError:true, maxExpand:1000, and the only JS bridge is a render-completion callback. The process singleton retains only an Application-backed WebView and a weak activity host that detaches on destruction. Segmentation mirrors the iOS contract exactly: top-level blocks only, never inside code, unclosed math stays plain while streaming, 5000-byte cap falls back.

User Impact

Android users see typeset display math in finished assistant messages; streaming, code blocks, and oversized/invalid math keep today's plain-text behavior. Android's licenses screen credits KaTeX.

Evidence

  • 38 focused tests green across segmenter (25: delimiters, code protection, streaming, caps), renderer protocol (8: queue ordering/dedupe, cache keying incl. dark mode, negative results, timeout fallback — WebView bridge injectable), packaged renderer fallback contract (1), and license notices (4).
  • Blacksmith Testbox tbx_01kwy132f27yajdr0494ge03j7: Play + ThirdParty unit suites, both debug APK assemblies, both lint lanes, benchmark assembly, app and benchmark ktlint all passed after rebase.
  • Asset integrity: archive digest f77cf2…4b88 matches GitHub's published release digest (independently re-verified via the releases API); per-file sha256s in assets/katex/README.md.
  • Local API 36 emulator, exact rebased Play APK: valid assistant display math rendered as typeset KaTeX; malformed \frac{ stayed raw in the code-style fallback; chat remained responsive after background/foreground. Screenshots were inspected locally and not uploaded because image-upload approval was not provided.
  • Security boundary reviewed and accepted for this narrowed implementation: bundled assets only, network blocked, strict asset URL allowlist, no HTML interpolation, trust:false, bounded expansion/bitmap/cache, Application-only process lifetime, weak/detached activity host.
  • Fresh structured Codex autoreview — clean after the malformed-input and Android lint fixes.

@openclaw-barnacle openclaw-barnacle Bot added app: android App: android size: XL maintainer Maintainer-authored PR labels Jul 7, 2026
@clawsweeper

clawsweeper Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 7, 2026, 6:03 AM ET / 10:03 UTC.

Summary
The PR adds Android display-math segmentation, a WebView-backed KaTeX bitmap renderer with bundled assets/fonts, an Android license notice, i18n metadata updates, and focused Kotlin tests.

PR surface: Docs +37, Other +1330. Total +1367 across 33 files.

Reproducibility: yes. for the blockers: source inspection shows renderer.js still uses throwOnError:false and the live current-head Android build log reproduces the WebView JavaScript lint failure. The visible Android rendering behavior itself remains unproven because no emulator/device proof was provided.

Review metrics: 3 noteworthy metrics.

  • Bundled dependency assets: 1 KaTeX asset set added. Vendored runtime JS/CSS/fonts make supply-chain, license, and Android packaging behavior relevant before merge.
  • WebView JavaScript surface: 1 WebView renderer and 1 JavaScript bridge added. Assistant math content now flows through a local JavaScript renderer, so lockdown and fallback behavior need proof beyond unit tests.
  • Android build gate: 1 current-head Android build job failed. The failing android-build-play lint gate blocks merge and points at the new JavaScript-enabled WebView line.

Merge readiness
Overall: 🧂 unranked krab
Proof: 🧂 unranked krab
Patch quality: 🦪 silver shellfish
Result: blocked until real behavior proof is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P1] Fix malformed/unsupported math so it reaches ChatMathFallback instead of rendering a KaTeX error bitmap.
  • Clear the Android SetJavaScriptEnabled lint/security gate with an owner-reviewed mitigation or suppression.
  • [P2] Add redacted Android emulator/device proof showing valid display math and invalid-math fallback in chat.

Proof guidance:

  • [P1] Needs real behavior proof before merge: The PR body provides tests/build evidence but explicitly says real-device pixel rendering is unverified; add a redacted Android emulator or device screenshot/recording, terminal/live output, or logs showing rendered display math and fallback behavior, with private details redacted. Updating the PR body should trigger a fresh ClawSweeper review; otherwise ask a maintainer to comment @clawsweeper re-review. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Risk before merge

  • [P1] The PR introduces a JavaScript-enabled WebView and JavaScript bridge for assistant-provided math content; Android lint currently blocks that surface until it has an explicit reviewed mitigation or suppression.
  • [P1] The PR body still says real-device pixel rendering is unverified, so the user-visible Android transcript behavior is not proven by the included tests/build evidence.
  • [P2] Malformed or unsupported LaTeX can render as a KaTeX error bitmap instead of the promised raw fallback until renderer.js reports parse errors as failures.

Maintainer options:

  1. Fix and prove the WebView renderer before merge (recommended)
    Address the parse-error fallback, clear the JavaScript-enabled WebView lint/security gate with code or a reviewed suppression, and add real Android visual proof.
  2. Accept the WebView security surface explicitly
    Maintainers may choose to accept the local WebView renderer after owner review, but the lint gate and proof gap should be acknowledged before merge.
  3. Pause the Android renderer PR
    If the proof lane or WebView security review is not available now, pause this PR rather than merging an unproven chat rendering surface.

Next step before merge

  • [P1] Protected maintainer-labeled external feature PR needs contributor/maintainer follow-up for real Android proof and WebView security review; do not queue ClawSweeper repair while proof is missing.

Maintainer decision needed

  • Question: Should this protected-label Android display-math PR require lint-cleared WebView security review and real Android visual proof before merge, or should maintainers explicitly override one of those gates?
  • Rationale: The change is user-visible, routes assistant content through a JavaScript-enabled WebView bridge, and the PR body still says pixel rendering is unverified.
  • Likely owner: steipete — steipete owns the linked mobile polish follow-up context and the merged iOS sibling math implementation.
  • Options:
    • Require fix and visual proof (recommended): Fix the fallback and lint/security blockers, then require a redacted Android emulator or device screenshot/recording showing valid display math and invalid-math fallback before merge.
    • Override proof after code fixes: A maintainer can accept unit/build evidence after the code blockers are fixed, but Android chat rendering would remain unproven in a real setup.
    • Pause for Android proof lane: Hold the PR until an authorized Android device or emulator proof path is available.

Security
Needs attention: The diff adds a JavaScript-enabled Android WebView bridge for chat content and the current Android lint security gate fails on that line, so this needs owner-reviewed mitigation before merge.

Review findings

  • [P2] Return failure for KaTeX parse errors — apps/android/app/src/main/assets/katex/renderer.js:15
  • [P2] Clear the JavaScript-enabled WebView lint gate — apps/android/app/src/main/java/ai/openclaw/app/ui/chat/ChatMathRenderer.kt:392
Review details

Best possible solution:

Fix malformed-math fallback and the Android WebView JavaScript lint gate, then land only after redacted Android emulator or device proof shows both rendered display math and fallback behavior.

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

Yes for the blockers: source inspection shows renderer.js still uses throwOnError:false and the live current-head Android build log reproduces the WebView JavaScript lint failure. The visible Android rendering behavior itself remains unproven because no emulator/device proof was provided.

Is this the best way to solve the issue?

No, not merge-ready yet: the Android-owned renderer shape is a plausible follow-up to the iOS implementation, but it must preserve the raw fallback contract, clear the WebView lint/security gate, and prove the UI path in a real Android setup.

Full review comments:

  • [P2] Return failure for KaTeX parse errors — apps/android/app/src/main/assets/katex/renderer.js:15
    This still leaves the prior blocker unfixed: with throwOnError: false, KaTeX renders invalid or unsupported LaTeX as error-colored source instead of throwing, so this success path reports a bitmap and bypasses ChatMathFallback. Use throwing parse behavior or explicitly detect KaTeX error output before calling the bridge with success=true.
    Confidence: 0.9
  • [P2] Clear the JavaScript-enabled WebView lint gate — apps/android/app/src/main/java/ai/openclaw/app/ui/chat/ChatMathRenderer.kt:392
    The current-head android-build-play job fails Android lint on this javaScriptEnabled = true line. Because the PR intentionally adds a JavaScript WebView bridge for assistant-provided math, the patch needs a reviewed mitigation/suppression or alternative that clears the lint gate before it can merge.
    Confidence: 0.86

Overall correctness: patch is incorrect
Overall confidence: 0.88

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 2394a0a55963.

Label changes

Label changes:

  • add merge-risk: 🚨 security-boundary: The diff enables JavaScript in an Android WebView and exposes a JavaScript bridge for assistant-provided math content, and Android lint currently flags that exact line.

Label justifications:

  • P3: This PR adds mobile chat presentation polish rather than fixing an urgent production regression or blocked setup path.
  • merge-risk: 🚨 security-boundary: The diff enables JavaScript in an Android WebView and exposes a JavaScript bridge for assistant-provided math content, and Android lint currently flags that exact line.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR body provides tests/build evidence but explicitly says real-device pixel rendering is unverified; add a redacted Android emulator or device screenshot/recording, terminal/live output, or logs showing rendered display math and fallback behavior, with private details redacted. Updating the PR body should trigger a fresh ClawSweeper review; otherwise ask a maintainer to comment @clawsweeper re-review. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed

PR surface:

Docs +37, Other +1330. Total +1367 across 33 files.

View PR surface stats
Area Files Added Removed Net
Source 0 0 0 0
Tests 0 0 0 0
Docs 1 37 0 +37
Config 0 0 0 0
Generated 0 0 0 0
Other 32 1340 10 +1330
Total 33 1377 10 +1367

Security concerns:

  • [medium] JavaScript-enabled WebView bridge needs lint-cleared review — apps/android/app/src/main/java/ai/openclaw/app/ui/chat/ChatMathRenderer.kt:392
    The renderer enables JavaScript and exposes ChatMathBridge; although the implementation restricts assets and passes JSON data, Android lint blocks the current head with SetJavaScriptEnabled until the security rationale is encoded or the implementation changes.
    Confidence: 0.84

What I checked:

Likely related people:

  • steipete: Authored the merged iOS display-math sibling PR and the mobile polish follow-up context that identifies Android math as remaining work. (role: recent area contributor and likely follow-up owner; confidence: high; commits: 2a741bebb54f, 48e77b6abf5e; files: apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatMarkdownBlockViews.swift, apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatMarkdownBlockSegmenter.swift, apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatInlineMath.swift)
  • Jason (Json): Recent current-main history shows Jason rewrote the Android ChatMarkdown surface this PR extends. (role: recent Android chat surface contributor; confidence: medium; commits: d8ffb1f30746; files: apps/android/app/src/main/java/ai/openclaw/app/ui/chat/ChatMarkdown.kt)
  • Ayaan Zaidi: History search shows Ayaan authored the Android GFM chat markdown renderer that established the Android markdown surface this PR builds on. (role: introduced adjacent Android markdown behavior; confidence: medium; commits: ff4dc050cc84, 5568b393a86d; files: apps/android/app/src/main/java/ai/openclaw/app/ui/chat/ChatMarkdown.kt, apps/android/app/src/test/java/ai/openclaw/app/ui/chat/ChatMarkdownTest.kt)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

How this review workflow works
  • 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.
Review history (1 earlier review cycle)
  • reviewed 2026-07-07T07:09:58.362Z sha ee50ac5 :: needs real behavior proof before merge. :: [P2] Return failure for KaTeX parse errors

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. labels Jul 7, 2026
@steipete steipete self-assigned this Jul 7, 2026
@steipete
steipete force-pushed the feat/android-chat-math-nash branch from ee50ac5 to d054e41 Compare July 7, 2026 09:40

@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: d054e41827

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

maxExpand: 1000,
maxSize: 10,
strict: "ignore",
throwOnError: false,

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 Render malformed math via fallback

For malformed display math, this option prevents the catch path from running: KaTeX's bundled renderer handles throwOnError: false by returning a .katex-error node instead of throwing, so ChatMathBridge.onRenderComplete(..., true) is reached and the chat shows a red KaTeX error image. That breaks the stated/plain-text fallback behavior for inputs like $$\notARealCommand{$$ and differs from the iOS sibling path, which falls back when parsing fails.

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added the merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. label Jul 7, 2026
@steipete
steipete force-pushed the feat/android-chat-math-nash branch from d054e41 to 65748a4 Compare July 7, 2026 10:33
@steipete

steipete commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

Coordination note from the sibling session that authored this branch (now standing down — your head supersedes my local lint fixes, which you made independently and named better):

  • 40356286a30 adds a CHANGELOG.md entry — per root AGENTS.md the changelog is release-only ("release generation owns it; do not edit for normal PRs"). Suggest dropping that commit and keeping the release-note context in the PR body, or ClawSweeper/review will flag it.
  • Landing artifacts for the scripts/pr flow are already written and validated under the canonical checkout's .worktrees/pr-101435/.local (review.json/review.md covering the GPL rejection, asset digest verification, WebView lockdown, and injectable-bridge tests) — review-validate-artifacts 101435 passes; only prepare-run/merge-run remain once CI is green at your head.
  • Heads-up on the landing gates: the earlier pull_request run for this PR is permanently stuck at "failure" (exhausted retries after a GitHub startup_failure wave), and verify-pr-hosted-gates.mjs prefers pull_request runs over dispatched CI release gate runs — a fresh push (new head) is the clean path, which your commits already accomplish.

@steipete

steipete commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Both prior findings are fixed on the current head: malformed KaTeX now reports failure into the raw-text fallback, and the Android WebView lint/security surface is explicitly documented, lifecycle-bounded, and lint-clean. The PR body now includes full Testbox and local API 36 emulator proof; screenshots were inspected locally but not uploaded because image-upload approval was not provided.

@clawsweeper

clawsweeper Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@steipete

steipete commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

Land-ready.

  • Review: repository review artifacts validated with no findings; fresh Codex autoreview clean.
  • Fixes since prior review: malformed/unsupported KaTeX now reports failure into raw fallback; all four Android lint findings are cleared with an Application-owned renderer, required KTX APIs, and narrowly documented suppressions for the intentional asset-only JavaScript/WebView boundary.
  • Focused proof: ChatMathAssetsTest, ChatMathRendererTest, and ChatMarkdownTest passed on Blacksmith Testbox tbx_01kwy132f27yajdr0494ge03j7.
  • Broad proof: Play and ThirdParty unit suites, both debug APK assemblies, both lint lanes, benchmark assembly, app ktlint, and benchmark ktlint passed on the same Testbox.
  • Behavior proof: exact rebased Play APK on a local API 36 emulator rendered valid assistant display math, preserved malformed \frac{ as raw code-style fallback, and stayed responsive across background/foreground. Screenshots were inspected locally and not uploaded because image-upload approval was not provided.
  • Exact-head CI: run 28860358215 passed at 7d77fcd570515e0a290229be448c6112a13ba8b1, including all four Android jobs.
  • Native prepare: OPENCLAW_TESTBOX=1 scripts/pr prepare-run 101435 passed; prepared head equals PR head.
  • Security boundary accepted: bundled asset origin only, restrictive CSP, network blocked, strict asset interception, no HTML interpolation, trust:false, bounded input/expansion/bitmap/cache, completion-only bridge, Application-only process lifetime, weak/detached activity host.
  • Known gap: the first cold user-authored math row briefly used raw fallback until transcript recomposition; the declared product surface is finished assistant messages, which rendered correctly on the first response.

@steipete
steipete merged commit 16348dd into main Jul 7, 2026
81 checks passed
@steipete
steipete deleted the feat/android-chat-math-nash branch July 7, 2026 10:57
@steipete

steipete commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 8, 2026
…penclaw#101435)

* feat(android): render LaTeX display math in chat via bundled KaTeX

* fix(android): preserve fallback for invalid math

* docs(changelog): note Android display math

* Revert "docs(changelog): note Android display math"

This reverts commit 4035628.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: android App: android maintainer Maintainer-authored PR merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant