The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): normalize hugging multi-line display-math delimiters
whisky080947066f5ea061
diff --git a/apps/desktop/src/components/assistant-ui/markdown-text.test.ts b/apps/desktop/src/components/assistant-ui/markdown-text.test.tsindex c97b8eb7793..0849e76de15 100644--- a/apps/desktop/src/components/assistant-ui/markdown-text.test.ts+++ b/apps/desktop/src/components/assistant-ui/markdown-text.test.ts@@ -306,4 +306,58 @@ describe('preprocessMarkdown', () => {expect(output).toContain('\\$5')expect(output).toContain('\\$10')})++ it('moves hugging $$ delimiters of multiline display math onto their own lines', () => {+ const input = [+ '$$\\begin{aligned}',+ '\\nabla \\cdot \\mathbf{E} &= \\frac{\\rho}{\\varepsilon_0} \\\\',+ '\\nabla \\cdot \\mathbf{B} &= 0',+ '\\end{aligned}$$'+ ].join('\n')++ const output = preprocessMarkdown(input)++ expect(output).toBe(+ [+ '$$',+ '\\begin{aligned}',+ '\\nabla \\cdot \\mathbf{E} &= \\frac{\\rho}{\\varepsilon_0} \\\\',+ '\\nabla \\cdot \\mathbf{B} &= 0',+ '\\end{aligned}',+ '$$'+ ].join('\n')+ )+ })++ it('keeps hugging display math inside its markdown container', () => {+ const input = ['> $$\\begin{aligned}', '> a &= b', '> \\end{aligned}$$'].join('\n')++ const output = preprocessMarkdown(input)++ expect(output).toBe(['> $$', '> \\begin{aligned}', '> a &= b', '> \\end{aligned}', '> $$'].join('\n'))+ })++ it('splits the hugging $$ form that the bracket rewrite itself produces', () => {+ const input = ['\\[\\begin{aligned}', 'a &= b', '\\end{aligned}\\]'].join('\n')++ const output = preprocessMarkdown(input)++ expect(output).toBe(['$$', '\\begin{aligned}', 'a &= b', '\\end{aligned}', '$$'].join('\n'))+ })++ it('keeps CRLF line endings consistent when splitting hugging delimiters', () => {+ const input = '$$\\begin{aligned}\r\na &= b\r\n\\end{aligned}$$'++ expect(preprocessMarkdown(input)).toBe('$$\r\n\\begin{aligned}\r\na &= b\r\n\\end{aligned}\r\n$$')+ })++ it('leaves single-line display math alone', () => {+ expect(preprocessMarkdown('$$x^2 + y^2 = r^2$$')).toBe('$$x^2 + y^2 = r^2$$')+ })++ it('leaves a multiline $$ block that sits wholly inside one inline code span alone', () => {+ const input = '`$$a\nb$$`'++ expect(preprocessMarkdown(input)).toBe(input)+ })})diff --git a/apps/desktop/src/lib/markdown-preprocess.ts b/apps/desktop/src/lib/markdown-preprocess.tsindex 5959048120e..c8caf6c9660 100644--- a/apps/desktop/src/lib/markdown-preprocess.ts+++ b/apps/desktop/src/lib/markdown-preprocess.ts@@ -17,6 +17,15 @@ const INLINE_CODE_SPLIT_RE = /(`[^`\n]+`)/gconst LATEX_DISPLAY_OPEN_LINE_RE = /^([ \t]*(?:>[ \t]*)*(?:(?:[-+*]|\d+[.)])[ \t]+)?[ \t]*)\\{1,2}\[[ \t]*\r?$/const LATEX_DISPLAY_CLOSE_LINE_RE = /^([ \t]*(?:>[ \t]*)*(?:(?:[-+*]|\d+[.)])[ \t]+)?[ \t]*)\\{1,2}\][ \t]*\r?$/const CUSTOM_DISPLAY_MATH_LINE_RE = /^([ \t]*(?:>[ \t]*)*(?:(?:[-+*]|\d+[.)])[ \t]+)?[ \t]*)\[\/math\][ \t]*\r?$/++// A `$$` that opens a block and is immediately followed by the first line of the+// equation, e.g. `$$\begin{aligned}`. Both patterns anchor the `$$` to the start+// of the line (modulo blockquote/list prefix), which is also what keeps them from+// firing inside an inline code span — `` `$$a `` leads with a backtick.+const HUGGING_DISPLAY_MATH_OPEN_RE =+ /^([ \t]*(?:>[ \t]*)*(?:(?:[-+*]|\d+[.)])[ \t]+)?[ \t]*)\$\$[ \t]*(\S[^\n]*?)[ \t]*\r?$/++const HUGGING_DISPLAY_MATH_CLOSE_RE = /^([ \t]*(?:>[ \t]*)*[ \t]*)(\S[^\n]*?)\$\$[ \t]*\r?$/// Bare-URL autolink matcher. The character classes EXCLUDE `*` so a URL that// abuts markdown emphasis with no separating space (e.g. `**label: https://x**`,// a very common LLM pattern) doesn't swallow the trailing `**` into the href.@@ -302,6 +311,76 @@ function escapeCurrencyDollarsPreservingMath(text: string): string {return out + text.slice(copiedThrough)}+/**+ * Moves the `$$` delimiters of a MULTI-LINE display-math block onto their own+ * lines: `$$\begin{aligned}` … `\end{aligned}$$` becomes a `$$`-only line, the+ * body, then a `$$`-only line.+ *+ * remark-math's flow-math construct is fence-shaped: whatever follows the+ * opening `$$` on the same line is read as an info string and DISCARDED, and the+ * closing `$$` is only recognized alone on its own line. So the hugging form+ * loses its first line, never closes, and KaTeX paints the remains as raw source+ * text. Models emit this form constantly.+ *+ * Single-line `$$…$$` is left alone — it routes through the inline math-text+ * construct and already renders.+ */+function splitHuggingDisplayMath(text: string): string {+ const lines = text.split('\n')+ const out: string[] = []++ for (let index = 0; index < lines.length; index += 1) {+ const openingMatch = lines[index].match(HUGGING_DISPLAY_MATH_OPEN_RE)++ // `$$x^2$$` closes on the same line — not our case.+ if (!openingMatch || openingMatch[2].endsWith('$$')) {+ out.push(lines[index])++ continue+ }++ let closingIndex = -1++ for (let candidate = index + 1; candidate < lines.length; candidate += 1) {+ if (HUGGING_DISPLAY_MATH_CLOSE_RE.test(lines[candidate])) {+ closingIndex = candidate++ break+ }+ }++ if (closingIndex === -1) {+ out.push(lines[index])++ continue+ }++ const closingMatch = lines[closingIndex].match(HUGGING_DISPLAY_MATH_CLOSE_RE) as RegExpMatchArray+ const openingCarriageReturn = lines[index].endsWith('\r') ? '\r' : ''+ const closingCarriageReturn = lines[closingIndex].endsWith('\r') ? '\r' : ''++ // The container prefix (blockquote marker, list bullet) has to be replayed+ // onto the delimiter lines, or the block falls out of its container.+ out.push(+ `${openingMatch[1]}$$${openingCarriageReturn}`,+ `${openingMatch[1]}${openingMatch[2]}${openingCarriageReturn}`+ )+ out.push(...lines.slice(index + 1, closingIndex))+ // The break this split INTRODUCES takes the block's own line ending, not the+ // closing line's — a final `\end{aligned}$$` with no trailing CRLF (it's the+ // last line of the message) would otherwise emit a bare LF into an+ // otherwise-CRLF block.+ out.push(+ `${closingMatch[1]}${closingMatch[2]}${openingCarriageReturn}`,+ `${closingMatch[1]}$$${closingCarriageReturn}`+ )++ index = closingIndex+ }++ return out.join('\n')+}+function normalizeDisplayMathForMarkdown(text: string): string {const lines = text.split('\n')@@ -344,7 +423,12 @@ function normalizeProseMath(text: string): string {// Normalize those locally before the dependency handles inline forms;// its compact `$$body$$` rewrite makes the first equation line metadata// and leaks the trailing `$$` into KaTeX's error fallback.- const normalized = normalizeMathDelimiters(normalizeDisplayMathForMarkdown(text))+ //+ // splitHuggingDisplayMath runs LAST because normalizeMathDelimiters is itself+ // a source of the hugging form: a multi-line `\[…\]` comes out of it as+ // `$$\begin{aligned}…\end{aligned}$$`. Running afterwards catches both the+ // hugging math the model emitted and the hugging math the rewrite produced.+ const normalized = splitHuggingDisplayMath(normalizeMathDelimiters(normalizeDisplayMathForMarkdown(text)))return escapeCurrencyDollarsPreservingMath(normalized)}