Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(markdown): support TeX bracket math delimiters

mayunxiang.26f2ffbedff0b2
diff --git a/apps/desktop/src/components/Markdown.tsx b/apps/desktop/src/components/Markdown.tsx
index 63bd8c287..4466bf29e 100644
--- a/apps/desktop/src/components/Markdown.tsx
+++ b/apps/desktop/src/components/Markdown.tsx
@@ -44,6 +44,10 @@ import {
sourcePositionProps,
type SourcePositionProps,
} from "../lib/markdown-source";
+import {
+ normalizeLatexMathDelimiters,
+ remarkLatexBracketDisplay,
+} from "../lib/latex-math";
import { useAppStore } from "../stores/app-store";
import { useReferencedImageDataUrl } from "../lib/use-referenced-image-data-url";
import { useOpenChatFileRef } from "../hooks/use-preview-target";
@@ -879,12 +883,14 @@ const Block = memo(function MarkdownBlock({
}),
[raw, renderDiagrams],
);
+ const normalized = useMemo(() => normalizeLatexMathDelimiters(raw), [raw]);
const remarkPlugins = useMemo(
() => [
...staticRemarkPlugins,
+ remarkLatexBracketDisplay(raw),
remarkChatFileLinks(workspaceRoot, baseDir),
],
- [workspaceRoot, baseDir],
+ [raw, workspaceRoot, baseDir],
);
const positionedRehypePlugins = useMemo(
() => [...rehypePlugins!, [rehypeSourcePositions, { offset: sourceOffset }]] as Options["rehypePlugins"],
@@ -897,7 +903,7 @@ const Block = memo(function MarkdownBlock({
rehypePlugins={positionedRehypePlugins}
components={markdownComponents}
>
- {raw}
+ {normalized}
</ReactMarkdown>
</MarkdownBlockContext.Provider>
);
diff --git a/apps/desktop/src/lib/latex-math.ts b/apps/desktop/src/lib/latex-math.ts
new file mode 100644
index 000000000..a5c13b340
--- /dev/null
+++ b/apps/desktop/src/lib/latex-math.ts
@@ -0,0 +1,119 @@
+type MdastLike = {
+ type?: string;
+ value?: string;
+ position?: {
+ start?: { offset?: number };
+ end?: { offset?: number };
+ };
+ data?: Record<string, unknown>;
+ children?: MdastLike[];
+};
+
+/** Convert TeX-style delimiters to remark-math's equal-width dollar syntax. */
+export function normalizeLatexMathDelimiters(source: string): string {
+ const output = source.split("");
+ let offset = 0;
+ let codeTicks = 0;
+ let fence: { char: "`" | "~"; length: number } | null = null;
+ let math: { close: ")" | "]"; open: number } | null = null;
+
+ const isDelimiter = (index: number, bracket: string) => {
+ if (source[index] !== "\\" || source[index + 1] !== bracket) return false;
+ let precedingSlashes = 0;
+ for (let i = index - 1; i >= 0 && source[i] === "\\"; i--) precedingSlashes++;
+ return precedingSlashes % 2 === 0;
+ };
+
+ for (const line of source.match(/[^\n]*(?:\n|$)/g) ?? []) {
+ if (!line) continue;
+ const body = line.endsWith("\n") ? line.slice(0, -1) : line;
+ const fenceMatch = !codeTicks && !math
+ ? /^( {0,3})(`{3,}|~{3,})(.*?)(?:\r)?$/.exec(body)
+ : null;
+ if (fence) {
+ if (
+ fenceMatch?.[2]?.[0] === fence.char &&
+ fenceMatch[2].length >= fence.length &&
+ !fenceMatch[3]?.trim()
+ ) {
+ fence = null;
+ }
+ offset += line.length;
+ continue;
+ }
+ if (fenceMatch) {
+ fence = {
+ char: fenceMatch[2][0] as "`" | "~",
+ length: fenceMatch[2].length,
+ };
+ offset += line.length;
+ continue;
+ }
+
+ for (let i = 0; i < line.length;) {
+ const index = offset + i;
+ if (math) {
+ if (isDelimiter(index, math.close)) {
+ output[math.open] = output[math.open + 1] = "$";
+ output[index] = output[index + 1] = "$";
+ math = null;
+ i += 2;
+ } else {
+ i++;
+ }
+ continue;
+ }
+
+ if (line[i] === "`") {
+ let length = 1;
+ while (line[i + length] === "`") length++;
+ if (!codeTicks) codeTicks = length;
+ else if (codeTicks === length) codeTicks = 0;
+ i += length;
+ continue;
+ }
+ if (codeTicks) {
+ i++;
+ continue;
+ }
+ if (isDelimiter(index, "(") || isDelimiter(index, "[")) {
+ math = {
+ close: source[index + 1] === "(" ? ")" : "]",
+ open: index,
+ };
+ i += 2;
+ continue;
+ }
+ i++;
+ }
+ offset += line.length;
+ }
+
+ return output.join("");
+}
+
+/** Preserve TeX bracket display semantics after remark-math parses `$$…$$`. */
+export function remarkLatexBracketDisplay(source: string) {
+ return function latexBracketDisplay() {
+ return (tree: MdastLike) => {
+ const visit = (node: MdastLike) => {
+ const start = node.position?.start?.offset;
+ const end = node.position?.end?.offset;
+ if (
+ node.type === "inlineMath" &&
+ typeof start === "number" &&
+ typeof end === "number" &&
+ source.slice(start, start + 2) === "\\[" &&
+ source.slice(end - 2, end) === "\\]"
+ ) {
+ node.data = {
+ ...node.data,
+ hProperties: { className: ["language-math", "math-display"] },
+ };
+ }
+ node.children?.forEach(visit);
+ };
+ visit(tree);
+ };
+ };
+}
diff --git a/apps/desktop/test/latex-math.test.mjs b/apps/desktop/test/latex-math.test.mjs
new file mode 100644
index 000000000..1472cad97
--- /dev/null
+++ b/apps/desktop/test/latex-math.test.mjs
@@ -0,0 +1,57 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import ReactMarkdown from "react-markdown";
+import rehypeKatex from "rehype-katex";
+import remarkMath from "remark-math";
+import {
+ normalizeLatexMathDelimiters,
+ remarkLatexBracketDisplay,
+} from "../src/lib/latex-math.ts";
+
+test("normalizes TeX math delimiters without changing source length", () => {
+ for (const [source, expected] of [
+ [String.raw`before \(a+b\) after`, "before $$a+b$$ after"],
+ [String.raw`\[
+a+b
+\]`, "$$\na+b\n$$"],
+ ]) {
+ const normalized = normalizeLatexMathDelimiters(source);
+ assert.equal(normalized, expected);
+ assert.equal(normalized.length, source.length);
+ }
+});
+
+test("leaves escaped, unmatched, and code-delimited TeX markers literal", () => {
+ for (const source of [
+ String.raw`\\(escaped\\)`,
+ String.raw`\(unmatched`,
+ String.raw`__TICK__\(inline\)__TICK__`.replaceAll("__TICK__", "`"),
+ "```tex\n\\(fenced\\)\n```",
+ "~~~tex\n\\[fenced\\]\n~~~",
+ ]) {
+ assert.equal(normalizeLatexMathDelimiters(source), source);
+ }
+});
+
+test("renders TeX parentheses inline and TeX brackets as KaTeX display math", () => {
+ for (const [source, display] of [
+ [String.raw`\(a+b\)`, false],
+ [String.raw`\[a+b\]`, true],
+ ]) {
+ const html = renderToStaticMarkup(
+ createElement(
+ ReactMarkdown,
+ {
+ remarkPlugins: [remarkMath, remarkLatexBracketDisplay(source)],
+ rehypePlugins: [rehypeKatex],
+ },
+ normalizeLatexMathDelimiters(source),
+ ),
+ );
+ assert.match(html, /class="katex"/);
+ if (display) assert.match(html, /class="katex-display"/);
+ else assert.doesNotMatch(html, /class="katex-display"/);
+ }
+});
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index b10413b40..32a8ab222 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -1675,7 +1675,8 @@ Renderer: `apps/desktop/src/components/Markdown.tsx` + `apps/desktop/src/lib/shi
until its matching closing fence arrives; partial streamed diagrams never
enter the diagram parser.
- **Plugins**: `remark-gfm` (tables, task lists, strikethrough, autolinks),
- `remark-math` + `rehype-katex` (inline `$…$`, display `$$…$$`). Raw HTML is
+ `remark-math` + `rehype-katex` (inline `$…$` or `\(…\)`, display `$$…$$`
+ or `\[…\]`). Raw HTML is
parsed by `rehype-raw` and immediately constrained by the extended
`rehype-sanitize` default schema; only the renderer-owned audio/video/source
additions are admitted. KaTeX's Vite-inlined WOFF2 fonts are allowed by the
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 78b03370f..980983ec5 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -954,20 +954,22 @@ identify the platform validation still needed.
- **Preconditions**: Session active; message sent.
- **Steps**: 1) Request a long answer containing Markdown and inline/display
- math. 2) Observe the assistant response as it streams. 3) Let the answer
- complete and inspect the renderer console.
+ math using both dollar (`$…$` / `$$…$$`) and TeX bracket (`\(…\)` /
+ `\[…\]`) delimiters. 2) Observe the assistant response as it streams. 3) Let
+ the answer complete and inspect the renderer console.
- **Expected**: Runtime chunks appear progressively through the incremental
- Markdown renderer and the final response is complete. The renderer does not
- start a second animation-frame typewriter loop, raise React error 185, or
+ Markdown renderer and the final response is complete. All four math delimiter
+ forms render with KaTeX, with `\[…\]` using display layout. The renderer does
+ not start a second animation-frame typewriter loop, raise React error 185, or
reject Vite-inlined KaTeX fonts under CSP.
- **Specs linked**: `03-runtime/02-agent-runtime.md`,
`04-ux/08-component-spec.md`, `04-ux/09-interaction-patterns.md`,
`05-security/01-security.md`
- **Acceptance**: C (streamed output), Quality
- **Milestone**: M2
-- **Status**: Partially automated (protocol live-model stream plus renderer
- source regression in `renderer-stream-safety.test.mjs`; full UI observation
- remains Draft)
+- **Status**: Partially automated (protocol live-model stream, renderer source
+ regression in `renderer-stream-safety.test.mjs`, and math delimiter rendering
+ in `latex-math.test.mjs`; full UI observation remains Draft)
#### E2E-010: Abort generation
diff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.md
index 1c779e9f7..b56960f99 100644
--- a/docs/zh-CN/spec/04-ux/08-component-spec.md
+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md
@@ -1247,7 +1247,8 @@ Renderer: `apps/desktop/src/components/Markdown.tsx` + `apps/desktop/src/lib/s
直到其匹配的关闭栅栏到达;部分流图永远不会
输入图表解析器。
- **插件**:`remark-gfm`(表格、任务列表、删除线、自动链接),
- `remark-math` + `rehype-katex`(内联 `$…$`,显示 `$$…$$`)。原始 HTML 是
+ `remark-math` + `rehype-katex`(内联 `$…$` 或 `\(…\)`,显示 `$$…$$`
+ 或 `\[…\]`)。原始 HTML 是
由 `rehype-raw` 解析并立即受扩展约束
`rehype-sanitize` 默认架构;仅渲染器拥有的 audio/video/source
允许添加。 KaTeX 的 Vite 内联 WOFF2 字体被允许
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index 5eeb5cc0c..fb8e9452b 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -426,21 +426,21 @@ unit/integration 测试;代码 pull request 使用有选择且高价值的 E2E
#### E2E-009:UI 中可见的流式令牌
- **先决条件**:会话处于活动状态;消息已发送。
-- **步骤**:1) 请求包含 Markdown 和 inline/display 的长答案
- 数学。 2) 观察助理的响应。 3)让答案
- 完成并检查渲染器控制台。
-- **预期**:运行时块通过增量逐渐出现
- Markdown 渲染器和最终响应完成。渲染器不
-启动第二个动画帧打字机循环,引发 React 错误 185,或者
- 拒绝 CSP 下的 Vite 内联 KaTeX 字体。
+- **步骤**:1) 请求包含 Markdown 和行内/块级数学公式的长答案,公式同时使用
+ 美元符号(`$…$` / `$$…$$`)和 TeX 括号(`\(…\)` / `\[…\]`)分隔符。
+ 2) 观察助理的流式响应。3) 让答案完成并检查渲染器控制台。
+- **预期**:运行时块通过增量 Markdown 渲染器逐渐出现,最终响应完整。
+ 四种数学分隔符均由 KaTeX 渲染,其中 `\[…\]` 使用块级布局。渲染器不会
+ 启动第二个动画帧打字机循环、触发 React 错误 185,或因 CSP 拒绝 Vite
+ 内联的 KaTeX 字体。
- **链接规格**:`03-runtime/02-agent-runtime.md`,
`04-ux/08-component-spec.md`、`04-ux/09-interaction-patterns.md`、
`05-security/01-security.md`
- **验收**:C(流式输出),质量
- **里程碑**:M2
-- **状态**:部分自动化(协议实时模型流加上渲染器
- `renderer-stream-safety.test.mjs` 中的源回归;完整的UI观察
- 仍为草案)
+- **状态**:部分自动化(协议实时模型流、`renderer-stream-safety.test.mjs`
+ 中的渲染器源回归,以及 `latex-math.test.mjs` 中的数学分隔符渲染;
+ 完整 UI 观察仍为草案)
#### E2E-010:中止生成