openwork icon indicating copy to clipboard operation
openwork copied to clipboard

[Feature Request] Native LaTeX/MathJax rendering for chat messages

Open dungphan0038 opened this issue 4 months ago • 3 comments

Description

Currently, OpenWork's chat interface renders LaTeX math expressions (wrapped in $$...$$ or $...$) as plain monospace text instead of typeset mathematical notation. This makes it difficult for users to discuss mathematical content — formulas, equations, integrals, matrices — within sessions.

Expected Behavior

When a user writes LaTeX math expressions in a chat message, they should be rendered as formatted mathematical notation, similar to how GitHub renders math in Markdown (via MathJax or KaTeX).

For example:

  • $$\int_0^\infty e^{-x^2} \, dx = \frac{\sqrt{\pi}}{2}$$ should render as a display equation
  • $E = mc^2$ should render as inline math

Actual Behavior

LaTeX expressions appear as plain text like $$x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$ without any rendering.

Workaround (DevTools Snippet)

I created a JavaScript snippet that can be run from DevTools (Sources > Snippets) to inject MathJax 3 into the page. It works reasonably well for most formulas but has limitations (detailed below).

How to use the workaround:

  1. Open DevTools: Ctrl+Shift+I / Cmd+Option+I
  2. Sources tab → Snippets → New snippet
  3. Paste the code from openwork-mathjax-inject.js → Save → Run

Console output when running:

[MathJax] Loading from CDN...
[MathJax] Ready!
[MathJax] Injected successfully!
[MathJax] Watching for new messages...

Features of the workaround:

  • Renders $$...$$ as display math, left-aligned
  • Renders $...$ as inline math
  • MutationObserver with debounce (500ms) to auto-render new messages
  • Exposes window.renderMath() for manual re-rendering in Console
  • CSS overrides to prevent line breaks and ensure proper alignment
  • Fallback CDN (cdnjs.cloudflare.com) if primary CDN is unreachable

Workaround code: (see attached file openwork-mathjax-inject.js)

Known Limitations of the Workaround

Despite solving basic math rendering, the following LaTeX environments fail to render multi-line content — everything collapses into a single line:

  • \begin{cases} ... \\ ... \end{cases} — system of equations
  • \begin{vmatrix} ... \\ ... \end{vmatrix} — matrix determinant
  • \begin{bmatrix} ... \\ ... \end{bmatrix} — bracketed matrix
  • \begin{pmatrix} ... \\ ... \end{pmatrix} — parenthesized matrix

The \\ line-break operator within these environments is not being processed correctly. The \begin{aligned} environment with & alignment markers works, but true matrix/cases environments do not render properly.

