fix(webui): preserve TeX formula boundaries in streaming Markdown

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-02 20:44:50 +08:00
1 parent d0d0a44e57
commit 810802e016
9 files changed
+329 -46

No files matched your search

@@ -0,0 +1,102 @@
import remarkMath from "remark-math";
import remarkParse from "remark-parse";
import { parseMarkdownIntoBlocks } from "streamdown";
import { unified } from "unified";
import { describe, expect, it } from "vitest";
import { parseMathAwareMarkdownBlocks } from "@/lib/markdown-streaming-blocks";
import { remarkTexMath } from "@/lib/remark-tex-math";
const formula = String.raw`\[
\tan\left(\frac{\mathrm{HFOV}}{2}\right)
=
\frac{X}{Z}
\]`;
function expectIntact(source: string, protectedSource: string) {
const blocks = parseMathAwareMarkdownBlocks(source);
expect(blocks.join("")).toBe(source);
expect(blocks.some((block) => block.includes(protectedSource))).toBe(true);
return blocks;
}
describe("math-aware streaming blocks", () => {
it("merges a TeX formula split at a Setext equals line and blank lines", () => {
const source = "Before\n\n" + formula + "\n\nAfter";
expect(parseMarkdownIntoBlocks(source).some((block) => block.includes(formula))).toBe(false);
const blocks = expectIntact(source, formula);
expect(blocks[0]).toBe("Before");
expect(blocks.at(-1)).toBe("After");
});
it("keeps every unfinished display-math prefix together without carrying state", () => {
for (let end = 2; end <= formula.length; end++) {
const partial = formula.slice(0, end);
expectIntact("Before\n\n" + partial, partial);
}
expect(parseMathAwareMarkdownBlocks("Replacement\n\nPlain text")).toEqual(
parseMarkdownIntoBlocks("Replacement\n\nPlain text"),
);
});
it.each([
String.raw`\[a
=
b\]`,
"Before\n" + formula,
String.raw`\(a + b\)`,
"$$a\n=\nb\n\n$$",
"$$$\na\n=\nb\n\n$$$",
])("keeps math intact with surrounding text and supported fences: %s", (math) => {
expectIntact(math + "\n\nAfter", math);
});
it.each([
formula.split("\n").map((line) => "> " + line).join("\n"),
"- Item\n\n" + formula.split("\n").map((line) => " " + line).join("\n"),
])("protects the enclosing container: %s", (container) => {
expectIntact(container + "\n\nAfter", container);
});
it("does not consume text outside an unfinished blockquote formula", () => {
const quoted = "> \\[\n> a\n> =\n> b";
const blocks = expectIntact(quoted + "\n\nOutside\n\nNext", quoted);
expect(blocks.at(-1)).toBe("Next");
expect(blocks.some((block) => block.includes(quoted) && block.includes("Outside"))).toBe(false);
});
it.each([
"", "First\n\n## Heading\n\nLast", "Prices: $20 and $30.\n\nNext",
"```latex\n" + formula + "\n```\n\nAfter",
formula.split("\n").map((line) => " " + line).join("\n") + "\n\nAfter",
"`" + formula + "`\n\nAfter",
String.raw`\\[a
=
b\\]
After`,
"$$a$$ trailing prose\n\nAfter",
"[link][target]\n\nNext\n\n[target]: https://example.com",
"<div>\n\nOrdinary HTML\n\n</div>\n\nAfter",
])("preserves default grouping when no math boundary needs repair: %s", (source) => {
expect(parseMathAwareMarkdownBlocks(source)).toEqual(parseMarkdownIntoBlocks(source));
});
it("preserves CRLF source bytes rather than comparing normalized offsets", () => {
const source = "Before\r\n\r\n" + formula.replaceAll("\n", "\r\n") + "\r\n\r\nAfter";
expect(parseMathAwareMarkdownBlocks(source)).toEqual([source]);
});
it("does not enable unfinished formulas in the rendering grammar", () => {
const source = String.raw`\[
a
=
b`;
const strict = unified().use(remarkParse).use(remarkMath).use(remarkTexMath);
const boundaries = unified().use(remarkParse).use(remarkMath)
.use(remarkTexMath, { allowUnclosedFlow: true });
expect(strict.parse(source).children.some((node) => node.type === "math")).toBe(false);
expect(boundaries.parse(source).children.map((node) => node.type)).toEqual(["math"]);
});
});
@@ -0,0 +1,33 @@
import { render, waitFor } from "@testing-library/react";
import { expect, it } from "vitest";
import { MarkdownText } from "@/components/MarkdownText";
it("retains a rendered TeX formula when an assistant response completes in streaming layout", async () => {
const source = String.raw`Before
\[
\tan\left(\frac{\mathrm{HFOV}}{2}\right)
=
\frac{W}{2f_x}
\]
After`;
const { container, rerender } = render(
<MarkdownText streaming preserveStreamingLayout>{source}</MarkdownText>,
);
await waitFor(() => expect(container.querySelector(".katex-display")).toBeInTheDocument(), {
timeout: 10_000,
});
const formula = container.querySelector(".katex-display");
const tex = container.querySelector("annotation")?.textContent;
rerender(<MarkdownText preserveStreamingLayout>{source}</MarkdownText>);
await waitFor(() => expect(container.querySelector(".katex-display")).toBe(formula));
expect(container.querySelector("annotation")?.textContent).toBe(tex);
expect(container.querySelector(".katex-error")).toBeNull();
expect(container.querySelector("h1, h2")).toBeNull();
expect(container).toHaveTextContent("Before");
expect(container).toHaveTextContent("After");
});
@@ -842,6 +842,48 @@ describe("MarkdownTextRenderer", () => {
expect(container.querySelector("annotation")).toHaveTextContent("C = \\sum_i c_i");
});
it.each([false, true])("keeps TeX equations out of Markdown headings (streaming=%s)", (streaming) => {
const formula = String.raw`\tan\left(\frac{\mathrm{HFOV}}{2}\right)
=
\frac{X}{Z}`;
const source = "Before\n\n\\[\n" + formula + "\n\n\\]\n\nAfter";
const { container } = render(
<MarkdownTextRenderer streaming={streaming}>{source}</MarkdownTextRenderer>,
);
expect(container.querySelector(".katex-display annotation")?.textContent?.trim()).toBe(formula);
expect(container.querySelector(".katex-error")).toBeNull();
expect(container.querySelector("h1, h2")).toBeNull();
expect(container).toHaveTextContent("Before");
expect(container).toHaveTextContent("After");
});
it("keeps an unfinished TeX command renderable when Remend adds a link suffix", () => {
const { container } = render(
<MarkdownTextRenderer streaming>{"\\[\n\\"}</MarkdownTextRenderer>,
);
expect(container.textContent).not.toBe("");
});
it("recovers a complete TeX equation after every streaming prefix", () => {
const source = String.raw`\[
\boxed{
\mathrm{HFOV}
=
2\arctan\left(\frac{W}{2f_x}\right)
}
\]`;
const { container, rerender } = render(<MarkdownTextRenderer streaming>{""}</MarkdownTextRenderer>);
for (let end = 1; end <= source.length; end++) {
rerender(<MarkdownTextRenderer streaming>{source.slice(0, end)}</MarkdownTextRenderer>);
}
rerender(<MarkdownTextRenderer streaming>{source + "\n\nFollowing paragraph"}</MarkdownTextRenderer>);
expect(container.querySelectorAll(".katex-display")).toHaveLength(1);
expect(container.querySelector(".katex-error")).toBeNull();
expect(container.querySelector("h1, h2")).toBeNull();
expect(container).toHaveTextContent("Following paragraph");
});
it("still renders explicit math blocks", () => {
const { container } = render(
<MarkdownTextRenderer>{"$$x^2 + y^2 = z^2$$"}</MarkdownTextRenderer>,