From 3cc18d7bb70919bde6654df9e5eaa5f0b1429cfb Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 19 Oct 2026 23:49:59 +0200 Subject: [PATCH] Chat: LaTeX math is drawn with KaTeX (inline $..$ and \(..\), display $$..$$ and \[..\]); KaTeX and its woff2 fonts ship with the app and load only when an answer has a formula; money and code stay text (#3268) --- apps/host/package-lock.json | 26 ++++++ apps/host/package.json | 1 + apps/host/src/components/Markdown.tsx | 22 ++++- apps/host/src/components/MathView.tsx | 43 +++++++++ apps/host/src/lib/math.ts | 130 ++++++++++++++++++++++++++ apps/host/src/styles/app.css | 8 ++ apps/host/tests/math.test.mjs | 73 +++++++++++++++ apps/host/tests/reliability.test.mjs | 7 +- apps/host/vite.config.ts | 14 ++- 9 files changed, 321 insertions(+), 3 deletions(-) create mode 100644 apps/host/src/components/MathView.tsx create mode 100644 apps/host/src/lib/math.ts create mode 100644 apps/host/tests/math.test.mjs diff --git a/apps/host/package-lock.json b/apps/host/package-lock.json index d3aa5df3..378dc870 100644 --- a/apps/host/package-lock.json +++ b/apps/host/package-lock.json @@ -9,6 +9,7 @@ "version": "0.2.0-beta", "dependencies": { "html-to-image": "^1.11.13", + "katex": "^0.19.0", "pdfjs-dist": "^6.4.299", "prismjs": "1.30.0", "react": "^19.1.0", @@ -1608,6 +1609,15 @@ ], "license": "CC-BY-4.0" }, + "node_modules/commander": { + "version": "15.0.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-15.0.0.tgz", + "integrity": "sha512-z67u4ZhzCL/Tydu1lJARtEZYWbWaN7oYLHbsuzocr6y4N6WZAagG3RQ4FW61V1/0+jImpj293XfrcYnd1qxtPg==", + "license": "MIT", + "engines": { + "node": ">=22.12.0" + } + }, "node_modules/convert-source-map": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", @@ -1781,6 +1791,22 @@ "node": ">=6" } }, + "node_modules/katex": { + "version": "0.19.0", + "resolved": "https://registry.npmjs.org/katex/-/katex-0.19.0.tgz", + "integrity": "sha512-v6Tznz3zJ7u3niRCoDTsumM2+HA2XXcCu+WAacCeHD2z3p9A9Ks987o5FzfTGBN0e8A0vjEgIDvLbICrXpdw/Q==", + "funding": [ + "https://opencollective.com/katex", + "https://github.com/sponsors/katex" + ], + "license": "MIT", + "dependencies": { + "commander": "^15.0.0" + }, + "bin": { + "katex": "cli.js" + } + }, "node_modules/lru-cache": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", diff --git a/apps/host/package.json b/apps/host/package.json index 7d73c865..aa346023 100644 --- a/apps/host/package.json +++ b/apps/host/package.json @@ -28,6 +28,7 @@ }, "dependencies": { "html-to-image": "^1.11.13", + "katex": "^0.19.0", "pdfjs-dist": "^6.4.299", "prismjs": "1.30.0", "react": "^19.1.0", diff --git a/apps/host/src/components/Markdown.tsx b/apps/host/src/components/Markdown.tsx index 696a2747..87e6c327 100644 --- a/apps/host/src/components/Markdown.tsx +++ b/apps/host/src/components/Markdown.tsx @@ -3,7 +3,9 @@ import { tr } from '../lib/i18n'; import { Fragment, type ReactNode } from 'react'; import { Btn, IconBtn } from './ui'; import { SyntaxCode } from './SyntaxCode'; -function inline(text: string, onOpenLink?: (url: string) => void): ReactNode { +import { MathView } from './MathView'; +import { displayBlock, hasMath, splitMath } from '../lib/math'; +function inlineMarks(text: string, onOpenLink?: (url: string) => void): ReactNode { return text.split(/(`[^`]+`|\*\*[^*]+\*\*|\*[^*\n]+\*|\[[^\]]+\]\([^\s)]+\))/g).map((part, i) => { if (part.startsWith('`') && part.endsWith('`')) return {part.slice(1, -1)}; @@ -20,6 +22,18 @@ function inline(text: string, onOpenLink?: (url: string) => void): ReactNode { return {part}; }); } +/** Text with its inline marks and, outside code spans, its math (#3268). Math is cut out first: a * or _ inside a formula is not emphasis. */ +function inline(text: string, onOpenLink?: (url: string) => void): ReactNode { + if (!hasMath(text)) + return inlineMarks(text, onOpenLink); + return text.split(/(`[^`]+`)/g).map((chunk, c) => { + if (chunk.length > 1 && chunk.startsWith('`') && chunk.endsWith('`')) + return {inlineMarks(chunk, onOpenLink)}; + return {splitMath(chunk).map((part, p) => part.kind === 'math' + ? + : {inlineMarks(part.text, onOpenLink)})}; + }); +} export function Markdown({ text, onOpenLink, onPreviewHtml }: { text: string; onOpenLink?: (url: string) => void; @@ -43,6 +57,12 @@ export function Markdown({ text, onOpenLink, onPreviewHtml }: { nodes.push(
{language || tr('code')}{tr(/^html$/i.test(language) && onPreviewHtml ? onPreviewHtml(body.join('\n'))}>{tr("Open preview")} : null)} void navigator.clipboard.writeText(body.join('\n'))}/>
); continue; } + const block = displayBlock(lines, i); + if (block) { + nodes.push(
); + i += block.used; + continue; + } const heading = line.match(/^(#{1,6})\s+(.+)$/); if (heading) { const Tag = heading[1].length <= 2 ? 'h2' : heading[1].length === 3 ? 'h3' : 'h4'; diff --git a/apps/host/src/components/MathView.tsx b/apps/host/src/components/MathView.tsx new file mode 100644 index 00000000..4547eeb6 --- /dev/null +++ b/apps/host/src/components/MathView.tsx @@ -0,0 +1,43 @@ +/** + * One formula of an answer (#3268), drawn by KaTeX. KaTeX and its fonts are bundled with the app (no network) and load as a separate + * chunk the first time an answer holds math, so a chat without math pays nothing. Until the chunk is there, and if it cannot load, + * the formula shows as its source text, as before. + */ +import { useEffect, useState } from 'react'; + +type Katex = typeof import('katex').default; +let loading: Promise | null = null; +const drawn = new Map(); + +function loadKatex(): Promise { + loading ??= Promise.all([import('katex'), import('katex/dist/katex.min.css')]).then(([module]) => module.default); + return loading; +} + +function draw(katex: Katex, tex: string, display: boolean): string { + const key = (display ? 'D' : 'I') + tex; + const known = drawn.get(key); + if (known !== undefined) + return known; + // trust stays off (no \href, \url, \includegraphics); a broken formula is shown as its source, not as an error page + const html = katex.renderToString(tex, { displayMode: display, throwOnError: false, strict: 'ignore', trust: false, maxSize: 30, maxExpand: 500 }); + if (drawn.size > 400) + drawn.clear(); + drawn.set(key, html); + return html; +} + +const source = (tex: string, display: boolean) => (display ? `$$${tex}$$` : `$${tex}$`); + +export function MathView({ tex, display }: { tex: string; display: boolean }) { + const [html, setHtml] = useState(() => drawn.get((display ? 'D' : 'I') + tex) ?? null); + useEffect(() => { + let live = true; + loadKatex().then(katex => { if (live) setHtml(draw(katex, tex, display)); }).catch(() => { /* stays as source text */ }); + return () => { live = false; }; + }, [tex, display]); + const cls = display ? 'md-math md-math--display' : 'md-math'; + if (html === null) + return {source(tex, display)}; + return ; +} diff --git a/apps/host/src/lib/math.ts b/apps/host/src/lib/math.ts new file mode 100644 index 00000000..4d007643 --- /dev/null +++ b/apps/host/src/lib/math.ts @@ -0,0 +1,130 @@ +/** + * Finding the math in an answer (#3268). Pure text work, no rendering: the pieces are drawn by components/MathView.tsx. + * + * Recognised, as models write them: + * $$ ... $$ and \[ ... \] display math (may span lines) + * $ ... $ and \( ... \) inline math (one line) + * A dollar sign that is money stays text: "costs $5 and $10" has no math, because an opening $ must be followed by a non-space, + * a closing $ must follow a non-space and must not be followed by a digit. `\$` is a literal dollar sign. + * Code (backtick spans, fenced blocks) is never searched: the caller splits it off first. + */ +export type MathPart = { kind: 'text'; text: string } | { kind: 'math'; tex: string; display: boolean }; + +const isSpace = (c: string | undefined) => c === undefined || /\s/.test(c); +const isDigit = (c: string | undefined) => c !== undefined && c >= '0' && c <= '9'; + +/** Where the unescaped `close` starts at or after `from`, or -1. `\\` and `\$` style escapes are skipped. */ +function findClose(text: string, from: number, close: string, oneLine: boolean): number { + for (let i = from; i < text.length; i++) { + const c = text[i]; + if (oneLine && c === '\n') + return -1; + if (c === '\\' && close !== '\\)' && close !== '\\]') { + i++; + continue; + } + if (text.startsWith(close, i)) + return i; + } + return -1; +} + +export function splitMath(text: string): MathPart[] { + const parts: MathPart[] = []; + let plain = ''; + const flush = () => { + if (plain) { + parts.push({ kind: 'text', text: plain }); + plain = ''; + } + }; + const push = (tex: string, display: boolean) => { + if (!tex.trim()) + return false; + flush(); + parts.push({ kind: 'math', tex: tex.trim(), display }); + return true; + }; + for (let i = 0; i < text.length;) { + const c = text[i]; + if (c === '\\') { + const next = text[i + 1]; + if (next === '$') { // \$ is a dollar sign + plain += '$'; + i += 2; + continue; + } + if (next === '(' || next === '[') { + const close = next === '(' ? '\\)' : '\\]'; + const end = findClose(text, i + 2, close, next === '('); + if (end > 0 && push(text.slice(i + 2, end), next === '[')) { + i = end + 2; + continue; + } + } + plain += c + (next ?? ''); + i += 2; + continue; + } + if (c === '$') { + if (text[i + 1] === '$') { + const end = findClose(text, i + 2, '$$', false); + if (end > 0 && push(text.slice(i + 2, end), true)) { + i = end + 2; + continue; + } + plain += '$$'; + i += 2; + continue; + } + if (!isSpace(text[i + 1])) { + const end = findClose(text, i + 1, '$', true); + if (end > i + 1 && !isSpace(text[end - 1]) && !isDigit(text[end + 1]) && push(text.slice(i + 1, end), false)) { + i = end + 1; + continue; + } + } + } + plain += c; + i++; + } + flush(); + return parts; +} + +/** True when the text holds any math, so a plain answer costs nothing. */ +export function hasMath(text: string): boolean { + return text.includes('$') || text.includes('\\(') || text.includes('\\['); +} + +/** + * A block of display math that starts a line: `$$ ... $$` on one line, or `$$` / `\[` on its own line up to the line with the closing + * delimiter. Returns the formula and the number of lines used, or null (an unclosed block, e.g. while the answer is still streaming, + * stays text). + */ +export function displayBlock(lines: string[], at: number): { tex: string; used: number } | null { + const first = lines[at].trim(); + const opens = first.startsWith('$$') ? '$$' : first.startsWith('\\[') ? '\\[' : ''; + if (!opens) + return null; + const closes = opens === '$$' ? '$$' : '\\]'; + const rest = first.slice(2); + const sameLine = rest.indexOf(closes); + if (sameLine >= 0) { + // "$$ x $$" alone on the line; text after the closing delimiter makes it an inline display in a paragraph instead + return rest.slice(sameLine + closes.length).trim() ? null : { tex: rest.slice(0, sameLine), used: 1 }; + } + const body = [rest]; + for (let j = at + 1; j < lines.length && j < at + 60; j++) { + const t = lines[j].trim(); + const end = t.indexOf(closes); + if (end >= 0) { + if (t.slice(end + closes.length).trim()) + return null; + body.push(t.slice(0, end)); + return { tex: body.join('\n'), used: j - at + 1 }; + } + body.push(lines[j]); + } + return null; +} diff --git a/apps/host/src/styles/app.css b/apps/host/src/styles/app.css index f1db727c..c740716c 100644 --- a/apps/host/src/styles/app.css +++ b/apps/host/src/styles/app.css @@ -7503,3 +7503,11 @@ textarea { .native-vision-missing { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-top: 8px; font-size: var(--st-fs-sm); color: var(--st-ink-soft); } .storage-model--shared { background: var(--st-surface-2); } .storage-model--shared small { font-size: var(--st-fs-xs); } + +/* Math in answers (#3268): KaTeX draws it; its own stylesheet and fonts load with it, on the first answer that has a formula. */ +.md-math--source { font-size: 0.9em; } +.md-math-block { margin: 0.6em 0; overflow-x: auto; overflow-y: hidden; text-align: center; } +.md-math--display { display: block; margin: 0.6em 0; overflow-x: auto; overflow-y: hidden; text-align: center; } +.md-math-block .md-math--display { margin: 0; } +.md-math .katex { font-size: 1.08em; } +.md-math .katex-display { margin: 0; } diff --git a/apps/host/tests/math.test.mjs b/apps/host/tests/math.test.mjs new file mode 100644 index 00000000..6adb6ae1 --- /dev/null +++ b/apps/host/tests/math.test.mjs @@ -0,0 +1,73 @@ +// #3268: LaTeX in answers is found (and drawn by KaTeX), money and code are not mistaken for it. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { transform } from 'esbuild'; +import katex from 'katex'; + +async function loadTs(path) { + const { code } = await transform(await readFile(new URL(path, import.meta.url), 'utf8'), { loader: 'ts', format: 'esm' }); + return import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`); +} +const { splitMath, displayBlock, hasMath } = await loadTs('../src/lib/math.ts'); +const maths = text => splitMath(text).filter(p => p.kind === 'math').map(p => [p.tex, p.display]); + +test('inline and display forms', () => { + assert.deepEqual(maths('a sphere of radius $r \\le R$ here'), [['r \\le R', false]]); + assert.deepEqual(maths('so \\(x^2\\) and \\[y^2\\]'), [['x^2', false], ['y^2', true]]); + assert.deepEqual(maths('then $$g = -k r$$ done'), [['g = -k r', true]]); + assert.deepEqual(splitMath('plain words').map(p => p.kind), ['text']); +}); + +test('money, escaped dollars and unclosed math stay text', () => { + assert.deepEqual(maths('it costs $5 and $10 in total'), []); + assert.deepEqual(maths('only $5 here'), []); + assert.deepEqual(maths('a \\$5 and a \\$7 fee'), []); + assert.deepEqual(maths('an open $$ x + y'), []); + assert.equal(splitMath('a \\$5 fee').map(p => p.text).join(''), 'a $5 fee'); + assert.equal(hasMath('no math here'), false); +}); + +test('inline math does not cross a line, display math does', () => { + assert.deepEqual(maths('start $a\nb$ end'), []); + assert.deepEqual(maths('x $$a\nb$$ y'), [['a\nb', true]]); +}); + +test('display blocks: one line, several lines, bracket form, and unclosed ones (still streaming) stay text', () => { + assert.deepEqual(displayBlock(['$$ a = b $$'], 0), { tex: ' a = b ', used: 1 }); + assert.deepEqual(displayBlock(['$$', '\\oint g = 1', '$$', 'after'], 0), { tex: '\n\\oint g = 1\n', used: 3 }); + assert.deepEqual(displayBlock(['\\[', 'x', '\\]'], 0), { tex: '\nx\n', used: 3 }); + assert.equal(displayBlock(['$$', 'x'], 0), null); + assert.equal(displayBlock(['$$a$$ and more'], 0), null); + assert.equal(displayBlock(['plain'], 0), null); +}); + +test('the formulas of the report are found in their paragraph and draw without an error', () => { + const answer = [ + 'Apply Gauss\'s Law for gravity to a sphere of radius $r \\le R$ concentric with the planet:', + '', + '$$\\oint \\vec{g}\\cdot d\\vec{A} = -4\\pi G\\, M_{\\text{enc}}(r)$$', + '', + 'By spherical symmetry, $\\vec{g}$ is radial and constant on the Gaussian sphere, so:', + '', + '$$g\\,(4\\pi r^2) = -4\\pi G\\left(\\tfrac{4}{3}\\pi r^3\\rho\\right)$$', + '', + '$$\\boxed{g(r) = -\\frac{4\\pi G\\rho}{3}\\,r}$$', + ].join('\n').split('\n'); + const found = []; + for (let i = 0; i < answer.length;) { + const block = displayBlock(answer, i); + if (block) { found.push([block.tex, true]); i += block.used; continue; } + for (const [tex, display] of maths(answer[i])) found.push([tex, display]); + i++; + } + assert.equal(found.length, 5); + for (const [tex, display] of found) { + const html = katex.renderToString(tex, { displayMode: display, throwOnError: false, strict: 'ignore', trust: false }); + assert.ok(html.includes('class="katex'), tex); + assert.ok(!html.includes('katex-error'), tex); + } + // trust is off: no link can come out of a model's formula + const bad = katex.renderToString('\\href{https://example.com}{x}', { throwOnError: false, strict: 'ignore', trust: false }); + assert.ok(!bad.includes(' { const bundle = await build({ stdin: { contents: `import React from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; import { Markdown } from './src/components/Markdown.tsx'; export {setTranslationLanguage as setLanguage} from './src/lib/i18n.ts'; export const render = text => renderToStaticMarkup(React.createElement(Markdown, { text }));`, resolveDir: root }, - bundle: true, write: false, platform: 'node', format: 'cjs', jsx: 'automatic', + bundle: true, write: false, platform: 'node', format: 'cjs', jsx: 'automatic', external: ['katex', 'katex/dist/katex.min.css'], // math loads on demand in the browser plugins: [{ name: 'copy-control-stub', setup(b) { b.onResolve({ filter: /^\.\/ui$/ }, () => ({ path: 'ui', namespace: 'test-stub' })); b.onLoad({ filter: /.*/, namespace: 'test-stub' }, () => ({ contents: 'export const IconBtn = () => null; export const Btn = () => null;' })); @@ -32,6 +32,11 @@ test('Markdown renders every incomplete stream prefix without looping', { timeou for (let i = 0; i <= text.length; i++) assert.equal(typeof render(text.slice(0, i)), 'string'); assert.match(render(text), /
    /); assert.match(render(text), /
      /); assert.match(render(text), /alert(1)').includes('