Skip to content

feat(android): render Mermaid diagrams in chat - #135342

Merged
steipete merged 5 commits into
mainfrom
codex/android-mermaid-diagrams
Sep 1, 2026
Merged

steipete merged 5 commits into
mainfrom
codex/android-mermaid-diagrams

Conversation

@steipete

@steipete steipete commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Related: #135293

What Problem This Solves

Android chat displays Mermaid diagrams as code even when the same message renders as a diagram in the Control UI. Completed mermaid fences now render inline with corner copy/options buttons and a full-screen vector viewer.

Why This Change Was Made

The Control UI and native apps share one pinned Mermaid engine, sandbox, and SVG sanitizer through a private workspace package. Android bundles the renderer for offline use. Math and diagrams share the native lifecycle implementation, with separate warm documents, queues, caches, and resource limits.

Incomplete streaming fences remain code. Failed diagrams retain readable source; temporary failures offer Retry. Android builds generate the assets and required dependency notices from pinned dependencies, including clean CI and release checkouts. This is the first of the requested Android, iOS, then macOS PRs.

User Impact

Users can read diagrams inline, copy or inspect their source, and expand a vector preview with zoom and pan. Rendering needs no network service, Gateway configuration, or additional device permissions. Caches are in-memory only; there is no persistent cache, database schema, migration, or serialized user-state change.

The lifecycle refactor preserves existing math admission. Mermaid alone has the new 32-item queue limit. Synchronous failures drain iteratively, and Activity teardown retires the old WebView before completing interrupted work or admitting its replacement.

Evidence

The final signed APK was built from e016723640697d40398219815f67171b268f5f82 and connected to an isolated real Gateway. Synthetic transcripts were read through the normal native chat flow, without model-provider calls or operator Gateway state. All 2,220 Android/shared/tooling input hashes were verified.

Before Final APK after
Android chat before Mermaid rendering Final Android app with inline Mermaid and compact controls
Final APK expanded vector preview

Final Android full-screen Mermaid preview

  • Final native run: cold launch renders all three architecture nodes/arrows and typeset math. The corner menu switches to source, Copy preserves all 279 source characters plus the original final newline, and full-screen open/close works.
  • Actual Activity lifecycle: two destroy/create/resume cycles, triggered by font scale 1.0 → 1.1 → 1.0, recover diagrams and math. App PID 5238 stays alive; renderer PIDs 5700 → 6616 → 6735 retire their predecessors. Final state has one Activity, two warm WebViews, and one renderer, with no crash or ANR. Font scale and the unsent copy-check draft were restored afterward.
  • Stress/error proof: 40 diagrams render 33 immediately and leave seven readable overflow blocks with Retry; one retry each produces 40/40. The same 40-formula transcript renders 40/40 without Retry. Malformed syntax retains source without Retry; the next valid diagram and math render. Light/dark, source/copy, zoom/pan, and rotation were also exercised.
  • Android tests: 406 chat/controller tests pass with zero skips in the original class order. Earlier focused verification covers 66 renderer, admission, lifecycle, parser, presentation, and notice tests, including 5,000 synchronous failures, plus seven generated Gateway protocol tests.
  • Shared/web/build proof: 14 shared browser boundary tests, 12 web presentation tests, and 26 build-input/CI-routing tests passed, along with scoped type/lint and native inventory validation.
  • Current CI: run 33560788154 is green at the exact final head, including Play, third-party and Wear tests, packaged builds, lint, and the required CI gate. Fresh Codex P0 review completed both passes without findings.

Final APK SHA-256: 2fd62bb764d39b2e2868901045f0f79bcad3aa864a209f9a728c166b3aa1ad52; the installed base.apk has the same hash. Physical Android hardware was unavailable, so native proof used a task-owned emulator. Memory samples are observations, not whole-app memory limits.

The broad 40-item stress and zoom/pan/rotation runs are attributed to APK7, source 9dcc084cb5785a0ff07a4d1eb71ede6cb3940653, SHA-256 c0c6ad12a585acb3e700cc0a5d4cba8e7af8f632a4540ae474ca92e6599b61f1. APK8, source 57e3137809c652c6144149d835f7e04cbdd2a75b, only relocates AndroidX's required method-local WebView feature checks and repeats cold rendering/lifecycle proof. All five feature commits remain patch-identical across the final rebase; the fresh APK9 build and live run above verify the newer upstream native inputs.

