Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(chat): escape an unclosed display math fence instead of swallowing the rest of the message

koeria741345468607
diff --git a/src/components/ChatMarkdown.test.ts b/src/components/ChatMarkdown.test.ts
index fdd9c2b423..6d85fd4673 100644
--- a/src/components/ChatMarkdown.test.ts
+++ b/src/components/ChatMarkdown.test.ts
@@ -229,6 +229,16 @@ describe("math rendering", () => {
);
});
+ it("escapes an unclosed display fence instead of swallowing the rest of the message as math", () => {
+ const text = "Let me compute:\n$$\n1 + 2\n\n# Step two\n- item\n\nAnd more text after.";
+ const normalized = normalizeMathDelimiters(text);
+ expect(normalized).toContain("\\$\\$");
+ expect(normalized).toContain("# Step two");
+ const html = renderToStaticMarkup(createElement(ChatMarkdown, { text }));
+ expect(html).not.toContain("katex-error");
+ expect(html).toContain("Step two");
+ });
+
it("keeps prices literal instead of rendering the text between them as math", () => {
for (const [text, expected] of [
["**1. R$ 120:** o plano custa R$ 120 por mês.", 0],
diff --git a/src/components/ChatMarkdown.tsx b/src/components/ChatMarkdown.tsx
index da46980394..4c63ac665c 100644
--- a/src/components/ChatMarkdown.tsx
+++ b/src/components/ChatMarkdown.tsx
@@ -563,6 +563,12 @@ export function normalizeMathDelimiters(text: string, imageOffsets?: Map<number,
.replace(/\\\(([\s\S]*?)\\\)/g, (_match, math: string) => `$${math.trim()}$`)
// remark-math treats flow math as a block only when the fences occupy their own lines.
.replace(/\$\$[ \t]*([^\n][\s\S]*?)[ \t]*\$\$/g, (_match, math: string) => `$$\n${math}\n$$`);
+ // An unpaired display fence makes remark-math swallow the rest of the message into one math block, so a KaTeX parse error paints the whole remainder red; escape the orphan fence.
+ const fences = [...normalized.matchAll(/\$\$/g)];
+ if (fences.length % 2 === 1) {
+ const last = fences.at(-1)!;
+ normalized = normalized.slice(0, last.index) + "\\$\\$" + normalized.slice(last.index + 2);
+ }
normalized = escapeLiteralDollars(normalized);
let shift = 0;
// oxlint-disable-next-line no-control-regex -- restore opaque code and image sentinels