Open-source AI browser agent for Chrome and Firefox (monorepo) ðŸ§
JavaScript ai-agentai-agentsai-toolsbrowser-aibrowser-automationbrowser-extensionchrome-aichrome-devtoolschrome-extensionchrome-extensionsfirefox-addonfirefox-addonsfirefox-extensionfirefox-extensionsgemmagemma4minimaxoffline-aioffline-llmqwen
Render inline $...$ math in the side panel
Emre Sokullu1feb4f522fd0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c49050dd0..4d32542eb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,7 @@ This changelog was generated from the repository Git history and release tags. V- WebBrain Companion planning: planner and classifier calls now ask for no thinking (`reasoning_effort: "none"`). Companion maps it per model (off where the model allows it, the lowest level where it cannot, dropped for models without thinking), and its local Bonsai 2 model now accepts it, so planning there no longer runs at the model's default xhigh reasoning.### Fixed+- Side panel math: inline formulas written between single dollar signs, such as `$\rightarrow$`, `$W \cdot S \cdot H$` or `$O(n^2)$`, now render with KaTeX instead of showing the raw TeX. A `$...$` span renders only when it reads as TeX (a command, `^`, `_` or braces, or a single letter), so prices such as $5 to $10 stay text, and saved history keeps each formula as its TeX source. Both builds.- WebBrain Companion: its local Bonsai 2 model no longer fails a request that asks for `high` reasoning effort, which clients such as Cline, Kilo and Open WebUI send. Bonsai 2's chat template accepts only `low`, `medium` and `xhigh`, so Companion now declares just those, and its proxy sends `high` as `medium`, the nearest declared level.## [45.0.1] - 2026-10-29diff --git a/src/chrome/src/ui/history-text.js b/src/chrome/src/ui/history-text.jsindex c72b3b6d6..dc19024a6 100644--- a/src/chrome/src/ui/history-text.js+++ b/src/chrome/src/ui/history-text.js@@ -19,6 +19,20 @@ const BLOCK_TAGS = new Set([const SKIPPED_TAGS = new Set(['SCRIPT', 'STYLE', 'TEMPLATE']);+// The TeX source KaTeX keeps in <annotation encoding="application/x-tex">.+function texAnnotation(node) {+ for (const child of Array.from(node?.childNodes || [])) {+ if (!child || child.nodeType !== ELEMENT_NODE) continue;+ if (String(child.tagName || '').toUpperCase() === 'ANNOTATION'+ && child.getAttribute?.('encoding') === 'application/x-tex') {+ return String(child.textContent ?? '');+ }+ const found = texAnnotation(child);+ if (found !== null) return found;+ }+ return null;+}+function elementChildren(node) {return Array.from(node?.childNodes || []).filter((child) => child && child.nodeType === ELEMENT_NODE);}@@ -102,6 +116,17 @@ export function historyTextFromElement(root, { markdown = true } = {}) {const tagName = String(node.tagName || '').toUpperCase();if (SKIPPED_TAGS.has(tagName)) return;if (node.classList?.contains?.('code-block-header')) return;+ // KaTeX output holds the formula three times (MathML, its TeX source and+ // the visible HTML). Save the source with delimiters the panel renders+ // again.+ const display = node.classList?.contains?.('katex-display');+ if (display || node.classList?.contains?.('katex')) {+ const tex = texAnnotation(node);+ if (tex !== null) {+ output += display ? `$$${tex}$$` : `\\(${tex}\\)`;+ return;+ }+ }if (tagName === 'BR') {// Every rendered <br> represents a source newline, including consecutive// <br>s used for blank lines. Do not deduplicate these hard breaks.diff --git a/src/chrome/src/ui/markdown-render.js b/src/chrome/src/ui/markdown-render.jsindex 53e6410b9..21f529681 100644--- a/src/chrome/src/ui/markdown-render.js+++ b/src/chrome/src/ui/markdown-render.js@@ -949,3 +949,52 @@ export function renderMarkdownTables(text) {return rendered.join('\n');}++// A TeX command (\rightarrow, \frac) or a sign only math uses.+const TEX_COMMAND = /\\[A-Za-z]+/;+const TEX_SIGNS = /[\^_{}]/;++/**+ * Find single-dollar inline math ($\rightarrow$, $O(n^2)$, $x$) and replace+ * each span with render(tex). Single dollars are mostly prices, so a span+ * counts only when it reads as TeX, following Pandoc's rule for $ math:+ * - the opening $ is followed by a non-space and the closing $ comes after+ * one, on the same line; \$ is a literal dollar;+ * - the closing $ is not followed by a digit ("$5 or $10"), unless the span+ * holds a TeX command ("$\sim$5 GB");+ * - the span holds a TeX command, ^, _, { or }, or is a single letter.+ * $$display$$ math is left for the KaTeX pass.+ */+export function replaceInlineDollarMath(text, render) {+ const source = String(text == null ? '' : text);+ let output = '';+ let index = 0;+ let from = 0;+ while (from < source.length) {+ const open = source.indexOf('$', from);+ if (open < 0) break;+ if (source[open + 1] === '$') {+ const close = source.indexOf('$$', open + 2);+ from = close < 0 ? open + 2 : close + 2;+ continue;+ }+ from = open + 1;+ if ((open > 0 && source[open - 1] === '\\') || !source[open + 1] || /\s/.test(source[open + 1])) continue;+ let close = -1;+ for (let at = open + 1; at < source.length && source[at] !== '\n'; at++) {+ if (source[at] === '$' && source[at - 1] !== '\\') {+ close = at;+ break;+ }+ }+ if (close < 0) continue;+ const tex = source.slice(open + 1, close);+ const after = source[close + 1] || '';+ const readsAsTex = TEX_COMMAND.test(tex) || TEX_SIGNS.test(tex) || /^[A-Za-z]$/.test(tex);+ if (/\s/.test(source[close - 1]) || after === '$' || tex.length > 300 || !readsAsTex+ || (/\d/.test(after) && !TEX_COMMAND.test(tex))) continue;+ output += source.slice(index, open) + render(tex);+ index = from = close + 1;+ }+ return output + source.slice(index);+}diff --git a/src/chrome/src/ui/sidepanel.js b/src/chrome/src/ui/sidepanel.jsindex 7cc23b4a4..49ad29549 100644--- a/src/chrome/src/ui/sidepanel.js+++ b/src/chrome/src/ui/sidepanel.js@@ -17,7 +17,7 @@ import { t, getLocale, setLocale, LANGUAGES, applyDOMTranslations, translationsFimport { CAPABILITY_LABEL, PERMISSION_GATE_SESSION_OFF_KEY, uploadApprovalCard } from '../agent/permission-gate.js';import { sanitizeMarkdownLinks, linkifyPlainUrls } from './markdown-link.js';import { installChatLinkIcons } from './chat-link-icons.js';-import { codeFenceLanguage, createMarkdownPlaceholders, highlightCode, renderMarkdownBlockquotes, renderMarkdownHeadings, renderMarkdownTables, replaceMarkdownCodeFences } from './markdown-render.js';+import { codeFenceLanguage, createMarkdownPlaceholders, highlightCode, renderMarkdownBlockquotes, renderMarkdownHeadings, renderMarkdownTables, replaceInlineDollarMath, replaceMarkdownCodeFences } from './markdown-render.js';import { applyMode, loadMode, watch } from './theme.js';import {UI_SCALE_LEVELS,@@ -15069,11 +15069,11 @@ function scheduleMathRender() {const target = document.getElementById('messages');if (!target) return;window.renderMathInElement(target, {- // Delimiters in order of precedence. We deliberately do NOT enable- // single-`$...$` as an inline-math delimiter: LLM responses very- // often contain dollar amounts ("$1,263 ... $2,526") and KaTeX- // would pair them up and italicize the prose between them. Users- // who genuinely want inline math can use \\( ... \\) or $$...$$.+ // Delimiters in order of precedence. Single `$...$` is NOT one:+ // LLM responses often contain dollar amounts ("$1,263 ... $2,526")+ // and KaTeX would pair them up and italicize the prose between them.+ // formatMarkdown turns $...$ that reads as TeX into \\( ... \\)+ // first (replaceInlineDollarMath).delimiters: [{ left: '$$', right: '$$', display: true },{ left: '\\[', right: '\\]', display: true },@@ -15121,6 +15121,13 @@ function formatMarkdown(text, options = {}) {return placeholders.add(`<code>${escaped}</code>`, code);});+ // 2b. Inline $...$ that reads as TeX ($\rightarrow$, $O(n^2)$) becomes+ // \(...\) text for the KaTeX pass, kept away from emphasis and escaping.+ // Prices stay text (replaceInlineDollarMath has the rules).+ if (enhance) {+ text = replaceInlineDollarMath(text, tex => placeholders.add(escapeHtml(`\\(${tex}\\)`), `$${tex}$`));+ }+// 3. Escape HTML in the remaining texttext = text.replace(/&/g, '&')diff --git a/src/firefox/src/ui/history-text.js b/src/firefox/src/ui/history-text.jsindex c72b3b6d6..dc19024a6 100644--- a/src/firefox/src/ui/history-text.js+++ b/src/firefox/src/ui/history-text.js@@ -19,6 +19,20 @@ const BLOCK_TAGS = new Set([const SKIPPED_TAGS = new Set(['SCRIPT', 'STYLE', 'TEMPLATE']);+// The TeX source KaTeX keeps in <annotation encoding="application/x-tex">.+function texAnnotation(node) {+ for (const child of Array.from(node?.childNodes || [])) {+ if (!child || child.nodeType !== ELEMENT_NODE) continue;+ if (String(child.tagName || '').toUpperCase() === 'ANNOTATION'+ && child.getAttribute?.('encoding') === 'application/x-tex') {+ return String(child.textContent ?? '');+ }+ const found = texAnnotation(child);+ if (found !== null) return found;+ }+ return null;+}+function elementChildren(node) {return Array.from(node?.childNodes || []).filter((child) => child && child.nodeType === ELEMENT_NODE);}@@ -102,6 +116,17 @@ export function historyTextFromElement(root, { markdown = true } = {}) {const tagName = String(node.tagName || '').toUpperCase();if (SKIPPED_TAGS.has(tagName)) return;if (node.classList?.contains?.('code-block-header')) return;+ // KaTeX output holds the formula three times (MathML, its TeX source and+ // the visible HTML). Save the source with delimiters the panel renders+ // again.+ const display = node.classList?.contains?.('katex-display');+ if (display || node.classList?.contains?.('katex')) {+ const tex = texAnnotation(node);+ if (tex !== null) {+ output += display ? `$$${tex}$$` : `\\(${tex}\\)`;+ return;+ }+ }if (tagName === 'BR') {// Every rendered <br> represents a source newline, including consecutive// <br>s used for blank lines. Do not deduplicate these hard breaks.diff --git a/src/firefox/src/ui/markdown-render.js b/src/firefox/src/ui/markdown-render.jsindex 53e6410b9..21f529681 100644--- a/src/firefox/src/ui/markdown-render.js+++ b/src/firefox/src/ui/markdown-render.js@@ -949,3 +949,52 @@ export function renderMarkdownTables(text) {return rendered.join('\n');}++// A TeX command (\rightarrow, \frac) or a sign only math uses.+const TEX_COMMAND = /\\[A-Za-z]+/;+const TEX_SIGNS = /[\^_{}]/;++/**+ * Find single-dollar inline math ($\rightarrow$, $O(n^2)$, $x$) and replace+ * each span with render(tex). Single dollars are mostly prices, so a span+ * counts only when it reads as TeX, following Pandoc's rule for $ math:+ * - the opening $ is followed by a non-space and the closing $ comes after+ * one, on the same line; \$ is a literal dollar;+ * - the closing $ is not followed by a digit ("$5 or $10"), unless the span+ * holds a TeX command ("$\sim$5 GB");+ * - the span holds a TeX command, ^, _, { or }, or is a single letter.+ * $$display$$ math is left for the KaTeX pass.+ */+export function replaceInlineDollarMath(text, render) {+ const source = String(text == null ? '' : text);+ let output = '';+ let index = 0;+ let from = 0;+ while (from < source.length) {+ const open = source.indexOf('$', from);+ if (open < 0) break;+ if (source[open + 1] === '$') {+ const close = source.indexOf('$$', open + 2);+ from = close < 0 ? open + 2 : close + 2;+ continue;+ }+ from = open + 1;+ if ((open > 0 && source[open - 1] === '\\') || !source[open + 1] || /\s/.test(source[open + 1])) continue;+ let close = -1;+ for (let at = open + 1; at < source.length && source[at] !== '\n'; at++) {+ if (source[at] === '$' && source[at - 1] !== '\\') {+ close = at;+ break;+ }+ }+ if (close < 0) continue;+ const tex = source.slice(open + 1, close);+ const after = source[close + 1] || '';+ const readsAsTex = TEX_COMMAND.test(tex) || TEX_SIGNS.test(tex) || /^[A-Za-z]$/.test(tex);+ if (/\s/.test(source[close - 1]) || after === '$' || tex.length > 300 || !readsAsTex+ || (/\d/.test(after) && !TEX_COMMAND.test(tex))) continue;+ output += source.slice(index, open) + render(tex);+ index = from = close + 1;+ }+ return output + source.slice(index);+}diff --git a/src/firefox/src/ui/sidepanel.js b/src/firefox/src/ui/sidepanel.jsindex fa9721472..d6f0ef4f2 100644--- a/src/firefox/src/ui/sidepanel.js+++ b/src/firefox/src/ui/sidepanel.js@@ -16,7 +16,7 @@ import { t, getLocale, setLocale, LANGUAGES, applyDOMTranslations, translationsFimport { CAPABILITY_LABEL, PERMISSION_GATE_SESSION_OFF_KEY, uploadApprovalCard } from '../agent/permission-gate.js';import { sanitizeMarkdownLinks, linkifyPlainUrls } from './markdown-link.js';import { installChatLinkIcons } from './chat-link-icons.js';-import { codeFenceLanguage, createMarkdownPlaceholders, highlightCode, renderMarkdownBlockquotes, renderMarkdownHeadings, renderMarkdownTables, replaceMarkdownCodeFences } from './markdown-render.js';+import { codeFenceLanguage, createMarkdownPlaceholders, highlightCode, renderMarkdownBlockquotes, renderMarkdownHeadings, renderMarkdownTables, replaceInlineDollarMath, replaceMarkdownCodeFences } from './markdown-render.js';import { applyMode, loadMode, watch } from './theme.js';import {UI_SCALE_LEVELS,@@ -14689,11 +14689,11 @@ function scheduleMathRender() {const target = document.getElementById('messages');if (!target) return;window.renderMathInElement(target, {- // Delimiters in order of precedence. We deliberately do NOT enable- // single-`$...$` as an inline-math delimiter: LLM responses very- // often contain dollar amounts ("$1,263 ... $2,526") and KaTeX- // would pair them up and italicize the prose between them. Users- // who genuinely want inline math can use \\( ... \\) or $$...$$.+ // Delimiters in order of precedence. Single `$...$` is NOT one:+ // LLM responses often contain dollar amounts ("$1,263 ... $2,526")+ // and KaTeX would pair them up and italicize the prose between them.+ // formatMarkdown turns $...$ that reads as TeX into \\( ... \\)+ // first (replaceInlineDollarMath).delimiters: [{ left: '$$', right: '$$', display: true },{ left: '\\[', right: '\\]', display: true },@@ -14738,6 +14738,13 @@ function formatMarkdown(text, options = {}) {return placeholders.add(`<code>${escaped}</code>`, code);});+ // 2b. Inline $...$ that reads as TeX ($\rightarrow$, $O(n^2)$) becomes+ // \(...\) text for the KaTeX pass, kept away from emphasis and escaping.+ // Prices stay text (replaceInlineDollarMath has the rules).+ if (enhance) {+ text = replaceInlineDollarMath(text, tex => placeholders.add(escapeHtml(`\\(${tex}\\)`), `$${tex}$`));+ }+// 3. Escape HTML in the remaining texttext = text.replace(/&/g, '&')diff --git a/test/markdown-render.mjs b/test/markdown-render.mjsindex 9b013bd94..171794709 100644--- a/test/markdown-render.mjs+++ b/test/markdown-render.mjs@@ -676,6 +676,96 @@ for (const build of ['chrome', 'firefox']) {assert.match(formatMarkdown(source), /<h2>After<\/h2>/);});+ test(`${build}: single-dollar math is found only where it reads as TeX`, () => {+ const mark = source => helpers.replaceInlineDollarMath(source, tex => `[${tex}]`);+ for (const [source, expected] of [+ ['traces $\\rightarrow$ rotation $\\rightarrow$ GPTQ', 'traces [\\rightarrow] rotation [\\rightarrow] GPTQ'],+ ['in $O(n^2)$ time for $x$ items, $a_{i}$ and $\\alpha$', 'in [O(n^2)] time for [x] items, [a_{i}] and [\\alpha]'],+ ['about $\\sim$5 GB', 'about [\\sim]5 GB'],+ // Prices, shell variables, escaped and unclosed dollars stay text.+ ['It costs $1,263 and then $2,526 more.', null],+ ['from $5 to $10, $5-$10, $5,$10', null],+ ['$HOME/$USER and $PATH', null],+ ['a \\$5$ fee, $ 5$, open $x', null],+ ['across $a\nb$ lines', null],+ // Display math belongs to the KaTeX pass.+ ['see $$a^2$$ here', null],+ ]) assert.equal(mark(source), expected ?? source, source);+ });++ test(`${build}: inline TeX math goes to KaTeX as \\(...\\); prices and code stay text`, () => {+ const html = formatMarkdown('traces $\\rightarrow$ rotation, about $\\sim$5 GB, $\\alpha*\\beta*$ and `$\\rightarrow$`');+ assert.match(html, /traces \\\(\\rightarrow\\\) rotation, about \\\(\\sim\\\)5 GB, \\\(\\alpha\*\\beta\*\\\) and <code>\$\\rightarrow\$<\/code>/);+ assert.doesNotMatch(html, /<em>/);+ const prices = 'It costs $1,263 and then $2,526 more.';+ assert.equal(formatMarkdown(prices), prices);+ assert.equal(formatMarkdown('a $\\rightarrow$ b', { enhance: false }), 'a $\\rightarrow$ b');+ });++ test(`${build}: history saves rendered formulas as their TeX source`, () => {+ const text = value => ({ nodeType: 3, nodeValue: value, textContent: value });+ const element = (tagName, className, ...childNodes) => ({+ nodeType: 1, tagName, childNodes,+ classList: { contains: name => String(className || '').split(' ').includes(name) },+ getAttribute: () => null,+ get textContent() { return childNodes.map(child => child.textContent).join(''); },+ });+ // KaTeX keeps MathML with the TeX source, and the visible HTML.+ const katex = (tex, shown) => {+ const annotation = { ...element('annotation', '', text(tex)), getAttribute: name => (name === 'encoding' ? 'application/x-tex' : null) };+ return element('SPAN', 'katex',+ element('SPAN', 'katex-mathml', element('math', '', element('semantics', '', element('mrow', '', text(shown)), annotation))),+ element('SPAN', 'katex-html', text(shown)));+ };+ const saved = historyTextFromElement(element('DIV', '',+ text('traces '), katex('\\rightarrow', '→'), text(' rotation, '), element('SPAN', 'katex-display', katex('a^2', 'a2'))));+ assert.equal(saved, 'traces \\(\\rightarrow\\) rotation, $$a^2$$');+ // Read back, the panel renders them again.+ assert.match(formatMarkdown(saved), /traces \\\(\\rightarrow\\\) rotation, \$\$a\^2\$\$/);+ });++ if (process.env.WEBBRAIN_MARKDOWN_DOM === '1') test(`${build}: browser renders inline TeX with KaTeX and saves it back`, async () => {+ const { chromium, firefox } = await import('playwright');+ const browser = await (build === 'chrome' ? chromium : firefox).launch({ headless: true });+ try {+ const page = await browser.newPage();+ await page.route('http://markdown.test/**', async route => {+ const name = new URL(route.request().url()).pathname.slice(1);+ if (/^[\w-]+\.js$/.test(name)) {+ await route.fulfill({ contentType: 'text/javascript', body: readUi(build, name) });+ } else if (/^katex\/[\w.-]+\.js$/.test(name)) {+ await route.fulfill({ contentType: 'text/javascript', body: fs.readFileSync(new URL(`../src/${build}/vendor/${name}`, import.meta.url), 'utf8') });+ } else {+ await route.fulfill({ contentType: 'text/html', body: '<!doctype html><html><head><script src="/katex/katex.min.js"></script><script src="/katex/auto-render.min.js"></script></head><body><div id="messages"><div class="message-text" id="message"></div></div></body></html>' });+ }+ });+ await page.goto('http://markdown.test/');+ const result = await page.evaluate(async ({ formatter, scheduler, source }) => {+ const helpers = await import('/markdown-render.js');+ const { sanitizeMarkdownLinks, linkifyPlainUrls } = await import('/markdown-link.js');+ const { escapeHtml } = await import('/utils.js');+ const { historyTextFromElement } = await import('/history-text.js');+ const scheduleMathRender = new Function(`let _mathRenderTimer = null; return (${scheduler})`)();+ const dependencies = { ...helpers, sanitizeMarkdownLinks, linkifyPlainUrls, escapeHtml, t: key => key, scheduleMathRender };+ const format = new Function(...Object.keys(dependencies), `return (${formatter})`)(...Object.values(dependencies));+ const message = document.querySelector('#message');+ const render = async markdown => {+ message.innerHTML = format(markdown);+ await new Promise(resolve => setTimeout(resolve, 150));+ };+ await render(source);+ const formulas = message.querySelectorAll('.katex').length;+ const shown = message.querySelector('.katex-html')?.textContent;+ const saved = historyTextFromElement(message);+ await render(saved);+ return { formulas, shown, saved, again: message.querySelectorAll('.katex').length, errors: message.querySelectorAll('.katex-error').length };+ }, { formatter: panelFormatter(build), scheduler: panelFunction(build, 'scheduleMathRender'), source: 'traces $\\rightarrow$ export. It costs $1,263 and then $2,526.' });+ assert.deepEqual(result, { formulas: 1, shown: '→', saved: 'traces \\(\\rightarrow\\) export. It costs $1,263 and then $2,526.', again: 1, errors: 0 });+ } finally {+ await browser.close();+ }+ });+// Opt-in native DOM checks: WEBBRAIN_MARKDOWN_DOM=1 npm run test:markdown.if (process.env.WEBBRAIN_MARKDOWN_DOM === '1') test(`${build}: browser render, Copy and history round trip`, async () => {const { chromium, firefox } = await import('playwright');diff --git a/test/run.js b/test/run.jsindex e1ea79f88..a66b21f42 100644--- a/test/run.js+++ b/test/run.js@@ -22505,7 +22505,7 @@ test('sidepanels wire highlighting and heading rendering into fenced Markdown',]) {const panel = fs.readFileSync(path.join(ROOT, panelRel), 'utf8');const css = fs.readFileSync(path.join(ROOT, cssRel), 'utf8');- assert.match(panel, /import \{ codeFenceLanguage, createMarkdownPlaceholders, highlightCode, renderMarkdownBlockquotes, renderMarkdownHeadings, renderMarkdownTables, replaceMarkdownCodeFences \} from '\.\/markdown-render\.js';/, `${label}: renderer helpers should be imported`);+ assert.match(panel, /import \{ codeFenceLanguage, createMarkdownPlaceholders, highlightCode, renderMarkdownBlockquotes, renderMarkdownHeadings, renderMarkdownTables, replaceInlineDollarMath, replaceMarkdownCodeFences \} from '\.\/markdown-render\.js';/, `${label}: renderer helpers should be imported`);assert.match(panel, /const lang = codeFenceLanguage\(info\);/, `${label}: fenced code should tolerate metadata after its language token`);assert.match(panel, /const highlighted = enhance \? highlightCode\(code, lang\) : escapeHtml\(code\);/, `${label}: completed fenced code should be highlighted by its language while live code stays lightweight`);assert.match(panel, /text = renderMarkdownTables\(text\);\s*text = renderMarkdownBlockquotes\(text\);\s*text = renderMarkdownHeadings\(text\);/, `${label}: pipe tables and quotes must render before headings swallow the following newline`);