40-formula admission regression: before and after repair

The initial candidate rendered 33 formulas and left seven permanently as source. The repaired owner renders all 40 without Retry, message edits, or clearing app data. The after picture is from APK7.

Earlier candidate Repaired candidate
Earlier candidate leaves later math as source Repaired candidate renders formulas 37 through 40

Production LOC, excluding moves: +1,191/-651 (net +540), for native presentation, vector viewing, the shared native boundary, and the rendering owner replacing the old math-only implementation. Tests/support: +894/-238 (net +656). Build/CI: +101; docs: +72; source inventory: +12; lockfile: +16; upstream notices: +1,909.

Review Follow-through

The math-admission and Activity-retirement findings are fixed and covered by failing-before/passing-after tests plus native runs. Mermaid retains its 32-item bound. Math preserves its preexisting admission policy, avoiding a new retry/re-admission state machine. The requested mixed-block coverage is the real 40-diagram transcript with following math, the 40-formula regression, and independent per-kind queues; a synthetic cross-kind queue would not represent production ownership. The persistent-data-model warning does not apply to transient renderer caches and bridge envelopes.

The final local test selection first encountered a Robolectric native-font initialization FileSystemAlreadyExistsException before the test body. A repeat and a repeat in the exact original suite order both passed all 406 tests. No assertion, timeout, graphics mode, or dependency override was changed. The shared state-directory CI failure was repaired at its test owner in #135495 and is included here. The earlier supplemental Gateway abort-fixture ENOTEMPTY cleanup failure did not reproduce in two complete six-case runs; current-head CI is green.

Named follow-ups: the existing Android landscape chat header/composer can consume the transcript viewport (also reproduced on baseline; expanded diagram landscape works); native localization extraction broadly excludes Preview filenames (this production PreviewView and all 12 strings are in inventory); the two non-reproducing test-initialization/cleanup failures above remain recorded for investigation if they recur. iOS and macOS follow separately under #135293.

@clawsweeper

clawsweeper Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: android App: android app: web-ui App: web-ui scripts Repository scripts size: XL maintainer Maintainer-authored PR labels Sep 1, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. 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 Sep 1, 2026
@clawsweeper

clawsweeper Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed September 1, 2026, 12:53 PM ET / 16:53 UTC.

ClawSweeper review

What this changes

This PR adds offline Mermaid diagram rendering to Android chat and moves the existing web renderer into a shared package used by both clients.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

Keep open: the Android feature remains absent from fetched current main, but the new shared queue permanently downgrades existing math blocks to source text when it reaches capacity.

Priority: P2
Reviewed head: 72692bf1d33796107481ee080eb397dd39b24f81
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The feature has substantial implementation and stated package evidence, but a concrete existing math-display regression blocks readiness.
Proof confidence 🌊 off-meta tidepool Not applicable: The review context identifies this as a member-authored PR, so the external-contributor proof gate does not apply; no authority-chain change triggers a narrower proof requirement.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The review context identifies this as a member-authored PR, so the external-contributor proof gate does not apply; no authority-chain change triggers a narrower proof requirement.
Evidence reviewed 5 items Introduced capacity rejection: The PR-introduced coordinator returns TransientFailure once 32 requests are queued; raw-parent comparison shows this new file was added by the feature commit.
Math caller makes transient capacity loss permanent: ChatMathBlock handles TransientFailure identically to permanent Failure and switches to the code fallback without a retry or re-admission path.
Prior finding remains at this head: The reviewed Math renderer blob is identical at the earlier reviewed SHA and current head, so the earlier queue-capacity finding was not addressed by the follow-up commit.
Findings 1 actionable finding [P2] Re-admit math after queue-capacity failures
Security None None.

How this fits together

Android chat detects completed Mermaid Markdown fences and sends them to a bounded local WebView renderer. The renderer returns a sanitized SVG and bitmap for inline chat display and a full-screen preview.

flowchart LR
A[Chat transcript] --> B[Markdown fence parser]
B --> C{Completed Mermaid fence}
C -->|Yes| D[Bounded local renderer]
C -->|No| E[Code block display]
D --> F[Sanitized SVG and bitmap]
F --> G[Chat preview and full-screen viewer]
Loading

