Skip to content

Matrix: render LaTeX for Element Desktop by emitting data-mx-maths in formatted_body#20286

Open
eloklam wants to merge 3 commits intoopenclaw:mainfrom
eloklam:fix/matrix-latex-data-mx-maths
Open

Matrix: render LaTeX for Element Desktop by emitting data-mx-maths in formatted_body#20286
eloklam wants to merge 3 commits intoopenclaw:mainfrom
eloklam:fix/matrix-latex-data-mx-maths

Conversation

@eloklam
Copy link

@eloklam eloklam commented Feb 18, 2026

Summary

  • Problem: Matrix messages containing LaTeX (........., .........) were sent as plain Markdown HTML (<p>.........</p>), which Element does not render as math.
  • Why it matters: Users see raw LaTeX text instead of rendered equations, making math-heavy chats difficult to read. Element is the most used and feature-riched client for Matrix.
  • What changed: Updated extensions/matrix/src/matrix/send/formatting.ts to detect inline/block LaTeX and emit Element-compatible data-mx-maths markup in formatted_body.
  • What did NOT change (scope boundary): No changes to non-math Markdown rendering behavior, no protocol-level Matrix API changes, no config schema changes.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

User-visible / Behavior Changes

  • Matrix messages containing LaTeX now render in Element when sent by OpenClaw:
  • Inline math: $$x^2$$<span data-mx-maths="x^2"><code>x^2</code></span>
  • Display math: E=mc2E = mc^2E=mc2<div data-mx-maths="E = mc^2"><code>E = mc^2</code></div>
  • Non-math messages are unchanged.

Security Impact (required)

  • New permissions/capabilities? (No)
  • Secrets/tokens handling changed? (No)
  • New/changed network calls? (No)
  • Command/tool execution surface changed? (No)
  • Data access scope changed? (No)

Repro + Verification

Environment

  • OS: Ubuntu 24.04.4 LTS
  • Runtime/container: OpenClaw gateway local runtime
  • Model/provider: ChatGPT Codex 5.3
  • Integration/channel (if any): Matrix (Element Desktop)
  • Relevant config (redacted): Matrix plugin enabled; standard org.matrix.custom.html message formatting path

Steps

  1. Send a Matrix message via OpenClaw containing E=mc2E = mc^2E=mc2.
  2. Inspect sent event content.formatted_body.
  3. Open message in Element Desktop and verify rendering.
  4. Repeat for inline example $$x^2$$ embedded in normal text.

Expected

  • formatted_body contains data-mx-maths markup for detected math.
  • Element renders equations as math, not raw $ delimiters.

Actual

  • Before fix: formatted_body contained <p>E=mc2E = mc^2E=mc2</p> (raw text shown in Element).
  • After fix: formatted_body contains data-mx-maths HTML and renders correctly.

Evidence

Attach at least one:

  • Failing test/log before + passing after
  • Trace/log snippets
  • [] Screenshot/recording
  • Perf numbers (if relevant)

Human Verification (required)

What you personally verified (not just CI), and how:

  • Verified scenarios:

  • Display math-only message renders in Element.

  • Inline math in mixed text renders.

  • Normal non-math markdown remains unchanged.

  • Edge cases checked:

  • Multiple math expressions in one message.

  • Multiline display-math capture with ..........

  • What you did not verify:

  • Full escaped-dollar edge cases (e.g. \$) across all clients.

  • Behavior in non-Element Matrix clients.

Compatibility / Migration

  • Backward compatible? (Yes)
  • Config/env changes? (No)
  • Migration needed? (No)

Failure Recovery (if this breaks)

  • How to disable/revert this change quickly:

  • Revert commit affecting extensions/matrix/src/matrix/send/formatting.ts.

  • Files/config to restore:

  • extensions/matrix/src/matrix/send/formatting.ts

  • Known bad symptoms reviewers should watch for:

  • Raw placeholders like OC_MATH_BLOCK_* appearing in chat.

  • Missing or malformed formatted_body.

  • Regressions in non-math markdown formatting.

Risks and Mitigations

List only real risks for this PR. Add/remove entries as needed. If none, write None.
None

Greptile Summary

