~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
test(ui): cover KaTeX edge cases — code blocks, multi-line display, PDF substitution (#4090)
LearningCircuit3dc22e8f5b6a
diff --git a/src/local_deep_research/web/static/js/services/pdf.js b/src/local_deep_research/web/static/js/services/pdf.jsindex a0f1c4324c..50983e05fe 100644--- a/src/local_deep_research/web/static/js/services/pdf.js+++ b/src/local_deep_research/web/static/js/services/pdf.js@@ -3,6 +3,37 @@* Handles generation of PDFs from research results*/+/**+ * Replace KaTeX-rendered math elements with their raw LaTeX source.+ *+ * The PDF generator extracts element.textContent for pdf.text(), which would+ * garble KaTeX's dual HTML+MathML output (rendered glyphs concatenated with+ * the duplicated LaTeX source from <annotation>). We swap each rendered math+ * element for its original LaTeX so PDFs show readable formulas.+ *+ * Display math (`$$\n...\n$$`) is emitted by marked-katex-extension as a+ * top-level <span class="katex-display"> with NO <p> wrapper. The PDF walker+ * iterates contentDiv.children (Elements only — text nodes skipped), so a+ * bare text-node replacement would silently drop top-level display math.+ * Wrap display math in <p> so the walker still finds it. Inline .katex+ * always sits inside a <p>/<li>/etc., so a bare text node is safe there.+ *+ * @param {Element} container - The DOM element containing rendered KaTeX+ */+function replaceKatexWithLatex(container) {+ container.querySelectorAll('.katex-display').forEach((el) => {+ const ann = el.querySelector('annotation[encoding="application/x-tex"]');+ if (!ann) return;+ const p = document.createElement('p');+ p.textContent = `$$${ann.textContent}$$`;+ el.replaceWith(p);+ });+ container.querySelectorAll('.katex').forEach((el) => {+ const ann = el.querySelector('annotation[encoding="application/x-tex"]');+ if (ann) el.replaceWith(document.createTextNode(`$${ann.textContent}$`));+ });+}+/*** Generate a PDF from the research content* @param {string|any} title - The research title/query@@ -154,31 +185,7 @@ async function generatePdf(title, content, _metadata = {}) {pdfBodyDiv.innerHTML = window.DOMPurify.sanitize(rawHtml, {ADD_TAGS: ['semantics', 'annotation'],});- // The PDF generator extracts element.textContent for pdf.text(),- // which would garble KaTeX output (rendered glyphs + duplicated- // LaTeX source from <annotation>). Replace each rendered math- // element with its original LaTeX source so PDFs show readable- // formulas instead of concatenated layout fragments.- //- // Display math (`$$\n...\n$$`) is emitted by marked-katex-extension- // as a top-level `<span class="katex-display">` with NO `<p>` wrapper.- // Replacing with a bare text node would leave the math at the- // top level — and the walker below iterates `contentDiv.children`- // (Elements only, text nodes skipped), silently dropping the math.- // Wrap in `<p>` so the walker still finds it.- pdfBodyDiv.querySelectorAll('.katex-display').forEach((el) => {- const ann = el.querySelector('annotation[encoding="application/x-tex"]');- if (!ann) return;- const p = document.createElement('p');- p.textContent = `$$${ann.textContent}$$`;- el.replaceWith(p);- });- // Inline `.katex` always lives inside a `<p>`/`<li>`/etc., so a- // bare text node is safe — the parent element still gets walked.- pdfBodyDiv.querySelectorAll('.katex').forEach((el) => {- const ann = el.querySelector('annotation[encoding="application/x-tex"]');- if (ann) el.replaceWith(document.createTextNode(`$${ann.textContent}$`));- });+ replaceKatexWithLatex(pdfBodyDiv);} else {// marked.js not available - this is a critical error for PDF generationdocument.body.removeChild(tempContainer);@@ -1002,5 +1009,6 @@ async function downloadPdf(titleOrData, content, metadata = {}) {// Export PDF functionswindow.pdfService = {generatePdf,- downloadPdf+ downloadPdf,+ replaceKatexWithLatex};diff --git a/tests/js/services/pdf.test.js b/tests/js/services/pdf.test.jsnew file mode 100644index 0000000000..53eb854960--- /dev/null+++ b/tests/js/services/pdf.test.js@@ -0,0 +1,140 @@+/**+ * Tests for services/pdf.js+ *+ * Currently covers the replaceKatexWithLatex helper: the substitution step+ * that swaps rendered KaTeX elements for their raw LaTeX source before the+ * PDF walker extracts textContent. Regression-protects the fix for+ * top-level `$$\n...\n$$` display math being silently dropped from PDFs.+ */++import '@js/services/pdf.js';++const { replaceKatexWithLatex } = window.pdfService;++// Build a DOM with KaTeX-shaped markup. We construct it by hand (rather than+// driving marked + KaTeX) so the test does not depend on KaTeX's exact+// internal layout — only on the structural contract: `.katex-display` for+// display math, `.katex` for inline, both containing an `<annotation>` with+// the original LaTeX. That matches what marked-katex-extension always emits.+function el(tag, attrs = {}, ...children) {+ const node = document.createElement(tag);+ for (const [k, v] of Object.entries(attrs)) node.setAttribute(k, v);+ for (const c of children) node.appendChild(typeof c === 'string' ? document.createTextNode(c) : c);+ return node;+}++function makeKatexInline(latex) {+ return el('span', { class: 'katex' },+ el('span', { class: 'katex-mathml' },+ el('math', {},+ el('semantics', {},+ el('mrow'),+ el('annotation', { encoding: 'application/x-tex' }, latex)+ )+ )+ ),+ el('span', { class: 'katex-html', 'aria-hidden': 'true' }, 'rendered')+ );+}++function makeKatexDisplay(latex) {+ return el('span', { class: 'katex-display' }, makeKatexInline(latex));+}++describe('replaceKatexWithLatex', () => {+ let root;++ beforeEach(() => {+ root = document.createElement('div');+ document.body.appendChild(root);+ });++ afterEach(() => {+ root.remove();+ });++ it('replaces inline .katex with `$LATEX$` text node inside its parent', () => {+ const p = document.createElement('p');+ p.append('Energy is ', makeKatexInline('E=mc^2'), ' famous.');+ root.appendChild(p);++ replaceKatexWithLatex(root);++ // The parent <p> still exists and now reads cleanly.+ expect(root.children.length).toBe(1);+ expect(root.children[0].tagName).toBe('P');+ expect(root.children[0].textContent).toBe('Energy is $E=mc^2$ famous.');+ expect(root.querySelector('.katex')).toBeNull();+ });++ it('wraps top-level .katex-display in a <p> so the PDF walker sees it', () => {+ // Regression: previously, display math at top level (the canonical+ // multi-line `$$\n...\n$$` form) was replaced with a bare text node.+ // The PDF walker iterates contentDiv.children (Elements only — text+ // nodes are skipped), so display math was silently dropped.+ root.appendChild(document.createElement('p')).textContent = 'Before';+ root.appendChild(makeKatexDisplay('\\sum_{i=1}^n i'));+ root.appendChild(document.createElement('p')).textContent = 'After';++ replaceKatexWithLatex(root);++ const kids = Array.from(root.children);+ expect(kids.map((k) => k.tagName)).toEqual(['P', 'P', 'P']);+ expect(kids[0].textContent).toBe('Before');+ expect(kids[1].textContent).toBe('$$\\sum_{i=1}^n i$$');+ expect(kids[2].textContent).toBe('After');+ });++ it('handles back-to-back display math blocks', () => {+ root.appendChild(makeKatexDisplay('a'));+ root.appendChild(makeKatexDisplay('b'));++ replaceKatexWithLatex(root);++ const kids = Array.from(root.children);+ expect(kids.length).toBe(2);+ expect(kids[0].textContent).toBe('$$a$$');+ expect(kids[1].textContent).toBe('$$b$$');+ });++ it('handles display math nested inside another element', () => {+ const li = document.createElement('li');+ li.appendChild(makeKatexDisplay('x=1'));+ const ul = document.createElement('ul');+ ul.appendChild(li);+ root.appendChild(ul);++ replaceKatexWithLatex(root);++ // The wrap <p> sits inside the <li>; the walker iterates the <ul>+ // and the <li> textContent recovers the LaTeX.+ expect(root.querySelector('.katex-display')).toBeNull();+ expect(root.querySelector('li').textContent).toBe('$$x=1$$');+ });++ it('leaves elements without an annotation untouched', () => {+ // Defensive: if DOMPurify ever stripped <annotation>, the substitution+ // should skip rather than silently produce $$$$ or $$.+ const broken = el('span', { class: 'katex-display' },+ el('span', { class: 'katex-html' }, 'no annotation here')+ );+ root.appendChild(broken);++ replaceKatexWithLatex(root);++ // Unchanged.+ expect(root.querySelector('.katex-display')).not.toBeNull();+ expect(root.querySelector('.katex-display').textContent).toBe('no annotation here');+ });++ it('is a no-op on a container with no KaTeX', () => {+ const p = document.createElement('p');+ p.textContent = 'Plain text only.';+ root.appendChild(p);++ replaceKatexWithLatex(root);++ expect(root.children.length).toBe(1);+ expect(root.children[0].textContent).toBe('Plain text only.');+ });+});diff --git a/tests/js/services/ui.test.js b/tests/js/services/ui.test.jsindex e081efb1f8..6f1b4a5bbb 100644--- a/tests/js/services/ui.test.js+++ b/tests/js/services/ui.test.js@@ -337,7 +337,8 @@ describe('renderMarkdown with KaTeX math', () => {const markedKatex = (await import('marked-katex-extension')).default;const DOMPurify = (await import('dompurify')).default;const m = new Marked();- m.use(markedKatex({ throwOnError: false }));+ // Mirror app.js so the test exercises the production config.+ m.use(markedKatex({ throwOnError: false, errorColor: 'currentColor' }));globalThis.marked = m;globalThis.DOMPurify = DOMPurify;});@@ -379,4 +380,42 @@ describe('renderMarkdown with KaTeX math', () => {const result = ui.renderMarkdown('It costs $10 and $20 per unit.');expect(result).not.toContain('class="katex"');});++ it('renders multi-line display math ($$\\n…\\n$$)', () => {+ // Canonical block form — what LLMs and textbooks typically emit.+ // This pattern caused display math to be silently dropped from PDFs+ // before commit 2c47b529e; locking in the rendering behavior here+ // guards against a related regression in the markdown path.+ const result = ui.renderMarkdown('Para 1\n\n$$\n\\sum_{i=1}^n i\n$$\n\nPara 2');+ expect(result).toContain('class="katex-display"');+ expect(result).toContain('Para 1');+ expect(result).toContain('Para 2');+ });++ it('does not render math inside inline code spans', () => {+ // `$x^2$` inside backticks must stay as literal code, not be parsed+ // as math. This is both a correctness and a defense-in-depth concern+ // (an LLM documenting LaTeX syntax should not have its examples+ // silently rendered).+ const result = ui.renderMarkdown('Use `$x^2$` to write x squared.');+ expect(result).not.toContain('class="katex"');+ expect(result).toContain('<code>$x^2$</code>');+ });++ it('does not render math inside fenced code blocks', () => {+ const result = ui.renderMarkdown('```\n$E=mc^2$\n```');+ expect(result).not.toContain('class="katex"');+ expect(result).toContain('$E=mc^2$');+ });++ it('renders invalid LaTeX without throwing (throwOnError: false)', () => {+ // app.js configures the extension with throwOnError: false so a+ // malformed formula in LLM output degrades gracefully rather than+ // breaking the whole render. Verify the wrapper doesn't blow up.+ expect(() => ui.renderMarkdown('Bad math: $\\frac{a$')).not.toThrow();+ const result = ui.renderMarkdown('Bad math: $\\frac{a$');+ // Either the error span renders or KaTeX recovers — either way the+ // surrounding text must come through.+ expect(result).toContain('Bad math:');+ });});