Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(chat): render highlighted code and LaTeX in the assistant's markdown

M3gA-Mindc90057b19a74
diff --git a/app/src/components/assistant-ui/__tests__/markdown-text.test.tsx b/app/src/components/assistant-ui/__tests__/markdown-text.test.tsx
new file mode 100644
index 0000000000..f70b1c6205
--- /dev/null
+++ b/app/src/components/assistant-ui/__tests__/markdown-text.test.tsx
@@ -0,0 +1,110 @@
+/**
+ * The assistant's markdown on `/chat` must render code and maths the way the
+ * rest of the app already does — `AgentMessageBubble` has had syntax
+ * highlighting and KaTeX since long before the assistant-ui surface existed,
+ * and for a while the same message rendered richly in a tool result and as
+ * flat grey text in the answer above it.
+ *
+ * Every assertion here is on RENDERED OUTPUT. Asserting that the plugin array
+ * has four entries would pass against a component that renders nothing.
+ */
+import { TextMessagePartProvider } from '@assistant-ui/react';
+import { render, waitFor } from '@testing-library/react';
+import { describe, expect, it } from 'vitest';
+
+import { MarkdownText } from '../markdown-text';
+
+async function renderMarkdown(text: string) {
+ const { container } = render(
+ <TextMessagePartProvider text={text} isRunning={false}>
+ <MarkdownText />
+ </TextMessagePartProvider>
+ );
+ // `defer` hands parsing to a lower-priority render.
+ await waitFor(() => expect(container.querySelector('.aui-md')?.innerHTML).toBeTruthy());
+ return container;
+}
+
+describe('MarkdownText — syntax highlighting', () => {
+ it('tokenises a fenced block that declares a language', async () => {
+ const container = await renderMarkdown('```ts\nconst x = 1;\n```');
+
+ const code = container.querySelector('code');
+ expect(code?.className).toContain('hljs');
+ // The specific token matters: `hljs` alone is on the wrapper even when
+ // nothing was tokenised, so assert a keyword span actually carrying "const".
+ const keyword = container.querySelector('code .hljs-keyword');
+ expect(keyword).not.toBeNull();
+ expect(keyword?.textContent).toBe('const');
+ });
+
+ it('keeps the language label and the copy button on a highlighted block', async () => {
+ // The regression this guards: `rehypeHighlight` turns the <code> element's
+ // string child into token spans, which routes the kit past the branch that
+ // renders its `CodeHeader` slot. Highlighting a block must not cost it its
+ // header.
+ const container = await renderMarkdown('```ts\nconst x = 1;\n```');
+
+ expect(container.querySelector('.aui-code-header-root')).not.toBeNull();
+ expect(container.querySelector('.aui-code-header-language')?.textContent).toBe('ts');
+ expect(container.querySelector('code .hljs-keyword')).not.toBeNull();
+ });
+
+ it('still renders a header for a fence with no language', async () => {
+ const container = await renderMarkdown('```\nplain text\n```');
+
+ expect(container.querySelector('.aui-code-header-root')).not.toBeNull();
+ expect(container.querySelector('pre')?.textContent).toContain('plain text');
+ });
+
+ it('leaves inline code unhighlighted', async () => {
+ const container = await renderMarkdown('use `const` here');
+
+ const inline = container.querySelector('code');
+ expect(inline?.textContent).toBe('const');
+ expect(inline?.className).toContain('aui-md-inline-code');
+ expect(container.querySelector('.hljs-keyword')).toBeNull();
+ });
+});
+
+describe('MarkdownText — LaTeX', () => {
+ it('renders display math written with $$', async () => {
+ const container = await renderMarkdown('$$\\frac{a}{b}$$');
+
+ // KaTeX emits `.katex`; its absence means the `$$` reached the DOM as text.
+ expect(container.querySelector('.katex')).not.toBeNull();
+ expect(container.textContent).not.toContain('$$');
+ });
+
+ it('renders math emitted with backslash delimiters', async () => {
+ // What models actually emit. `remark-math` understands only `$…$`, so this
+ // passes only if the text is normalised before parsing.
+ const container = await renderMarkdown('The value \\(\\frac{a}{b}\\) is small.');
+
+ expect(container.querySelector('.katex')).not.toBeNull();
+ // KaTeX keeps the original TeX in an <annotation>, so the source survives in
+ // textContent by design. What must NOT survive is the delimiter pair — if
+ // normalisation had not run, `\(` and `\)` would still be sitting in the
+ // prose, which is exactly the bug a reader sees.
+ expect(container.textContent).not.toContain('\\(');
+ expect(container.textContent).not.toContain('\\)');
+ });
+
+ it('does NOT treat prices as math', async () => {
+ // The reason math is gated rather than always on: `remark-math` would read
+ // "$10 vs $20" as one inline formula and swallow the words between them.
+ const container = await renderMarkdown('It costs $10 vs $20 elsewhere.');
+
+ expect(container.querySelector('.katex')).toBeNull();
+ expect(container.textContent).toContain('$10 vs $20');
+ });
+});
+
+describe('MarkdownText — GFM is unaffected', () => {
+ it('still renders tables', async () => {
+ const container = await renderMarkdown('| a | b |\n| - | - |\n| 1 | 2 |');
+
+ expect(container.querySelector('table')).not.toBeNull();
+ expect(container.querySelectorAll('td')).toHaveLength(2);
+ });
+});
diff --git a/app/src/components/assistant-ui/markdown-text.tsx b/app/src/components/assistant-ui/markdown-text.tsx
index ef3985f8d7..1252d1d1d9 100644
--- a/app/src/components/assistant-ui/markdown-text.tsx
+++ b/app/src/components/assistant-ui/markdown-text.tsx
@@ -2,6 +2,7 @@
import { cn } from '@/components/assistant-ui/lib/utils';
import { TooltipIconButton } from '@/components/assistant-ui/tooltip-icon-button';
+import { useMessagePartText } from '@assistant-ui/react';
import {
type CodeHeaderProps,
MarkdownTextPrimitive,
@@ -10,13 +11,50 @@ import {
} from '@assistant-ui/react-markdown';
import '@assistant-ui/react-markdown/styles/dot.css';
import { CheckIcon, CopyIcon } from 'lucide-react';
-import { type FC, memo, useState } from 'react';
+import { type ComponentPropsWithoutRef, type FC, isValidElement, memo, useState } from 'react';
+import rehypeHighlight from 'rehype-highlight';
+import rehypeKatex from 'rehype-katex';
import remarkGfm from 'remark-gfm';
+import remarkMath from 'remark-math';
+
+import { hasLatexContent, normalizeLatexDelimiters } from '../../utils/latex';
+import { extractLanguage, extractTextContent } from '../markdown/CodeBlock';
+
+/**
+ * Plugin sets, matched to `AgentMessageBubble`'s so the two markdown surfaces
+ * cannot disagree about the same message. Module-level constants because a new
+ * array identity on every render makes `react-markdown` re-parse the whole
+ * document — on a streaming answer that is once per token.
+ *
+ * `rehypeHighlight` must precede `rehypeKatex` so code blocks inside a math
+ * environment are not processed twice (same ordering, same reason, as
+ * `AgentMessageBubble.tsx`).
+ */
+const GFM_REMARK_PLUGINS = [remarkGfm];
+const MATH_REMARK_PLUGINS = [remarkGfm, remarkMath];
+const HIGHLIGHT_REHYPE_PLUGINS = [rehypeHighlight];
+const MATH_REHYPE_PLUGINS = [rehypeHighlight, rehypeKatex];
const MarkdownTextImpl = () => {
+ // Math is GATED, not always-on, and the gate is `hasLatexContent` rather than
+ // "contains a $". `remark-math` would otherwise read "$10 vs $20" as an inline
+ // formula and eat the prose between them; the signature requires a real LaTeX
+ // signal (`\frac`, `\begin`, `\[`, `\(`, `$$`). Same call the legacy
+ // surface makes, so a message renders identically on both.
+ //
+ // Read the raw part text, not the smoothed text `MarkdownTextPrimitive`
+ // renders: the gate must not flip mid-reveal.
+ const { text } = useMessagePartText();
+ const hasMath = hasLatexContent(text);
+
return (
<MarkdownTextPrimitive
- remarkPlugins={[remarkGfm]}
+ remarkPlugins={hasMath ? MATH_REMARK_PLUGINS : GFM_REMARK_PLUGINS}
+ rehypePlugins={hasMath ? MATH_REHYPE_PLUGINS : HIGHLIGHT_REHYPE_PLUGINS}
+ // `\[ … \]` / `\( … \)` are what models actually emit; `remark-math`
+ // only understands `$ … $`. Runs before the smooth reveal, so the text is
+ // normalised once rather than per frame.
+ preprocess={hasMath ? normalizeLatexDelimiters : undefined}
className="aui-md"
components={defaultComponents}
defer
@@ -66,6 +104,56 @@ const useCopyToClipboard = ({ copiedDuration = 3000 }: { copiedDuration?: number
return { isCopied, copyToClipboard };
};
+/** The slice of a hast `<code>` element this file reads. */
+type HastElement = { properties?: { className?: string | string[] } };
+
+/**
+ * The fenced-code block: our header bar, then the code body.
+ *
+ * The header is rendered HERE rather than through the kit's `CodeHeader` slot,
+ * and that is load-bearing. `rehypeHighlight` replaces the `<code>` element's
+ * single string child with `<span class="hljs-*">` nodes, and the kit branches
+ * on exactly that: a string child takes the `DefaultCodeBlock` path (header +
+ * body), anything else takes `DefaultCodeBlockContent` (body only). So wiring
+ * the highlighter through the `CodeHeader` slot silently drops the language
+ * label and the copy button from every block that has a language — i.e. every
+ * block a reader cares about — while leaving them on untagged ones. Verified
+ * both ways before this was written.
+ *
+ * `Pre` is called on both paths, so owning the header here gives one code path
+ * instead of two and the highlighted and unhighlighted cases render alike.
+ */
+const CodeBlockPre: FC<ComponentPropsWithoutRef<'pre'>> = ({ className, children, ...props }) => {
+ // The child is the kit's wrapped `<code>`. Its React props carry only `node`
+ // and `children` — the `className` is merged in downstream, inside the
+ // wrapper — so the `language-*` class has to be read off the hast node, where
+ // `className` is an array of tokens rather than a string.
+ const codeProps = isValidElement<{ node?: HastElement; children?: unknown }>(children)
+ ? children.props
+ : undefined;
+ const hastClassName = codeProps?.node?.properties?.className;
+
+ return (
+ <>
+ <CodeHeader
+ language={
+ extractLanguage(Array.isArray(hastClassName) ? hastClassName.join(' ') : hastClassName) ??
+ undefined
+ }
+ code={extractTextContent(codeProps?.children)}
+ />
+ <pre
+ className={cn(
+ 'aui-md-pre border-border/50 bg-muted/30 overflow-x-auto rounded-t-none rounded-b-xl border border-t-0 p-3.5 text-[13px] leading-relaxed',
+ className
+ )}
+ {...props}>
+ {children}
+ </pre>
+ </>
+ );
+};
+
const defaultComponents = memoizeMarkdownComponents({
h1: ({ className, ...props }) => (
<h1
@@ -202,15 +290,7 @@ const defaultComponents = memoizeMarkdownComponents({
sup: ({ className, ...props }) => (
<sup className={cn('aui-md-sup [&>a]:text-xs [&>a]:no-underline', className)} {...props} />
),
- pre: ({ className, ...props }) => (
- <pre
- className={cn(
- 'aui-md-pre border-border/50 bg-muted/30 overflow-x-auto rounded-t-none rounded-b-xl border border-t-0 p-3.5 text-[13px] leading-relaxed',
- className
- )}
- {...props}
- />
- ),
+ pre: CodeBlockPre,
code: function Code({ className, ...props }) {
const isCodeBlock = useIsMarkdownCodeBlock();
return (
@@ -224,5 +304,4 @@ const defaultComponents = memoizeMarkdownComponents({
/>
);
},
- CodeHeader,
});
diff --git a/app/src/components/markdown/CodeBlock.tsx b/app/src/components/markdown/CodeBlock.tsx
index 4335ef169d..8a295c1faf 100644
--- a/app/src/components/markdown/CodeBlock.tsx
+++ b/app/src/components/markdown/CodeBlock.tsx
@@ -23,7 +23,7 @@ import { useT } from '../../lib/i18n/I18nContext';
* and return only the language part (e.g. "typescript"), or null if not
* present. rehype-highlight adds this class when a fenced block is tagged.
*/
-function extractLanguage(className?: string): string | null {
+export function extractLanguage(className?: string): string | null {
if (!className) return null;
const match = /\blanguage-(\S+)/.exec(className);
return match ? match[1] : null;
@@ -42,7 +42,7 @@ function formatLanguageLabel(lang: string): string {
* Walk a React child tree and collect all text nodes as a single string.
* This gives us the raw source code for the clipboard copy.
*/
-function extractTextContent(node: unknown): string {
+export function extractTextContent(node: unknown): string {
if (typeof node === 'string') return node;
if (typeof node === 'number') return String(node);
if (Array.isArray(node)) return node.map(extractTextContent).join('');