Skip to content

Commit b7a83a0

Browse files
orbitingfleaclaude
andcommitted
fix(web): render chat math with KaTeX
Chat responses commonly contain dollar, parenthesized, and bracketed math delimiters that were rendered as literal source. Normalize provider-style delimiters outside protected markdown regions, pair inline dollars with Pandoc-style delimiter rules, and render valid formulas through remark-math and KaTeX while keeping unpaired dollars literal. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent f8e4acc commit b7a83a0

6 files changed

Lines changed: 454 additions & 6 deletions

File tree

‎apps/web/package.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,15 +38,18 @@
3838
"jose": "catalog:",
3939
"jsonc-parser": "3.3.1",
4040
"jszip": "3.10.1",
41+
"katex": "^0.18.4",
4142
"lexical": "^0.41.0",
4243
"lucide-react": "^0.564.0",
4344
"react": "19.2.6",
4445
"react-dom": "19.2.6",
4546
"react-markdown": "^10.1.0",
47+
"rehype-katex": "^7.0.1",
4648
"rehype-raw": "^7.0.0",
4749
"rehype-sanitize": "^6.0.0",
4850
"remark-breaks": "^4.0.0",
4951
"remark-gfm": "^4.0.1",
52+
"remark-math": "^6.0.0",
5053
"tailwind-merge": "^3.4.0",
5154
"zustand": "^5.0.11"
5255
},
@@ -59,6 +62,7 @@
5962
"@types/babel__core": "^7.20.5",
6063
"@types/compression": "^1.8.1",
6164
"@types/culori": "^4.0.1",
65+
"@types/katex": "^0.16.8",
6266
"@types/react": "~19.2.14",
6367
"@types/react-dom": "~19.2.3",
6468
"@vercel/config": "^0.3.0",

‎apps/web/src/components/ChatMarkdown.test.tsx‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,27 @@ describe("hasMarkdownFilePrimaryAction", () => {
9292
});
9393
});
9494

