Skip to content

Commit ba05c22

Browse files
orbitingfleaclaude
andcommitted
fix(web): render chat math with KaTeX
Chat messages showed raw TeX: `$x^2$`, `\(x\)`, `$$…$$`, and `\[…\]` all rendered as literal text, because the markdown pipeline had no math parser. Parse math with remark-math and render it with rehype-katex in both chat markdown remark plugin lists. A pnpm override pins remark-math's parser to micromark-extension-llm-math 3.1.1-20250610, the fork LibreChat ships, which reads all four delimiters structurally, so code fences, code spans, and link destinations are safe by construction. Two rules the library lacks are added as a small remark plugin. Display delimiters mean display everywhere: `$$…$$` and `\[…\]` render as block math even mid-paragraph, where the parser reads them inline. And Pandoc's currency guard: single-dollar math must not start or end with whitespace and must not be followed by a digit, so "$5 and $3" and "$20,000-$30,000" stay literal. `\$` forces a literal dollar. Co-Authored-By: Claude Fable 5.1 <[email protected]>
1 parent 827345a commit ba05c22

5 files changed

Lines changed: 233 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.16.0",
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: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,71 @@ describe("hasMarkdownFilePrimaryAction", () => {
9292
});
9393
});
9494

95+
describe("ChatMarkdown math", () => {
96+
it.each([false, true])("renders all four math notations with lineBreaks=%s", (lineBreaks) => {
97+
const html = renderToStaticMarkup(
98+
<ChatMarkdown
99+
cwd="/tmp/project"
100+
text={"Math $x^2$, $$w_0$$ and \\(y+1\\)\n\\[z-2\\]"}
101+
lineBreaks={lineBreaks}
102+
/>,
103+
);
104+
105+
expect(html.match(/class="katex"/g)).toHaveLength(4);
106+
for (const math of ["x^2", "w_0", "y+1", "z-2"]) expect(html).toContain(math);
107+
});
108+
109+
it("renders double-dollar and bracket math as display even mid-paragraph", () => {
110+
const html = renderToStaticMarkup(
111+
<ChatMarkdown
112+
cwd="/tmp/project"
113+
text={"Inline $x^2$ and \\(y+1\\), display $$w_0$$ and \\[z-2\\] here."}
114+
/>,
115+
);
116+
117+
expect(html.match(/class="katex"/g)).toHaveLength(4);
118+
expect(html.match(/katex-display/g)).toHaveLength(2);
119+
expect(html).toContain("here.");
120+
});
121+
122+
it("renders display math whose brackets sit on their own lines", () => {
123+
const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={"\\[\na+b\n\\]"} />);
124+
125+
expect(html).toContain("katex-display");
126+
expect(html).toContain("a+b");
127+
});
128+
129+
it("renders an escaped citation as math", () => {
130+
const html = renderToStaticMarkup(
131+
<ChatMarkdown cwd="/tmp/project" text={"See \\[1\\] for details"} />,
132+
);
133+
134+
expect(html.match(/class="katex"/g)).toHaveLength(1);
135+
});
136+
137+
it.each([
138+
"The total is $12.50 today.",
139+
"Between $5 and $3 for each.",
140+
"Pay $ 100 or $200 now.",
141+
"It costs $20,000-$30,000 to build.",
142+
])("keeps prices literal: %s", (text) => {
143+
const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />);
144+
145+
expect(html).toContain(text);
146+
expect(html).not.toContain('class="katex"');
147+
});
148+
149+
it("leaves dollars and backslashes in code alone", () => {
150+
const html = renderToStaticMarkup(
151+
<ChatMarkdown cwd="/tmp/project" text={"Run `echo $x^2$` in\n```sh\nprice=$5 and $3\n```"} />,
152+
);
153+
154+
expect(html).toContain("echo $x^2$");
155+
expect(html).toContain("price=$5 and $3");
156+
expect(html).not.toContain('class="katex"');
157+
});
158+
});
159+
95160
describe("ChatMarkdown file option chips", () => {
96161
it("keeps the fallback button text selectable", () => {
97162
const html = renderToStaticMarkup(

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

Lines changed: 58 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,12 +67,15 @@ import React, {
6767
import type { Components, Options as ReactMarkdownOptions } from "react-markdown";
6868
import ReactMarkdown from "react-markdown";
6969
import { defaultUrlTransform } from "react-markdown";
70+
import rehypeKatex from "rehype-katex";
7071
import rehypeRaw from "rehype-raw";
7172
import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
7273
import remarkBreaks from "remark-breaks";
7374
import { parseAssistantCitationHref } from "@t3tools/shared/assistantCitations";
7475
import { AssistantCitationChip } from "./chat/AssistantCitationChip";
7576
import remarkGfm from "remark-gfm";
77+
import remarkMath from "remark-math";
78+
import "katex/dist/katex.min.css";
7679
import { remarkGithubAlerts } from "../markdown-github-alerts";
7780
import {
7881
artifactTemplateFromHastProperties,
@@ -380,7 +383,13 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
380383
attributes: {
381384
...defaultSchema.attributes,
382385
"*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
383-
code: [...(defaultSchema.attributes?.code ?? []), "dataCodeMeta", "dataInlineCode"],
386+
code: [
387+
// First match wins: keep the display marker `remarkMathDelimiters` sets for KaTeX.
388+
["className", /^language-./, "math-display"],
389+
...(defaultSchema.attributes?.code ?? []),
390+
"dataCodeMeta",
391+
"dataInlineCode",
392+
],
384393
blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"],
385394
div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES],
386395
a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"],
@@ -398,6 +407,8 @@ const CHAT_MARKDOWN_REMARK_PLUGINS = [
398407
remarkGithubAlerts,
399408
remarkNormalizeListItemIndentation,
400409
remarkCodexDirectives,
410+
remarkMath,
411+
remarkMathDelimiters,
401412
remarkPreserveCodeMeta,
402413
remarkNormalizeLinksAndTagInlineCode,
403414
] satisfies NonNullable<ReactMarkdownOptions["remarkPlugins"]>;
@@ -407,6 +418,8 @@ const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS = [
407418
remarkGithubAlerts,
408419
remarkNormalizeListItemIndentation,
409420
remarkCodexDirectives,
421+
remarkMath,
422+
remarkMathDelimiters,
410423
remarkBreaks,
411424
remarkPreserveCodeMeta,
412425
remarkNormalizeLinksAndTagInlineCode,
@@ -416,8 +429,14 @@ const CHAT_MARKDOWN_REHYPE_PLUGINS = [
416429
rehypeRaw,
417430
rehypePreserveImageSourceMeta,
418431
[rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],
432+
// KaTeX renders after sanitizing: its own markup is generated, not authored.
433+
rehypeKatex,
419434
] satisfies NonNullable<ReactMarkdownOptions["rehypePlugins"]>;
420435

436+
const KATEX_ONLY_REHYPE_PLUGINS = [rehypeKatex] satisfies NonNullable<
437+
ReactMarkdownOptions["rehypePlugins"]
438+
>;
439+
421440
/** GitHub's own five alert kinds, in its colors: the glyph names the urgency, the title says it. */
422441
const GITHUB_ALERT_PRESENTATIONS: Record<
423442
string,
@@ -496,12 +515,49 @@ type MarkdownAstNode = {
496515
type?: string;
497516
meta?: unknown;
498517
url?: string;
518+
value?: string;
519+
position?: { start: { offset?: number }; end: { offset?: number } };
499520
data?: {
500521
hProperties?: Record<string, unknown>;
501522
};
502523
children?: MarkdownAstNode[];
503524
};
504525

526+
/**
527+
* Two rules the math parser lacks. Display delimiters mean display everywhere:
528+
* `$$…$$` and `\[…\]` render as block math even mid-paragraph, where the parser
529+
* reads them inline. And Pandoc's currency guard: `remark-math` reads `$…$`
530+
* with code-span rules, which turns prices such as "$5 and $3" into math, so
531+
* demote every single-dollar span whose content starts or ends with whitespace
532+
* or whose closing dollar is followed by a digit. Write `\$` to force a literal.
533+
*/
534+
function remarkMathDelimiters() {
535+
return (tree: MarkdownAstNode, file: { value?: unknown }) => {
536+
const source = typeof file.value === "string" ? file.value : "";
537+
const visit = (node: MarkdownAstNode) => {
538+
node.children?.forEach((child, index, children) => {
539+
visit(child);
540+
const from = child.position?.start.offset;
541+
const to = child.position?.end.offset;
542+
if (child.type !== "inlineMath" || from === undefined || to === undefined) return;
543+
const raw = source.slice(from, to);
544+
if (raw.startsWith("$$") || raw.startsWith("\\[")) {
545+
child.data = {
546+
...child.data,
547+
hProperties: { className: ["language-math", "math-display"] },
548+
};
549+
return;
550+
}
551+
if (!raw.startsWith("$")) return;
552+
const content = raw.slice(1, -1);
553+
if (/^\S/.test(content) && /\S$/.test(content) && !/\d/.test(source[to] ?? "")) return;
554+
children[index] = { type: "text", value: raw };
555+
});
556+
};
557+
visit(tree);
558+
};
559+
}
560+
505561
function remarkPreserveCodeMeta() {
506562
return (tree: MarkdownAstNode) => {
507563
const visit = (node: MarkdownAstNode) => {
@@ -2782,7 +2838,7 @@ function ChatMarkdown({
27822838
>
27832839
<ReactMarkdown
27842840
remarkPlugins={remarkPlugins}
2785-
rehypePlugins={parseRawHtml ? CHAT_MARKDOWN_REHYPE_PLUGINS : undefined}
2841+
rehypePlugins={parseRawHtml ? CHAT_MARKDOWN_REHYPE_PLUGINS : KATEX_ONLY_REHYPE_PLUGINS}
27862842
skipHtml={false}
27872843
components={markdownComponents}
27882844
urlTransform={markdownUrlTransform}

0 commit comments

Comments
 (0)