Decision needed

Question Recommendation
Should the Android-only native Mermaid rollout be sponsored after its existing math-display regression is repaired? Sponsor Android rollout after repair: Preserve the bounded renderer while fixing transient math re-admission and its regression coverage before review continues.

Why: This draft creates a shared renderer and an ongoing native presentation surface; technical repair alone does not establish the intended rollout scope.

Before merge

  • Re-admit math after queue-capacity failures (P2) - When the new coordinator already has 32 queued distinct renders, it returns TransientFailure; this caller treats it as permanent failure and renders source with no retry. A diagrams-heavy message followed by math therefore regresses existing formula rendering even after capacity drains. Preserve the bound, but re-admit visible math work and cover the mixed-block overflow case. This remains from the previous review cycle.
  • Resolve merge risk (P2) - Merging can leave formula blocks as permanent source fallback in messages with more than 33 distinct rich render requests, even after renderer capacity becomes available.

Findings

  • [P2] Re-admit math after queue-capacity failures — apps/android/app/src/main/java/ai/openclaw/app/ui/chat/ChatMathRenderer.kt:108-110
Agent review details

Security

None.

PR surface

PR surface statistics unavailable: the file list is incomplete.

Review metrics

Metric Value Why it matters
Production versus test delta production +501; tests/support +421; dependency notices +1,909 The feature's substantial production growth is tied to a shared renderer, while its queue boundary still needs a regression repair.
Renderer admission bound 1 active render plus 32 queued distinct requests Further requests receive TransientFailure, which the existing math caller treats as permanent.

Stored data model

Persistent data-model change detected: persistent cache schema: apps/android/app/src/main/java/ai/openclaw/app/ui/chat/ChatRichBlockCoordinator.kt, serialized state: packages/mermaid-renderer/src/native.ts, unknown-data-model-change: packages/mermaid-renderer/src/native.ts, unknown-truncated-pull-files. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Repair transient math admission (recommended)
    Keep the 32-item bound but automatically re-admit visible math after a temporary capacity result, with a mixed rich-block regression test.
  2. Pause the native rollout
    Defer this draft if the renderer cannot preserve existing math rendering under bounded capacity.

Technical review

Best possible solution:

Keep the queue bound, but distinguish temporary admission loss from a permanent render failure and automatically re-admit visible math work when capacity frees.

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

Yes, from source: submit more than 33 distinct rich blocks in one composed message, including a later math block. The coordinator reports TransientFailure and the math caller immediately commits the code fallback; execution was not possible because pnpm is unavailable in this review environment.

Is this the best way to solve the issue?

No. Sharing the renderer is a coherent direction, but treating temporary queue admission failure as permanent math-render failure is not the maintainable solution.

Full review comments:

  • [P2] Re-admit math after queue-capacity failures — apps/android/app/src/main/java/ai/openclaw/app/ui/chat/ChatMathRenderer.kt:108-110
    When the new coordinator already has 32 queued distinct renders, it returns TransientFailure; this caller treats it as permanent failure and renders source with no retry. A diagrams-heavy message followed by math therefore regresses existing formula rendering even after capacity drains. Preserve the bound, but re-admit visible math work and cover the mixed-block overflow case. This remains from the previous review cycle.
    Confidence: 0.98

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 520f6f7d22af.

Labels

Label changes:

  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp. Replaced prior rating: 🦪 silver shellfish.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.

Label justifications:

  • P2: The source establishes an existing Android math-display regression under a bounded, high-content chat scenario.
  • merge-risk: 🚨 availability: The new renderer capacity limit can make already-supported math rendering unavailable until the user changes the message or view.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp. Replaced prior rating: 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: The review context identifies this as a member-authored PR, so the external-contributor proof gate does not apply; no authority-chain change triggers a narrower proof requirement.

Evidence

What I checked:

Likely related people:

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

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Handle transient admission separately from permanent math-render failure and automatically re-admit the visible block.
  • Add a caller-boundary test with at least 34 distinct mixed Mermaid and math requests.

Rating scale

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

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

Workflow

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

History

Review history (1 earlier review cycle)
  • reviewed 2026-09-01T16:38:53.909Z sha 62fa2320512f960b8ce7381e35f9f345d544f991 :: found issues before merge. :: [P2] Preserve visible math blocks when the render queue fills | [P2] Retire the renderer when its Activity is destroyed