This PR adds LaTeX math rendering support for Matrix messages in Element by detecting $...$ (inline) and $$...$$ (block) delimiters and converting them to Element-compatible data-mx-maths HTML markup. The implementation uses a placeholder-based approach: math expressions are extracted before markdown rendering, then re-injected as proper HTML elements afterward.

  • Critical: Inline math regex false-positives on currency text. The pattern \$([^\n$]+?)\$ will match text like $10 and $20 as a single math expression, corrupting non-math messages. This needs word-boundary guards (e.g. (?<!\w)\$...\$(?!\w)) to avoid treating dollar amounts as LaTeX delimiters.
  • No test coverage for the new extractMath/injectMath logic — the existing test file only covers markdownToMatrixHtml. Given the regex edge cases, tests are important for confidence in this change.
  • The overall architecture (extract → render markdown → inject) is reasonable and the escapeHtml usage correctly prevents injection in the data-mx-maths attribute.

Confidence Score: 2/5

  • The inline math regex will corrupt messages containing dollar amounts, which is a common real-world scenario
  • Score of 2 reflects that while the approach is architecturally sound, the inline math regex has a confirmed false-positive bug with currency text (e.g. "$10 and $20" gets treated as math). This would corrupt normal messages in production. Additionally, there are no tests for the new logic.
  • extensions/matrix/src/matrix/send/formatting.ts — the inline math regex at line 51 needs word-boundary guards to prevent false positives on currency text

Last reviewed commit: 3e845bd

(2/5) Greptile learns from your feedback when you react with thumbs up/down!

@openclaw-barnacle openclaw-barnacle bot added channel: matrix Channel integration: matrix size: S labels Feb 18, 2026
Copy link
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

1 file reviewed, 2 comments

Edit Code Review Agent Settings | Greptile

Comment on lines +40 to +57
function extractMath(markdown: string): { text: string; blocks: string[]; inlines: string[] } {
const blocks: string[] = [];
const inlines: string[] = [];
let text = markdown;

text = text.replace(/\$\$([\s\S]+?)\$\$/g, (_m, latex) => {
const id = blocks.length;
blocks.push(String(latex));
return `OC_MATH_BLOCK_${id}`;
});

text = text.replace(/\$([^\n$]+?)\$/g, (_m, latex) => {
const id = inlines.length;
inlines.push(String(latex));
return `OC_MATH_INLINE_${id}`;
});

return { text, blocks, inlines };
Copy link
Contributor

Choose a reason for hiding this comment

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

No tests for the new math extraction/injection logic

The existing format.test.ts covers markdownToMatrixHtml but there are no tests for extractMath, injectMath, or the updated applyMatrixFormatting. Given the regex edge cases involved (currency false positives, escaped dollars, mixed inline/block), this logic needs test coverage. Consider adding tests for at least:

  • Basic inline math: $x^2$
  • Basic block math: $$E = mc^2$$
  • Currency text not treated as math: costs $10 and $20
  • Mixed content: The equation $a+b$ and the formula $$c+d$$
  • No math (passthrough): Hello world
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/matrix/src/matrix/send/formatting.ts
Line: 40:57

Comment:
**No tests for the new math extraction/injection logic**

The existing `format.test.ts` covers `markdownToMatrixHtml` but there are no tests for `extractMath`, `injectMath`, or the updated `applyMatrixFormatting`. Given the regex edge cases involved (currency false positives, escaped dollars, mixed inline/block), this logic needs test coverage. Consider adding tests for at least:
- Basic inline math: `$x^2$`
- Basic block math: `$$E = mc^2$$`
- Currency text not treated as math: `costs $10 and $20`
- Mixed content: `The equation $a+b$ and the formula $$c+d$$`
- No math (passthrough): `Hello world`

How can I resolve this? If you propose a fix, please make it concise.

eloklam and others added 2 commits February 18, 2026 22:32
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
@openclaw-barnacle
Copy link

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle bot added the stale Marked as stale due to inactivity label Feb 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: matrix Channel integration: matrix size: S stale Marked as stale due to inactivity

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Matrix: Element Desktop doesn’t render LaTeX from OpenClaw messages (missing data-mx-maths in formatted_body)

1 participant