95+
describe("ChatMarkdown math", () => {
96+
it.each([false, true])("renders inline math with lineBreaks=%s", (lineBreaks) => {
97+
const html = renderToStaticMarkup(
98+
<ChatMarkdown cwd="/tmp/project" text={"Math $x^2$ and \\(y+1\\)"} lineBreaks={lineBreaks} />,
99+
);
100+
101+
expect(html.match(/class="katex"/g)).toHaveLength(2);
102+
expect(html).toContain("x^2");
103+
expect(html).toContain("y+1");
104+
});
105+
106+
it("keeps an ordinary price literal", () => {
107+
const html = renderToStaticMarkup(
108+
<ChatMarkdown cwd="/tmp/project" text="The total is $12.50 today." />,
109+
);
110+
111+
expect(html).toContain("The total is $12.50 today.");
112+
expect(html).not.toContain('class="katex"');
113+
});
114+
});
115+
95116
describe("ChatMarkdown file option chips", () => {
96117
it("keeps the fallback button text selectable", () => {
97118
const html = renderToStaticMarkup(

‎apps/web/src/components/ChatMarkdown.tsx‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,10 +63,13 @@ import React, {
6363
import type { Components, Options as ReactMarkdownOptions } from "react-markdown";
6464
import ReactMarkdown from "react-markdown";
6565
import { defaultUrlTransform } from "react-markdown";
66+
import rehypeKatex from "rehype-katex";
6667
import rehypeRaw from "rehype-raw";
6768
import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
6869
import remarkBreaks from "remark-breaks";
6970
import remarkGfm from "remark-gfm";
71+
import remarkMath from "remark-math";
72+
import "katex/dist/katex.min.css";
7073
import { remarkGithubAlerts } from "../markdown-github-alerts";
7174
import {
7275
artifactTemplateFromHastProperties,
@@ -113,6 +116,7 @@ import {
113116
serializeTableElementToMarkdown,
114117
} from "../markdown-clipboard";
115118
import { remarkNormalizeListItemIndentation } from "../markdown-list-indentation";
119+
import { normalizeChatMath } from "../markdown-math";
116120
import {
117121
extractMarkdownLinkHrefs,
118122
isWindowsDrivePathHref,
@@ -374,6 +378,7 @@ const CHAT_MARKDOWN_REMARK_PLUGINS = [
374378
remarkGithubAlerts,
375379
remarkNormalizeListItemIndentation,
376380
remarkCodexDirectives,
381+
remarkMath,
377382
remarkPreserveCodeMeta,
378383
remarkNormalizeLinksAndTagInlineCode,
379384
] satisfies NonNullable<ReactMarkdownOptions["remarkPlugins"]>;
@@ -383,6 +388,7 @@ const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS = [
383388
remarkGithubAlerts,
384389
remarkNormalizeListItemIndentation,
385390
remarkCodexDirectives,
391+
remarkMath,
386392
remarkBreaks,
387393
remarkPreserveCodeMeta,
388394
remarkNormalizeLinksAndTagInlineCode,
@@ -392,8 +398,13 @@ const CHAT_MARKDOWN_REHYPE_PLUGINS = [
392398
rehypeRaw,
393399
rehypePreserveImageSourceMeta,
394400
[rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],
401+
rehypeKatex,
395402
] satisfies NonNullable<ReactMarkdownOptions["rehypePlugins"]>;
396403

404+
const KATEX_ONLY_REHYPE_PLUGINS = [rehypeKatex] satisfies NonNullable<
405+
ReactMarkdownOptions["rehypePlugins"]
406+
>;
407+
397408
/** GitHub's own five alert kinds, in its colors: the glyph names the urgency, the title says it. */
398409
const GITHUB_ALERT_PRESENTATIONS: Record<
399410
string,
@@ -2453,12 +2464,12 @@ function ChatMarkdown({
24532464
remarkPlugins={
24542465
lineBreaks ? CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS : CHAT_MARKDOWN_REMARK_PLUGINS
24552466
}
2456-
rehypePlugins={parseRawHtml ? CHAT_MARKDOWN_REHYPE_PLUGINS : undefined}
2467+
rehypePlugins={parseRawHtml ? CHAT_MARKDOWN_REHYPE_PLUGINS : KATEX_ONLY_REHYPE_PLUGINS}
24572468
skipHtml={false}
24582469
components={markdownComponents}
24592470
urlTransform={markdownUrlTransform}
24602471
>
2461-
{text}
2472+
{normalizeChatMath(text)}
24622473
</ReactMarkdown>
24632474
</div>
24642475
);

‎apps/web/src/markdown-math.test.ts‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import { describe, expect, it } from "vite-plus/test";
2+
3+
import { normalizeChatMath } from "./markdown-math";
4+
5+
describe("normalizeChatMath", () => {
6+
it.each([
7+
["\\[x+y\\]\n$$z$$", "$$\nx+y\n$$\n$$\nz\n$$"],
8+
[
9+
"math $x^2+1$ and $$\\sum_{i=1}^n i$$ reply ok",
10+
"math $x^2+1$ and \n\n$$\n\\sum_{i=1}^n i\n$$\n\n reply ok",
11+
],
12+
["before\n\\[\nx=\\pm i\n\\]\nafter", "before\n$$\nx=\\pm i\n$$\nafter"],
13+
["Inline \\(x^2=-1\\)", "Inline $x^2=-1$"],
14+
])("normalizes chat math in %s", (markdown, expected) => {
15+
expect(normalizeChatMath(markdown)).toBe(expected);
16+
});
17+
18+
it.each([
19+
["$5.5$", "$5.5$"],
20+
["$5$", "$5$"],
21+
["价格:$5 和 $5/month", "价格:\\$5 和 \\$5/month"],
22+
["$20,000 and $30,000", "\\$20,000 and \\$30,000"],
23+
])("keeps only valid Pandoc-style dollar pairs in %s", (markdown, expected) => {
24+
expect(normalizeChatMath(markdown)).toBe(expected);
25+
});
26+
27+
it("keeps unpaired dollar amounts literal", () => {
28+
expect(normalizeChatMath("Prices are $5 and $3 today.")).toBe(
29+
"Prices are \\$5 and \\$3 today.",
30+
);
31+
expect(normalizeChatMath("The total is $12.50 today.")).toBe("The total is \\$12.50 today.");
32+
});
33+
34+
it("does not alter math-like text in fenced or inline code", () => {
35+
const markdown = ["```txt", "~~~", "\\(x\\)", "```", "``code ` \\(y\\)`` and \\(z\\)"].join(
36+
"\n",
37+
);
38+
expect(normalizeChatMath(markdown)).toBe(
39+
["```txt", "~~~", "\\(x\\)", "```", "``code ` \\(y\\)`` and $z$"].join("\n"),
40+
);
41+
});
42+
43+
it("does not alter math-like text in link destinations or HTML tags", () => {
44+
const markdown =
45+
'[docs](https://example.com/\\(intro\\)) <a href="/\\(raw\\)">link</a> \\(x\\)';
46+
expect(normalizeChatMath(markdown)).toBe(
47+
'[docs](https://example.com/\\(intro\\)) <a href="/\\(raw\\)">link</a> $x$',
48+
);
49+
});
50+
51+
it("escapes dollar signs that cannot form valid pairs", () => {
52+
expect(normalizeChatMath("$5-$10, ($5 off), $5%, and $5: each")).toBe(
53+
"\\$5-\\$10, (\\$5 off), \\$5%, and \\$5: each",
54+
);
55+
});
56+
57+
it("normalizes multiple display spans on one line separately", () => {
58+
expect(normalizeChatMath("$$a$$ and $$b$$")).toBe("\n\n$$\na\n$$\n\n and \n\n$$\nb\n$$\n\n");
59+
});
60+
61+
it("normalizes math in prose comparisons", () => {
62+
expect(normalizeChatMath("for 0 < x, \\(x^2\\) grows when x > 1")).toBe(
63+
"for 0 < x, $x^2$ grows when x > 1",
64+
);
65+
});
66+
67+
it("does not alter indented code or blockquote fenced code", () => {
68+
const markdown = [
69+
" code block \\(x\\) indented",
70+
"> ```txt",
71+
"> \\(y\\)",
72+
"> ```",
73+
"after \\(z\\)",
74+
].join("\n");
75+
expect(normalizeChatMath(markdown)).toBe(
76+
[" code block \\(x\\) indented", "> ```txt", "> \\(y\\)", "> ```", "after $z$"].join("\n"),
77+
);
78+
});
79+
80+
it("only treats bracket math as display math when it stands alone", () => {
81+
// Inline bracket escapes are commonly emitted as citations, so only a
82+
// whole-line \\[…] span is interpreted as display math.
83+
expect(normalizeChatMath("See \\[1\\] for details\n\\[x+y\\]")).toBe(
84+
"See \\[1\\] for details\n$$\nx+y\n$$",
85+
);
86+
});
87+
});

0 commit comments

Comments
 (0)