@steipete
steipete marked this pull request as ready for review September 1, 2026 16:50
@steipete
steipete requested a review from a team as a code owner September 1, 2026 16:50
@github-actions github-actions Bot added the dependencies-changed PR changes dependency-related files label Sep 1, 2026
@github-actions

github-actions Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

Dependency Guard

This PR changes dependency-related files. Maintainers should confirm these changes are intentional.

Changed files:

  • packages/mermaid-renderer/package.json
  • pnpm-lock.yaml
  • ui/package.json

Maintainer follow-up:

  • Review whether the dependency changes are intentional.
  • Inspect resolved package deltas when lockfiles or workspace dependency policy changes are present.
  • Treat pnpm-lock.yaml and package-lock.json diffs as dependency security-review surfaces.
  • Run pnpm deps:changes:report -- --base-ref origin/main --markdown /tmp/dependency-changes.md --json /tmp/dependency-changes.json locally for detailed release-style evidence.

@github-actions

github-actions Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Dependency graph changes noted

This PR includes dependency graph changes. The dependency guard is informational because the PR author is a repository admin, a member of @openclaw/openclaw-secops, or an OpenClaw organization member with Maintain or Admin repository access.

  • Current SHA: e016723640697d40398219815f67171b268f5f82
  • Trusted actor: @steipete
  • Trusted role: pull request author; openclaw-secops

Security review is still recommended before merge when the dependency graph change is intentional.

@steipete
steipete force-pushed the codex/android-mermaid-diagrams branch from 72692bf to 9dcc084 Compare September 1, 2026 17:10
@steipete

steipete commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

The review findings are addressed in the final native artifact, built from 9dcc084cb5785a0ff07a4d1eb71ede6cb3940653 (the subsequent commit is browser-test typing/lint only).

Math and Mermaid have separate renderer instances and queues. The 32-queued-diagram bound remains; math preserves its prior admission behavior. The same persisted 40-formula message that previously left seven permanent source blocks now renders 40/40 without retry or edits. A 5,000-pending-job regression also proves synchronous host loss drains without stack overflow.

Activity destruction now retires the old document before completion and replacement. Live font-scale changes 1.0 → 1.1 → 1.0 produced two actual destroy/create/resume cycles, retired both old renderer processes, and recovered diagrams plus math in the same app process. The final hierarchy returns to two warm WebViews and one Activity. Queue overflow exposes Retry; malformed syntax exposes source without Retry; both paths recover for subsequent valid content.

The PR body now contains the final before/after diagram and math screenshots, 66 focused Android tests, seven generated protocol tests, browser proof, exact APK digest, and CI follow-through. The rollout order is the maintainer's explicit Android → iOS → macOS request. All renderer caches are in memory; no database/schema or persistent-state change is present.

@steipete
steipete force-pushed the codex/android-mermaid-diagrams branch from ec42739 to 597af72 Compare September 1, 2026 17:42
@openclaw-barnacle openclaw-barnacle Bot added the cli CLI command changes label Sep 1, 2026
@steipete
steipete force-pushed the codex/android-mermaid-diagrams branch from 57e3137 to 3a2fff5 Compare September 1, 2026 18:46
@openclaw-barnacle openclaw-barnacle Bot removed the cli CLI command changes label Sep 1, 2026
@steipete
steipete force-pushed the codex/android-mermaid-diagrams branch from 3a2fff5 to e016723 Compare September 1, 2026 21:23
@steipete steipete self-assigned this Sep 1, 2026
@steipete
steipete merged commit ba7b99e into main Sep 1, 2026
310 checks passed
@steipete
steipete deleted the codex/android-mermaid-diagrams branch September 1, 2026 21:53
@steipete

steipete commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 2, 2026
* feat(android): render Mermaid diagrams in chat

* fix(android): finish diagram preview and retry feedback

* fix(android): preserve rich renderer recovery and lifecycle

* test(mermaid): type browser fixture receivers

* fix(android): gate rich renderer WebView allocation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: android App: android app: web-ui App: web-ui dependencies-changed PR changes dependency-related files docs Improvements or additions to documentation maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P2 Normal backlog priority with limited blast radius. 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