I suspect this is because MathJax is injected into a React-rendered DOM where text nodes are split across multiple elements, or the \\ syntax is being mangled during the $$ → \[ preprocessing step.

Suggested Solution

It would be great if OpenWork could add native MathJax or KaTeX support to the chat message renderer. This would:

  1. Eliminate the need for DevTools workarounds
  2. Render all LaTeX environments correctly (matrices, cases, aligned, etc.)
  3. Provide a seamless experience for users discussing mathematics in their sessions

A good reference implementation would be Obsidian's MathJax support or GitHub's native math rendering.

Attachments

  • openwork-mathjax-inject.js — The workaround DevTools Snippet for MathJax injection

dungphan0038 avatar Jul 06 '26 11:07 dungphan0038

Workaround Code — Full Snippet (openwork-mathjax-inject.js)

Copy this into a DevTools Snippet (Sources > Snippets) and run it:

/**
 * =========================================================
 *  OpenWork — MathJax Inject Snippet
 *  ----------------------------------
 *  DevTools snippet to render LaTeX math in chat messages.
 *
 *  Usage:
 *    1. Open DevTools: Ctrl+Shift+I (Win/Linux) / Cmd+Option+I (Mac)
 *    2. Sources tab > Snippets > New snippet
 *    3. Paste this code, save (Ctrl+S)
 *    4. Right-click > Run (or Ctrl+Enter)
 * =========================================================
 */
(function () {
  'use strict';

  if (window.__owMathInjected) {
    console.log('[MathJax] Already loaded. Re-rendering...');
    window.renderMath();
    return;
  }

  // ─── CSS Overrides ──────────────────────────────────────
  var css = document.createElement('style');
  css.id = 'ow-math-css';
  css.textContent = [
    /* Display math: left-aligned with horizontal scroll */
    'mjx-container[display="true"] { display: block !important; text-align: left !important; margin: 6px 0 !important; }',
    'mjx-container[display="true"] svg { margin-left: 0 !important; margin-right: auto !important; }',
    /* Prevent line breaks inside rendered math */
    '.MathJax svg { display: inline-block !important; vertical-align: middle !important; }',
    '.MathJax_Display { display: inline-block !important; margin: 8px 0 !important; text-align: left !important; overflow-x: auto; overflow-y: hidden; max-width: 100%; }',
    '.message-content .MathJax_Display, [class*="message"] .MathJax_Display { word-break: normal !important; white-space: nowrap !important; }',
    /* Matrix/table elements */
    '.MathJax table { display: inline-table !important; vertical-align: middle !important; }',
    '.MathJax .mjx-table { display: inline-table !important; }',
    '.MathJax .mjx-mtable { display: inline-block !important; }',
    /* Bullet point compatibility */
    'li .MathJax_Display { display: inline !important; }',
    'li .MathJax svg { display: inline !important; }',
  ].join('\n');
  document.head.appendChild(css);

  // ─── MathJax Configuration ──────────────────────────────
  window.MathJax = {
    tex: {
      inlineMath: [['$', '$']],
      displayMath: [['$$', '$$']],
      processEscapes: true,
      processEnvironments: true,
      tags: 'ams',
    },
    options: {
      enableMenu: false,
      ignoreHtmlClass: 'no-mathjax',
      processHtmlClass: '',
      renderEmpty: true,
    },
    svg: {
      fontCache: 'global',
      scale: 1.0,
    },
    startup: {
      typeset: true,
      pageReady: function () {
        console.log('[MathJax] Ready!');
        return window.MathJax.typeset();
      },
    },
  };

  // ─── Helper: convert $$ → \[ \] ────────────────────────
  function preprocessDisplayMath(html) {
    return html.replace(/\$\$([\s\S]+?)\$\$/g, function (m, tex) {
      return '\\[' + tex.trim() + '\\]';
    });
  }

  // ─── Inject MathJax from CDN ────────────────────────────
  var script = document.createElement('script');
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js';
  script.async = true;

  script.onload = function () {
    window.__owMathInjected = 1;
    console.log('[MathJax] Injected successfully!');

    // ── DOM Preprocessing ──
    function preprocessDOM() {
      var walker = document.createTreeWalker(
        document.body,
        NodeFilter.SHOW_TEXT
      );
      var nodes = [];
      while (walker.nextNode()) {
        var node = walker.currentNode;
        if (node.nodeValue && node.nodeValue.includes('$$')) {
          nodes.push(node);
        }
      }
      nodes.forEach(function (node) {
        var text = node.nodeValue;
        var processed = text.replace(/\$\$([\s\S]+?)\$\$/g, function (m, tex) {
          return '\\[' + tex.trim() + '\\]';
        });
        processed = processed.replace(/\$([^\$\n]+?)\$/g, function (m, tex) {
          return '\\(' + tex.trim() + '\\)';
        });
        if (processed !== text) {
          node.nodeValue = processed;
        }
      });
    }

    // ── Render ──
    function doRender() {
      try {
        preprocessDOM();
        if (window.MathJax && window.MathJax.typesetPromise) {
          return window.MathJax.typesetPromise();
        }
      } catch (e) {
        console.warn('[MathJax] Render error:', e);
      }
    }

    // ── MutationObserver (debounced) ──
    var timer;
    var observer = new MutationObserver(function (mutations) {
      var hasNew = mutations.some(function (m) {
        return m.addedNodes.length > 0;
      });
      if (hasNew) {
        clearTimeout(timer);
        timer = setTimeout(doRender, 500);
      }
    });

    observer.observe(document.body, { childList: true, subtree: true });
    console.log('[MathJax] Watching for new messages...');

    // ── Expose global re-render function ──
    window.renderMath = doRender;

    // ── First render ──
    doRender();
  };

  script.onerror = function () {
    console.error('[MathJax] Failed to load from CDN. Check your internet connection.');
    // Try fallback CDN
    var fallback = document.createElement('script');
    fallback.src =
      'https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-svg.min.js';
    fallback.async = true;
    fallback.onload = function () {
      window.__owMathInjected = 1;
      console.log('[MathJax] Injected successfully! (fallback CDN)');
      window.MathJax.typeset();
    };
    document.head.appendChild(fallback);
  };

  document.head.appendChild(script);
  console.log('[MathJax] Loading from CDN...');
})();

dungphan0038 avatar Jul 06 '26 11:07 dungphan0038

Thank you @PriyeshPandey2000 👍

dungphan0038 avatar Jul 07 '26 07:07 dungphan0038

closed due to age, please reopen and tag me if still valid

OmarMcAdam avatar Oct 28 '26 22:10 OmarMcAdam