A local-first multi-agent app development platform, built on PenguinHarness
Render LaTeX math on every Markdown surface (#503)
Yaowei Zhengb952753cfb47
diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.mdindex 40d0c419..c2d0f7e4 100644--- a/THIRD-PARTY-NOTICES.md+++ b/THIRD-PARTY-NOTICES.md@@ -1,12 +1,18 @@# Third-party noticesPenguinHarness itself is licensed under Apache-2.0 (see [LICENSE](LICENSE)). Some **distributed-release artifacts** additionally bundle third-party programs, which keep their own licenses. This-file records those, and how to obtain their source.+release artifacts** additionally bundle third-party programs and files, which keep their own+licenses. This file records those, and how to obtain their source.-Nothing listed here is part of this repository — the components are downloaded by the release-workflow (`.github/workflows/release.yml`) and placed alongside the application inside the-release archives. Installing from npm (`@prismshadow/penguin-cli`) bundles none of them.+Nothing listed here is source code of this repository. The programs below are downloaded by the+release workflow (`.github/workflows/release.yml`) and placed alongside the application inside the+release archives; the fonts are copied out of an npm dependency into the built web assets.+Installing from npm (`@prismshadow/penguin-cli`) bundles none of them.++What earns an entry is a third-party work redistributed **as its own file**. An npm package whose+JavaScript is compiled and minified into the application bundle (React, Shiki, xterm.js, KaTeX's own+code, ...) is not listed: its license travels with it in `node_modules` and in the lockfile, and+repeating every one of them here would be a second, staler copy of `pnpm-lock.yaml`.## Node.js runtime — `node/`@@ -45,3 +51,21 @@ MinGit is published by the Git for Windows project at:The bundled binaries are byte-identical to the `MinGit-<version>-64-bit.zip` asset of that tag;no patches are applied. If you need the corresponding source and cannot obtain it from the URLsabove, open an issue on this repository and we will provide it.++## KaTeX fonts — `KaTeX_*.woff2` in the web assets++Present wherever the Web App ships: every release archive, the desktop application, and the assets+the server serves.++Math rendering uses [KaTeX](https://katex.org), whose typefaces are separate font files rather than+code. The web build copies them unmodified out of the `katex` npm package into the application's+asset directory, where the browser fetches them by URL; bundling them locally is what lets the+desktop application render formulas with no network. Only the woff2 format is copied — the woff and+truetype fallbacks KaTeX also ships are dropped at build time (`dropNonWoff2FontSources` in+`packages/web/vite.config.ts`).++**License: MIT**, the same license as the rest of KaTeX. The full text ships inside the package, at+`node_modules/katex/LICENSE`.++Source: <https://github.com/KaTeX/KaTeX> — the tag matching the `katex` version resolved in+`pnpm-lock.yaml`. The font sources and the script that builds them live in that repository.diff --git a/changelog/unreleased/2026-08-26-markdown-math.md b/changelog/unreleased/2026-08-26-markdown-math.mdnew file mode 100644index 00000000..79f6b94c--- /dev/null+++ b/changelog/unreleased/2026-08-26-markdown-math.md@@ -0,0 +1,43 @@+# LaTeX formulas render on every Markdown surface++- **Date:** 2026-08-26+- **Type:** feature+- **Scope:** `web`+- **PR:** [#503](https://github.com/Prism-Shadow/penguin-harness/pull/503)++[中文版](2026-08-26-markdown-math.zh.md)++Markdown bodies now render mathematical notation with KaTeX. The pipeline is shared, so chat+messages, Trace events, benchmark cases and Workspace file previews all gained it at once.++## Details++- Three delimiter pairs were enabled: `\[…\]` and `$$…$$` render as display math, `\(…\)` as+ inline. A `$$…$$` pair is display wherever it is written, not only when it stands alone on its+ own lines. The TeX bracket forms — the ones models emit most — were taught to the parser as a+ micromark syntax extension, which is what keeps them out of code spans and fenced blocks and lets+ an unclosed `\[` mid-stream stay ordinary text until its closer arrives.+- Single-dollar inline math was left off. `$PATH`, `$HOME` and prices such as `$5 and $10` are left+ exactly as written; `$$…$$` is unaffected.+- A formula KaTeX cannot parse renders as its own source with the parse error in a tooltip, rather+ than failing the message it sits in. Sizing commands were capped at 5em, so a `\rule{9999em}{9999em}`+ arriving from a model is a small square rather than a page-sized one.+- CJK inside `\text{}` renders in the application's own font stack. KaTeX's typefaces carry no CJK+ glyphs and leave the class they tag such runs with undefined, so the change added a rule for it.+- Display math scrolls horizontally inside its own block, as tables and code blocks already do, and+ a long inline formula scrolls inside itself instead of widening the message column.+- A formula in a message that is still streaming shows as its own TeX source and is typeset when+ the message settles. Rendering it per delta meant re-parsing KaTeX's markup and rebuilding a few+ hundred elements per formula around eight times a second, which is the cost the transcript+ memoization and the deferred syntax highlighting already exist to avoid.+- `\[` and `\]` are also CommonMark's escape for a literal bracket, and the collision was resolved+ in favour of math: `See \[1\] and \[2\] for details.` reads as two centred formulas rather than+ two footnote markers. A `\[…\]` broken by a blank line is not matched, and `\[a\\]` — a TeX line+ break butted against the closer — closes at the second backslash.+- A backtick between the delimiters declines the formula, so prose that shows a closing delimiter+ inside a code span keeps both the span and its sentence.+- KaTeX's stylesheet and its woff2 faces are bundled as local assets, so math renders with no+ network. The woff and truetype fallbacks KaTeX also ships are dropped at build time; the web+ bundle grew by about 550KB, of which roughly 250KB is fonts fetched only when a formula appears.+- The remark and rehype plugin lists moved to `packages/web/src/lib/markdown-plugins.ts`, and every+ `ReactMarkdown` call site was pointed at them rather than assembling its own.diff --git a/changelog/unreleased/2026-08-26-markdown-math.zh.md b/changelog/unreleased/2026-08-26-markdown-math.zh.mdnew file mode 100644index 00000000..06af83ab--- /dev/null+++ b/changelog/unreleased/2026-08-26-markdown-math.zh.md@@ -0,0 +1,36 @@+# 所有 Markdown 界面渲染 LaTeX 公式++- **Date:** 2026-08-26+- **Type:** feature+- **Scope:** `web`+- **PR:** [#503](https://github.com/Prism-Shadow/penguin-harness/pull/503)++[English](2026-08-26-markdown-math.md)++Markdown 正文改用 KaTeX 渲染数学公式。渲染管线是共用的,因此对话消息、Trace 事件、Benchmark 用例与+Workspace 文件预览同时具备该能力。++## 细节++- 启用三种分隔符:`\[…\]` 与 `$$…$$` 渲染为独立成块的公式,`\(…\)` 渲染为行内公式。`$$…$$` 无论+ 写在哪里都是成块公式,不限于单独占据整行的写法。模型最常输出的 TeX 方括号形式以 micromark 语法+ 扩展的方式加入解析器,这使其不会侵入行内代码与围栏代码块,也使流式输出中尚未闭合的 `\[` 先按普通+ 文本显示、待结束符到达后再变为公式。+- 保持关闭单个 `$` 的行内公式。`$PATH`、`$HOME` 以及 `$5 和 $10` 这类价格保持原样;`$$…$$` 不受影响。+- KaTeX 无法解析的公式显示为其自身源码,解析错误保留在悬停提示中,不会波及所在的整条消息。尺寸类命令+ 被限制在 5em 以内,模型输出的 `\rule{9999em}{9999em}` 只会得到一个小方块,而不是一整页那么大。+- `\text{}` 中的中文使用应用自身的字体栈渲染。KaTeX 的字体不含 CJK 字形,且未为其标记的中文片段定义+ 样式,本次改动补齐了该样式。+- 成块公式在自身区块内横向滚动,与表格、代码块的既有处理一致;过长的行内公式也在自身范围内滚动,而不+ 会撑宽整列消息。+- 消息仍在流式输出时,其中的公式先显示为 TeX 源码,待消息结束后再排版。逐个增量渲染意味着每秒约八次+ 重新解析 KaTeX 的产物、并为每条公式重建数百个元素,而这正是消息记录的 memo 与延后语法高亮已经在+ 规避的开销。+- `\[` 与 `\]` 同时也是 CommonMark 中方括号的转义写法,本次改动把这一冲突判给公式:+ `See \[1\] and \[2\] for details.` 会被读成两条居中公式,而不是两个脚注标记。被空行截断的 `\[…\]`+ 不匹配,`\[a\\]`(TeX 换行紧贴结束符)在第二个反斜杠处闭合。+- 分隔符之间出现反引号时放弃识别该公式,因此在行内代码里展示结束符的句子,代码片段与句子都完好。+- KaTeX 的样式表与 woff2 字体作为本地资源打包,离线也能渲染公式。KaTeX 同时提供的 woff 与 truetype+ 回退在构建时丢弃;Web 产物体积增加约 550KB,其中约 250KB 是仅在出现公式时才会请求的字体。+- remark 与 rehype 插件列表移至 `packages/web/src/lib/markdown-plugins.ts`,所有 `ReactMarkdown`+ 调用点改为读取该列表,不再各自拼装。diff --git a/packages/web/package.json b/packages/web/package.jsonindex 0a25bd5f..0e5f6309 100644--- a/packages/web/package.json+++ b/packages/web/package.json@@ -19,11 +19,14 @@"@xterm/addon-fit": "^0.10.0","@xterm/addon-web-links": "^0.11.0","@xterm/xterm": "^5.5.0",+ "katex": "^0.16.47","react": "^19.1.0","react-dom": "^19.1.0","react-markdown": "^10.1.0","react-router": "^8.3.0",+ "rehype-katex": "^7.0.1","remark-gfm": "^4.0.0",+ "remark-math": "^6.0.0","shiki": "^4.3.1","zustand": "^5.0.15"},diff --git a/packages/web/src/features/benchmark/benchmark-case-browser.tsx b/packages/web/src/features/benchmark/benchmark-case-browser.tsxindex 4905968a..4bca9894 100644--- a/packages/web/src/features/benchmark/benchmark-case-browser.tsx+++ b/packages/web/src/features/benchmark/benchmark-case-browser.tsx@@ -7,7 +7,7 @@ import type {} from "@prismshadow/penguin-server/api";import ReactMarkdown from "react-markdown";import type { Components } from "react-markdown";-import { REMARK_PLUGINS } from "../../lib/remark-autolink-boundary";+import { REHYPE_PLUGINS, REMARK_PLUGINS } from "../../lib/markdown-plugins";import * as api from "../../api/endpoints";import { apiErrorText } from "../../lib/api-error";import { joinWorkspacePath } from "../../lib/file-path";@@ -455,7 +455,11 @@ export function BenchmarkCaseBrowser({ projectId, agentId, benchmarkId, caseSumm) : preview.kind === "md" ? (<><div className="md-body text-sm text-gray-800 dark:text-gray-100">- <ReactMarkdown remarkPlugins={REMARK_PLUGINS} components={markdownComponents}>+ <ReactMarkdown+ remarkPlugins={REMARK_PLUGINS}+ rehypePlugins={REHYPE_PLUGINS}+ components={markdownComponents}+ >{preview.content ?? ""}</ReactMarkdown></div>diff --git a/packages/web/src/features/chat/md.tsx b/packages/web/src/features/chat/md.tsxindex 67361816..38e3920c 100644--- a/packages/web/src/features/chat/md.tsx+++ b/packages/web/src/features/chat/md.tsx@@ -11,12 +11,16 @@* re-tokenizing a growing block every frame is O(n²) main-thread cost — and the settle* re-render (new string instance, streaming=false) highlights each block exactly once.* Inline code keeps the default rendering (`.md-body code` styling).+ *+ * KaTeX is held back the same way, for the same reason: `streaming` swaps the rehype stage+ * out, so a formula shows its own TeX source until the message settles and is typeset once+ * (see NO_REHYPE_PLUGINS in lib/markdown-plugins.ts for the measurements).*/import { isValidElement, memo } from "react";import type { ComponentPropsWithoutRef, ReactNode } from "react";import ReactMarkdown from "react-markdown";import type { Components, ExtraProps } from "react-markdown";-import { REMARK_PLUGINS } from "../../lib/remark-autolink-boundary";+import { NO_REHYPE_PLUGINS, REHYPE_PLUGINS, REMARK_PLUGINS } from "../../lib/markdown-plugins";import { CodeBlock } from "./code-block";/** Flatten a react-markdown code element's children to plain text (string or string array in practice). */@@ -26,11 +30,21 @@ function codeText(children: unknown): string {return "";}-/** Fenced-block adapter: unwraps the <pre><code class="language-x"> pair react-markdown emits into CodeBlock. */+/**+ * Fenced-block adapter: unwraps the <pre><code class="language-x"> pair react-markdown emits into+ * CodeBlock.+ *+ * `language-math` is the exception. remark-math models block math as a fence in that language and+ * rehype-katex replaces the whole pair before this adapter is consulted — except while streaming,+ * where the rehype stage is off, and the block would otherwise pick up CodeBlock's chrome and copy+ * button for the few hundred milliseconds before it settles into a formula. A plain <pre> is the+ * source either way, so the settle changes the typesetting and nothing else.+ */function MdPre({ children, streaming }: { children?: ReactNode; streaming: boolean }) {if (isValidElement(children)) {const props = children.props as { className?: string; children?: unknown };const language = /language-([\w+-]+)/.exec(props.className ?? "")?.[1] ?? "";+ if (language === "math") return <pre>{children}</pre>;return (<CodeBlocklanguage={language}@@ -70,8 +84,8 @@ function MdLink({* text selection and resetting each block's Copy-button state — ~8 times a second while a reply* streams, including for blocks that closed long ago. `streaming` is the only thing the adapter* closes over, so one frozen map per value is enough; the single flip between them happens on- * the settle render, which re-parses the message anyway. The `a` adapter closes over nothing,- * so both maps share the one `MdLink` reference.+ * the settle render, which re-parses the message anyway — the same render the rehype stage+ * flips on. The `a` adapter closes over nothing, so both maps share the one `MdLink` reference.*/const STREAMING_COMPONENTS: Components = {pre: (props) => <MdPre streaming>{props.children}</MdPre>,@@ -92,6 +106,7 @@ export const Md = memo(function Md({return (<ReactMarkdownremarkPlugins={REMARK_PLUGINS}+ rehypePlugins={streaming ? NO_REHYPE_PLUGINS : REHYPE_PLUGINS}components={streaming ? STREAMING_COMPONENTS : SETTLED_COMPONENTS}>{text}diff --git a/packages/web/src/features/chat/workspace-browser.tsx b/packages/web/src/features/chat/workspace-browser.tsxindex 72bf1815..0cec48ed 100644--- a/packages/web/src/features/chat/workspace-browser.tsx+++ b/packages/web/src/features/chat/workspace-browser.tsx@@ -15,7 +15,7 @@import { useCallback, useEffect, useRef, useState } from "react";import type { ChangeEvent } from "react";import ReactMarkdown from "react-markdown";-import { REMARK_PLUGINS } from "../../lib/remark-autolink-boundary";+import { REHYPE_PLUGINS, REMARK_PLUGINS } from "../../lib/markdown-plugins";import type { SessionInfo, WorkspaceFilesResponse } from "@prismshadow/penguin-server/api";import * as api from "../../api/endpoints";import { ApiError } from "../../api/client";@@ -615,6 +615,7 @@ export function WorkspaceBrowser({<div className="md-body text-base leading-relaxed text-gray-800 dark:text-gray-100"><ReactMarkdownremarkPlugins={REMARK_PLUGINS}+ rehypePlugins={REHYPE_PLUGINS}components={{// Relative images are resolved against the md file's directory into the file API (otherwise resolving against the app's origin would always 404).// `v` is the read nonce, not a cache-buster for its own sake: adiff --git a/packages/web/src/features/traces/trace-event-row.tsx b/packages/web/src/features/traces/trace-event-row.tsxindex 1180066b..528d3bf2 100644--- a/packages/web/src/features/traces/trace-event-row.tsx+++ b/packages/web/src/features/traces/trace-event-row.tsx@@ -13,7 +13,7 @@*/import { Fragment, useState } from "react";import ReactMarkdown from "react-markdown";-import { REMARK_PLUGINS } from "../../lib/remark-autolink-boundary";+import { REHYPE_PLUGINS, REMARK_PLUGINS } from "../../lib/markdown-plugins";import { S } from "../../lib/strings";import type { OmniMessage } from "@prismshadow/penguin-core/omnimessage";import { formatTime, humanizeTokens } from "../../lib/format";@@ -218,7 +218,9 @@ function SessionMetaBody({ p }: { p: Record<string, unknown> }) {<details><summary className={summaryClass}>{S.traces.systemPrompt}</summary><div className="md-body mt-1.5 max-h-96 overflow-auto rounded bg-gray-100 px-2.5 py-2 text-sm leading-relaxed text-gray-700 dark:bg-gray-800/70 dark:text-gray-300">- <ReactMarkdown remarkPlugins={REMARK_PLUGINS}>{prompt}</ReactMarkdown>+ <ReactMarkdown remarkPlugins={REMARK_PLUGINS} rehypePlugins={REHYPE_PLUGINS}>+ {prompt}+ </ReactMarkdown></div></details>)}@@ -321,7 +323,9 @@ function EventBody({ msg }: { msg: OmniMessage }) {if (!md.trim()) return <p className="text-xs text-gray-400">—</p>;return (<div className="md-body text-sm leading-relaxed text-gray-700 dark:text-gray-300">- <ReactMarkdown remarkPlugins={REMARK_PLUGINS}>{md}</ReactMarkdown>+ <ReactMarkdown remarkPlugins={REMARK_PLUGINS} rehypePlugins={REHYPE_PLUGINS}>+ {md}+ </ReactMarkdown></div>);}diff --git a/packages/web/src/lib/markdown-plugins.ts b/packages/web/src/lib/markdown-plugins.tsnew file mode 100644index 00000000..7cd6cb63--- /dev/null+++ b/packages/web/src/lib/markdown-plugins.ts@@ -0,0 +1,115 @@+/**+ * The unified pipeline every Markdown surface renders through.+ *+ * Shared so the five renderers cannot drift: a bare URL has to end at the same place, and a formula+ * has to render the same way, in a chat message, a Trace event, a benchmark case and a workspace+ * file preview. The lists are module constants rather than array literals at the call sites because+ * a fresh array is a new prop identity, and react-markdown rebuilds its whole processor when the+ * plugin list changes — per commit, on a path that already had to be memoized to stop an O(n²)+ * re-parse of the transcript while a reply streams.+ *+ * ## Math+ *+ * Three delimiter pairs are accepted, which is what it takes to cover what models actually emit:+ * `$$…$$` and `\[…\]` render as display math, `\(…\)` as inline. `remark-math` brings the dollar+ * form, `remarkMathBrackets` the TeX bracket forms (see its module comment for why those cannot be+ * a text-node rewrite), and `remarkMathDollars` makes a `$$…$$` pair display wherever it is written+ * rather than only when it stands alone on its own lines.+ *+ * **Single-dollar inline math is off.** It is the one delimiter whose cost is paid by text that was+ * never meant to be math, and in this product that text is everywhere: `$PATH`, `$HOME`, prices.+ * `remark-math` rejects a span that starts or ends with whitespace, which saves a lone `$5`, but+ * two dollars in a sentence are enough and agent transcripts are full of pairs. Measured against+ * this repo's own idiom, with single-dollar math enabled:+ *+ * Set $PATH and $HOME before running. -> Set <math>PATH and </math>HOME before running.+ * It costs $5 and $10 in total. -> It costs <math>5 and </math>10 in total.+ * The range is $5-$10 per seat. -> The range is <math>5-</math>10 per seat.+ * echo $PATH; echo $HOME -> echo <math>PATH; echo </math>HOME+ * Prices: $1,200 and $3,400. -> Prices: <math>1,200 and </math>3,400.+ *+ * Each of those loses its dollar signs, its spacing and its meaning. The failure in the other+ * direction is that someone writing `$x^2$` sees `$x^2$` — the source, legible, and re-typable as+ * `\(x^2\)`. Corrupting prose that was already correct is the worse trade, so the dollar pair is+ * reserved for `$$…$$`, which no shell variable or price produces by accident.+ */+import remarkGfm from "remark-gfm";+import remarkMath from "remark-math";+import rehypeKatex from "rehype-katex";+import type { Options } from "react-markdown";+import { remarkAutolinkBoundary } from "./remark-autolink-boundary";+import { remarkMathBrackets } from "./remark-math-brackets";+import { remarkMathDollars } from "./remark-math-dollars";++/** react-markdown's own plugin-list type, taken from its props so `unified` need not be a dep. */+type PluginList = NonNullable<Options["remarkPlugins"]>;++/**+ * KaTeX settings for untrusted input, because that is what this renders: model output, and files+ * out of a Workspace.+ *+ * - `strict: "ignore"` — KaTeX's default warns to the console for every LaTeX-incompatible but+ * renderable construct, and sloppy `\text` around CJK trips it per character. The warnings are+ * not actionable by anyone reading a chat transcript, and the render is identical either way.+ * - `errorColor: "currentColor"` — the default `#cc0000` is an inline style, so it cannot adapt to+ * the dark theme, where it lands under 4:1 against a black background. Failed expressions instead+ * render as their own source in the body colour; `.katex-error` in styles.css marks them with a+ * dotted underline and keeps KaTeX's parse error in the `title` tooltip.+ * - `trust: false` (KaTeX's default, restated because it is a boundary) — leaves `\href`, `\url`+ * and `\includegraphics` inert, so a formula cannot smuggle in a link or an image request.+ * - `maxSize` — caps the em value any sizing command may claim. KaTeX defaults to Infinity, so+ * `\rule{9999em}{9999em}` is a black square the size of the viewport many times over; 5em is+ * 80px at a 16px root, which a message body absorbs the way it absorbs an emoji. Every sizing+ * command a real formula uses — a `\rule` for a fraction bar, a `\raisebox`, an array row gap,+ * `\hspace{1cm}` — is well under it.+ *+ * `throwOnError` is *not* here, and cannot be: `rehype-katex` omits it from its options type+ * because it owns that behaviour. It renders once strictly, and on any error re-renders with+ * `throwOnError: false`, falling back to a `.katex-error` span holding the original source. That is+ * exactly the required degradation — a malformed expression shows its own text instead of taking+ * the message down with it — so there is nothing to override.+ */+const KATEX_OPTIONS = {+ strict: "ignore",+ errorColor: "currentColor",+ trust: false,+ maxSize: 5,+} as const;++/** The remark (Markdown -> mdast) stage. */+export const REMARK_PLUGINS: PluginList = [+ remarkGfm,+ remarkAutolinkBoundary,+ [remarkMath, { singleDollarTextMath: false }],+ remarkMathBrackets,+ remarkMathDollars,+];++/**+ * The rehype (mdast -> hast) stage. `rehype-katex` turns every element the remark stage classed+ * `math-inline` / `math-display` into KaTeX's own markup, replacing it outright — which is also why+ * a `$$…$$` block never reaches the chat renderer's `<pre>` override and never becomes a CodeBlock.+ */+export const REHYPE_PLUGINS: NonNullable<Options["rehypePlugins"]> = [[rehypeKatex, KATEX_OPTIONS]];++/**+ * The rehype stage for a message that is still streaming: nothing, so the remark stage's own+ * `math-*` elements reach the DOM carrying the TeX source, and the formula is typeset once on the+ * settle render.+ *+ * KaTeX itself is cheap — ~0.3ms for a typical formula. What is not cheap is the rest of the stage+ * around it: `rehype-katex` re-parses KaTeX's ~2.5KB of markup per formula back into hast, and+ * React then builds several hundred elements from it. Measured through this pipeline with+ * `renderToStaticMarkup` on a 3.6KB reply carrying 60 formulas: 16ms for gfm alone, 13ms with the+ * math parsed but not rendered, 284ms for the full stage. Streamed in 40 deltas — chat bodies+ * re-parse on every delta, ~8 times a second — that is 196ms of total work without the rehype+ * stage and 2352ms with it, and it grows with the square of the reply's length. One oversized+ * formula shows the same shape on its own: a 16KB formula is 885ms per render, and a 20KB+ * paragraph accidentally wrapped by an unmatched `\[ … \]` is 856ms.+ *+ * Memoizing the produced hast per formula was measured too and is not enough: it cannot help the+ * formula that is still growing, which is the one being re-rendered, and it left 1853ms of the+ * 2352ms in place. This is the same trade as `highlight={!streaming}` for code blocks — the settle+ * render re-parses the message anyway, so it is where the expensive stage belongs.+ */+export const NO_REHYPE_PLUGINS: NonNullable<Options["rehypePlugins"]> = [];diff --git a/packages/web/src/lib/remark-autolink-boundary.ts b/packages/web/src/lib/remark-autolink-boundary.tsindex 04f8c149..4a272091 100644--- a/packages/web/src/lib/remark-autolink-boundary.ts+++ b/packages/web/src/lib/remark-autolink-boundary.ts@@ -16,8 +16,6 @@* the RFC and browsers only accept it by encoding it for you; the same link pasted in its encoded* form is untouched. Explicit `[text](url)` links are never touched at all.*/-import remarkGfm from "remark-gfm";-/*** The mdast shapes this touches, declared structurally rather than pulling `@types/mdast` in as a* dependency for three of them. Anything else on a node passes through untouched.@@ -79,10 +77,3 @@ function walk(parent: Parent): void {export function remarkAutolinkBoundary() {return (tree: Parent): void => walk(tree);}--/**- * The remark plugin list every Markdown surface uses. Shared so the five renderers cannot drift:- * a bare URL has to end at the same place in a chat message, a Trace event, a benchmark case and- * a workspace file preview.- */-export const REMARK_PLUGINS = [remarkGfm, remarkAutolinkBoundary];diff --git a/packages/web/src/lib/remark-math-brackets.ts b/packages/web/src/lib/remark-math-brackets.tsnew file mode 100644index 00000000..f482c84d--- /dev/null+++ b/packages/web/src/lib/remark-math-brackets.ts@@ -0,0 +1,328 @@+/**+ * LaTeX's `\(…\)` and `\[…\]` delimiters, taught to remark as first-class math.+ *+ * `remark-math` understands `$…$` and `$$…$$` only, but models emit the TeX bracket forms+ * constantly — the report that prompted this feature was a pasted reply whose entire formula was a+ * `\[…\]` chain of `\text{}` runs joined by `\rightarrow`. Without this, such replies render as+ * prose littered with backslash commands.+ *+ * **Why this is a syntax extension and not a text-node rewrite.** By CommonMark, a backslash before+ * any ASCII punctuation is a character escape, so `\[x\]` has *already* become the literal text+ * `[x]` by the time an mdast tree exists — the backslashes are gone, and nothing then distinguishes+ * it from a bracket someone typed. A plugin walking `text` nodes would have to guess, and guessing+ * means eating real brackets. Rewriting the source string before parsing is the other tempting+ * shortcut, and it is worse: to avoid corrupting code it would have to re-derive which spans are+ * fences, indented blocks and code spans of arbitrary backtick runs — reimplementing CommonMark,+ * badly, on the streaming path.+ *+ * Registering a micromark construct makes both problems disappear by construction. The tokenizer is+ * only consulted where inline content is read, so a `\[` inside a fenced block or a code span is+ * never offered to it — not "handled correctly", never seen. That covers the opener only: once+ * inside a formula the construct reads raw characters, so it has to decline a backtick itself+ * (see `declineAtBacktick`). And because `micromark-util-combine-extensions` splices extension+ * constructs *before* the built-in ones at the same character, this runs ahead of+ * `characterEscape` and gets first refusal on every `\`;+ * when it declines — the next character is not `(`/`[`, or no closer arrives — micromark falls back+ * to the escape exactly as before, so a half-arrived `\[` mid-stream stays ordinary text and+ * settles into math once its closer lands.+ *+ * **What it produces.** Both forms become an mdast `inlineMath` node carrying explicit hast+ * instructions: a `<span>` classed `math math-inline` or `math math-display`, which is the contract+ * `rehype-katex` reads to pick KaTeX's display mode. Display math is deliberately a *span* rather+ * than the `<pre><code>` pair `remark-math` builds for `$$`: `\[…\]` is phrasing-level syntax that+ * may legally appear mid-sentence, and a `<div>` or `<pre>` inside the surrounding `<p>` would be+ * invalid nesting. KaTeX's own `.katex-display` wrapper supplies the centring and block layout, so+ * the span still reads as display math wherever it lands.+ *+ * **Known limits.** A `\[…\]` broken by a blank line spans two paragraphs and is not matched (a+ * blank line inside display math is not valid input anyway); `\[a\\]` — a TeX line break butted+ * straight against the closer, ambiguous in TeX too — closes at the second backslash; a backtick+ * between the delimiters declines the formula outright (see `declineAtBacktick`); and `\[`/`\]` is+ * also CommonMark's escape for a literal bracket, so `See \[1\] and \[2\]` is read as two formulas+ * rather than two footnote markers. The last is a genuine collision between two syntaxes that+ * cannot both win, and it is resolved in favour of the one models actually emit.+ */++/**+ * The micromark and mdast-util shapes this touches, declared structurally rather than adding+ * `micromark-util-types` and `mdast-util-from-markdown` as dependencies for a handful of+ * interfaces — the same trade `remark-autolink-boundary.ts` makes for its mdast nodes.+ */+type Code = number | null;+interface Token {+ type: string;+}+interface Effects {+ enter(type: string): Token;+ exit(type: string): Token;+ consume(code: Code): void;+}+type State = (code: Code) => State | undefined;+/**+ * The tokenize context, plus the one field this construct parks on it. micromark builds a fresh+ * context per run of inline content, so the memo below is scoped to a single paragraph.+ */+interface TokenizeContext {+ _mathBracketUnclosed?: Record<number, boolean>;+}+interface HastText {+ type: "text";+ value: string;+}+interface MathNode {+ type: "inlineMath";+ value: string;+ data: { hName: string; hProperties: { className: string[] }; hChildren: HastText[] };+}+/** The subset of mdast-util-from-markdown's compile context these handlers use. */+interface CompileContext {+ stack: MathNode[];+ enter(node: MathNode, token: Token): void;+ exit(token: Token): void;+ sliceSerialize(token: Token): string;+}+/** The `this.data()` bag unified plugins share to register parser extensions. */+interface ProcessorData {+ micromarkExtensions?: unknown[];+ fromMarkdownExtensions?: unknown[];+}++const BACKSLASH = 92;+const BACKTICK = 96;+const PAREN_OPEN = 40;+const PAREN_CLOSE = 41;+const BRACKET_OPEN = 91;+const BRACKET_CLOSE = 93;++/**+ * micromark feeds negative codes for the characters that are not really characters: -5 carriage+ * return, -4 line feed, -3 the pair, -2 tab, -1 virtual space. Its own `markdownLineEnding` is this+ * comparison, inlined rather than pulling in `micromark-util-character` for one predicate.+ */+function isLineEnding(code: Code): boolean {+ return code !== null && code < -2;+}++/** The wrapping token; its serialized slice is the whole `\[…\]`, delimiters included. */+const MATH = "mathBracket";+/** A two-character opening or closing delimiter. */+const MARKER = "mathBracketMarker";+/** A run of formula text with no line break in it. */+const VALUE = "mathBracketValue";+/**+ * A line break inside a formula, as its own token — not decoration.+ *+ * `micromark-util-subtokenize` stitches an inline token stream back onto the per-line chunks a+ * paragraph was split into by counting *void tokens that span a line break*, one per chunk+ * boundary. A single value token swallowing two newlines therefore reports one boundary where the+ * paragraph has two, and the stitch walks off the end of its buffer (`RangeError: Cannot access+ * index …`) — a crash, not a misrender. Every built-in inline construct that can span lines emits+ * these for the same reason.+ */+const LINE_ENDING = "lineEnding";++/**+ * Tokenizes `\(…\)` and `\[…\]`, entered on a `\` in inline content.+ *+ * The closing delimiter cannot be recognized without consuming its backslash first, and micromark+ * has no lookahead — so that backslash is consumed into a freshly opened marker token, and if the+ * character after it turns out not to be the closer (`\rightarrow`, `\\`, `\{`, …) the token is+ * re-typed as formula text and reading continues. Re-typing an open token in place is micromark's+ * own idiom for this; `micromark-extension-math` does the same when a `$` run proves too short to+ * close.+ */+function tokenizeMathBracket(+ this: TokenizeContext,+ effects: Effects,+ ok: State,+ nok: State,+): State {+ const self = this;+ /** The opening character, once known; keys the give-up memo below. */+ let opener = 0;+ /** The character that, preceded by a backslash, ends this formula. */+ let closer = 0;+ /** A marker token opened on a backslash that may or may not turn out to close the formula. */+ let pending: Token | undefined;++ return start;++ /**+ * Abandons the attempt, recording that this delimiter has no closer anywhere in the rest of the+ * paragraph.+ *+ * Reaching here means the scan ran to the end of the content without meeting the closer, so no+ * closer exists at or after this opener — and therefore none exists after any *later* opener of+ * the same kind either. Without that memo a paragraph carrying many unterminated openers costs+ * one full scan each: 1000 stray `\[` in an 18k-character paragraph measured at ~520ms of parse,+ * and chat bodies are re-parsed as they stream.+ */+ function giveUp(code: Code): State | undefined {+ (self._mathBracketUnclosed ??= {})[opener] = true;+ return nok(code);+ }++ function start(code: Code): State | undefined {+ effects.enter(MATH);+ effects.enter(MARKER);+ effects.consume(code); // The `\`, already known from the construct's character.+ return afterOpenBackslash;+ }++ function afterOpenBackslash(code: Code): State | undefined {+ if (code === PAREN_OPEN) closer = PAREN_CLOSE;+ else if (code === BRACKET_OPEN) closer = BRACKET_CLOSE;+ // Any other escape — `\*`, `\\`, a hard break — is not ours; micromark retries the built-ins.+ else return nok(code);+ opener = code;+ if (self._mathBracketUnclosed?.[opener]) return nok(code);+ effects.consume(code);+ effects.exit(MARKER);+ return valueStart;+ }++ /**+ * At a position where formula text may begin, with no value token open: just after the opening+ * delimiter, and again after every line break.+ *+ * Nothing is entered until there is a character to put in it. micromark's development build+ * asserts that no token is ever closed empty, so opening a value token eagerly and finding a+ * backslash or a newline in the very next position would abort the parse.+ */+ function valueStart(code: Code): State | undefined {+ if (code === null) return giveUp(code);+ if (code === BACKTICK) return declineAtBacktick(code);+ if (code === BACKSLASH) return backslash(code);+ if (isLineEnding(code)) return lineEnding(code);+ effects.enter(VALUE);+ effects.consume(code);+ return value;+ }++ /** Inside an open value token, which therefore always holds at least one character. */+ function value(code: Code): State | undefined {+ // An unclosed formula at end of input: the value token is left open for `nok` to discard+ // along with the rest of this attempt's events.+ if (code === null) return giveUp(code);+ if (code === BACKTICK) return declineAtBacktick(code);+ if (code === BACKSLASH) {+ effects.exit(VALUE);+ return backslash(code);+ }+ if (isLineEnding(code)) {+ effects.exit(VALUE);+ return lineEnding(code);+ }+ effects.consume(code);+ return value;+ }++ /**+ * Declines the attempt at a backtick, because from here the scan cannot see a code span.+ *+ * The construct is only *entered* where inline content is read, so an opener inside a code span+ * is never offered to it — but once inside a formula it consumes raw characters, and a code+ * span's boundaries are just more of them. Prose explaining the delimiters is the shape that+ * breaks: a sentence that opens with a bare `\(` and then shows its closer inside a code span+ * finds that closer, swallows the opening backtick into the formula and leaves the closing one+ * stranded in the text. Declining hands the backslash back to `characterEscape` and the backtick+ * to `codeText`, which is the reading a writer meant.+ *+ * Whether the run has a partner later — the CommonMark rule for a code span — is not checked:+ * knowing would mean scanning ahead for a matching run, and preferring prose to math on the rare+ * unpaired backtick is the safe direction. The cost is that a backtick *inside* a formula (TeX's+ * open-quote pair, in a `\text{}`) declines it, which no reported input has contained. `nok`+ * rather than `giveUp`, because nothing here proves the closer is missing from the rest of the+ * paragraph — only that this attempt must not cross the backtick to reach it.+ */+ function declineAtBacktick(code: Code): State | undefined {+ return nok(code);+ }++ function lineEnding(code: Code): State | undefined {+ effects.enter(LINE_ENDING);+ effects.consume(code);+ effects.exit(LINE_ENDING);+ return valueStart;+ }++ /** Consumes a backslash into a marker token, on the chance that it opens the closing delimiter. */+ function backslash(code: Code): State | undefined {+ pending = effects.enter(MARKER);+ effects.consume(code);+ return afterValueBackslash;+ }++ function afterValueBackslash(code: Code): State | undefined {+ if (code === closer) {+ effects.consume(code);+ return afterClose;+ }+ // Not the closer after all: that backslash was formula text, so the token holding it becomes+ // one — non-empty already, which is what lets `value` take over from here.+ if (pending) pending.type = VALUE;+ return value(code);+ }++ function afterClose(code: Code): State | undefined {+ effects.exit(MARKER);+ effects.exit(MATH);+ return ok(code);+ }+}++/**+ * The micromark syntax extension: one construct on `\` in inline content. There is deliberately no+ * `flow` entry — display math is handled at the same inline level (see the module comment), which+ * is what lets `\[…\]` behave identically whether it stands alone or sits inside a sentence.+ */+const syntax = {+ text: { [BACKSLASH]: { tokenize: tokenizeMathBracket, name: MATH } },+};++/**+ * The mdast extension: the node is built on exit, where the whole `\[…\]` can be sliced in one go.+ * Which delimiter opened it is read back from that slice rather than threaded through the+ * tokenizer, so the two forms need no separate token types.+ */+const fromMarkdown = {+ enter: {+ [MATH](this: CompileContext, token: Token) {+ this.enter(+ {+ type: "inlineMath",+ value: "",+ // Filled in on exit; `mdast-util-to-hast` reads these to build the element.+ data: { hName: "span", hProperties: { className: [] }, hChildren: [] },+ },+ token,+ );+ },+ },+ exit: {+ [MATH](this: CompileContext, token: Token) {+ const node = this.stack[this.stack.length - 1]!; // Read before exit pops it.+ this.exit(token);+ const raw = this.sliceSerialize(token);+ // Both delimiters are exactly two characters, so the formula is everything between them.+ const value = raw.slice(2, -2);+ const display = raw.charCodeAt(1) === BRACKET_OPEN;+ node.value = value;+ node.data.hProperties.className = ["math", display ? "math-display" : "math-inline"];+ node.data.hChildren = [{ type: "text", value }];+ },+ },+};++/**+ * remark plugin: registers the syntax and mdast extensions above.+ *+ * Both lists are the ones `remark-parse` hands to micromark and `mdast-util-from-markdown`, which+ * is also how `remark-math` installs itself — so the two coexist without either knowing about the+ * other, each owning its own delimiter character.+ */+export function remarkMathBrackets(this: { data(): ProcessorData }): undefined {+ const data = this.data();+ (data.micromarkExtensions ??= []).push(syntax);+ (data.fromMarkdownExtensions ??= []).push(fromMarkdown);+}diff --git a/packages/web/src/lib/remark-math-dollars.ts b/packages/web/src/lib/remark-math-dollars.tsnew file mode 100644index 00000000..e2dae537--- /dev/null+++ b/packages/web/src/lib/remark-math-dollars.ts@@ -0,0 +1,62 @@+/**+ * `$$…$$` is display math wherever it is written, not only when it stands alone on its own lines.+ *+ * `remark-math` has two constructs for the dollar forms. The flow one — `$$` alone on a line, the+ * formula, `$$` alone on a line — is display. Everything else is its *text* construct, which is+ * inline whatever the run length: `$$E=mc^2$$` on one line, and `text $$E=mc^2$$ text`, both come+ * out as inline math. That is a run-length rule, not a TeX one. In TeX `$$` has meant display since+ * plain TeX, `$` alone means inline, and single-dollar math is off here — so a `$$` pair in this+ * app can only have been meant as display, and models emit it on one line constantly.+ *+ * Leaving it inline had a layout cost as well as a typographic one. KaTeX sets+ * `.katex .base { white-space: nowrap }`, so a long single-line `$$…$$` is one unbreakable run.+ * `.md-body .katex-display` scrolls inside its own block; an inline run has to be caught by the+ * separate guard in styles.css, and even caught it is still typeset cramped — inline mode uses+ * small integrals, small sums and squeezed fractions for a formula the author centred.+ *+ * So every text-math node opened by a dollar run is re-classed to display, which is also what makes+ * `$$…$$` and `\[…\]` behave identically (see remark-math-brackets.ts). The delimiter is read back+ * from the source rather than from the class list, because `remark-math` and `remarkMathBrackets`+ * both produce `inlineMath` nodes and only the source separates them.+ */++/**+ * The mdast shapes this touches, declared structurally rather than pulling `@types/mdast` and+ * `mdast-util-math` in as dependencies for two of them — the same trade the sibling plugins make.+ */+interface Node {+ type: string;+ position?: { start?: { offset?: number } };+ data?: { hProperties?: { className?: unknown } };+ children?: Node[];+}++const DOLLAR = "$";+const INLINE_CLASS = "math-inline";+const DISPLAY_CLASS = "math-display";++/** Re-classes one node if it is a dollar-delimited text-math node. */+function promote(node: Node, source: string): void {+ if (node.type !== "inlineMath") return;+ const offset = node.position?.start?.offset;+ // `\(…\)` and `\[…\]` are `inlineMath` too, and already carry the class they want.+ if (offset === undefined || source[offset] !== DOLLAR) return;+ const className = node.data?.hProperties?.className;+ if (!Array.isArray(className)) return;+ const index = className.indexOf(INLINE_CLASS);+ // `rehype-katex` picks KaTeX's display mode off this class, and drops the element either way.+ if (index !== -1) className[index] = DISPLAY_CLASS;+}++/** Walks every parent, so a formula inside a table cell, a heading or a list item is covered too. */+function walk(node: Node, source: string): void {+ for (const child of node.children ?? []) {+ promote(child, source);+ walk(child, source);+ }+}++/** Runs after remark-math, on the tree it produced. */+export function remarkMathDollars() {+ return (tree: Node, file: { value?: unknown }): void => walk(tree, String(file.value ?? ""));+}diff --git a/packages/web/src/main.tsx b/packages/web/src/main.tsxindex 2bc943a1..76edf001 100644--- a/packages/web/src/main.tsx+++ b/packages/web/src/main.tsx@@ -5,6 +5,11 @@import { StrictMode } from "react";import { createRoot } from "react-dom/client";import { App } from "./app";+// KaTeX's stylesheet and its woff2 faces, resolved out of node_modules so Vite emits them as local+// assets: the desktop app has to render math with no network, and a CDN <link> would leave every+// formula as unstyled markup offline. Imported before styles.css so the app's own `.katex` rules+// (CJK fallback, error state, wide-formula scrolling) come later in the cascade and win.+import "katex/dist/katex.min.css";import "./styles.css";const container = document.getElementById("root");diff --git a/packages/web/src/styles.css b/packages/web/src/styles.cssindex 9e88e103..f6ccd65e 100644--- a/packages/web/src/styles.css+++ b/packages/web/src/styles.css@@ -31,6 +31,11 @@@layer base {:root {color-scheme: light;+ /* The body font stack, named because KaTeX borrows it: math has to fall back to the same CJK+ faces as the prose around it (see .katex .cjk_fallback below), and two copies would drift. */+ --font-app-sans:+ ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "PingFang SC", "Microsoft YaHei",+ sans-serif;/* Theme color (accent): used for primary buttons, focus rings, etc. Defaults to gray/white (neutral,switches with light/dark); selecting a specific color via data-accent overrides it (consistent acrosslight/dark, white text). */@@ -101,15 +106,7 @@}body {@apply bg-white text-gray-900 antialiased dark:bg-gray-950 dark:text-gray-100;- font-family:- ui-sans-serif,- system-ui,- -apple-system,- "Segoe UI",- Roboto,- "PingFang SC",- "Microsoft YaHei",- sans-serif;+ font-family: var(--font-app-sans);}code,pre,@@ -556,3 +553,47 @@ html.dark .shiki span {.md-body :is(th, td) {@apply border border-gray-200 px-2 py-1 text-sm dark:border-gray-800;}++/* ---------- KaTeX (math rendering; see lib/markdown-plugins.ts) ---------- */++/* KaTeX's own fonts carry no CJK glyphs, and it tags every CJK run `cjk_fallback` while leaving+ that class undefined in its stylesheet — so a CJK `\text{}` inherits `.katex { font: …+ KaTeX_Main, "Times New Roman", serif }` and lands on whatever the browser picks last. Pointing+ the class at the app's own stack makes CJK inside a formula match the sentence it sits in, on+ every platform, and leaves Latin math on KaTeX's metrics-tuned faces where it belongs. */+.katex .cjk_fallback {+ font-family: var(--font-app-sans);+}++/* A formula KaTeX could not parse (rehype-katex falls back to this rather than throwing): its own+ source, in the body colour, marked as suspect without shouting. The parse error rides along in+ the element's title attribute, which is what `cursor: help` advertises. */+.katex-error {+ text-decoration: underline dotted;+ text-underline-offset: 3px;+ cursor: help;+ @apply decoration-gray-400 dark:decoration-gray-600;+}++/* Display math is `white-space: nowrap` by construction, so a wide matrix or a long derivation+ would otherwise push the whole message body sideways. Same treatment as .md-body table and pre:+ scroll inside the block. Overflow on one axis forces the other to scroll too, so the padding is+ what keeps tall fractions and descenders from being clipped. */+.md-body .katex-display {+ overflow-x: auto;+ overflow-y: hidden;+ padding: 0.25rem 0;+}++/* The same guard for inline math, which is nowrap too and sits in the text flow where nothing+ clips it. `\(…\)` is meant for short spans, but nothing stops a model putting a whole derivation+ in one, and an inline run that overflows takes the message column and the page with it.+ A scroll container has to be inline-block to exist at all; `vertical-align: middle` is what+ keeps it on the line, because an inline-block whose overflow is not `visible` aligns its bottom+ margin edge to the baseline and would otherwise hang a fraction's descender above the text. */+.md-body :not(.katex-display) > .katex {+ display: inline-block;+ max-width: 100%;+ overflow-x: auto;+ vertical-align: middle;+}diff --git a/packages/web/test/markdown-math.test.ts b/packages/web/test/markdown-math.test.tsnew file mode 100644index 00000000..8af22725--- /dev/null+++ b/packages/web/test/markdown-math.test.ts@@ -0,0 +1,387 @@+/**+ * Math rendering across the shared Markdown pipeline (lib/markdown-plugins.ts), via+ * react-dom/server static markup — KaTeX renders synchronously, so the finished formula is in the+ * first pass with no DOM and no effects.+ *+ * What is pinned here is the set of decisions that are invisible once they work and silently wrong+ * when they break: which delimiters count, which look like delimiters but must not, what a+ * malformed formula does to the message around it, and that all five renderers still share one+ * plugin list.+ */+import { describe, expect, it } from "vitest";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import ReactMarkdown from "react-markdown";+import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+import { REHYPE_PLUGINS, REMARK_PLUGINS } from "../src/lib/markdown-plugins";+import { Md } from "../src/features/chat/md";+import { dropNonWoff2FontSources } from "../vite.config.js";++const render = (markdown: string) =>+ renderToStaticMarkup(+ createElement(+ ReactMarkdown,+ { remarkPlugins: REMARK_PLUGINS, rehypePlugins: REHYPE_PLUGINS },+ markdown,+ ),+ );++/** KaTeX rendered something here (as opposed to leaving the source as prose). */+const isMath = (html: string) => html.includes('class="katex');+/** KaTeX rendered it in display mode — its own block wrapper, not an inline run. */+const isDisplay = (html: string) => html.includes('class="katex-display"');+/**+ * The reader-visible text, tags stripped.+ *+ * KaTeX emits each formula twice: a visually hidden MathML tree (for screen readers, and carrying+ * the original TeX in an `<annotation>`) alongside the styled HTML. Dropping the `<math>` element+ * first is what makes this the text a reader actually sees rather than everything twice over.+ */+const text = (html: string) => html.replace(/<math\b[\s\S]*?<\/math>/g, "").replace(/<[^>]*>/g, "");++describe("delimiters that are math", () => {+ it("renders the reported shape: a display formula in \\[…\\] with CJK in \\text{}", () => {+ const html = render(+ String.raw`\[\text{采集} \rightarrow \text{解码} \rightarrow \text{干预}\]`,+ );+ expect(isDisplay(html)).toBe(true);+ // The source is gone from view: no stray backslash commands left in the prose.+ expect(text(html)).not.toContain(String.raw`\rightarrow`);+ expect(text(html)).toBe("采集→解码→干预");+ });++ it("accepts all three delimiter pairs", () => {+ for (const source of [+ String.raw`\(E=mc^2\)`,+ String.raw`\[E=mc^2\]`,+ "$$E=mc^2$$",+ // Fenced $$ on its own lines, the block form remark-math documents.+ "$$\nE=mc^2\n$$",+ ]) {+ expect(isMath(render(source)), source).toBe(true);+ }+ });++ it("distinguishes display from inline", () => {+ expect(isDisplay(render(String.raw`\[x\]`))).toBe(true);+ expect(isDisplay(render("$$\nx\n$$"))).toBe(true);+ expect(isDisplay(render(String.raw`\(x\)`))).toBe(false);+ expect(isMath(render(String.raw`\(x\)`))).toBe(true);+ });++ it("makes a $$…$$ pair display wherever it is written, not only on its own lines", () => {+ // remark-math decides by run length, which leaves a one-line `$$…$$` inline: nowrap, typeset+ // cramped, and behaving unlike `\[…\]` for content nobody writes meaning inline. A `$$` pair+ // has been display since plain TeX, and single-dollar math is off, so nothing else fits.+ for (const source of ["$$E=mc^2$$", "text $$E=mc^2$$ text", "# heading $$x^2$$"]) {+ expect(isDisplay(render(source)), source).toBe(true);+ }+ });++ it("clamps a sizing command to a size the message body absorbs", () => {+ // KaTeX defaults maxSize to Infinity, so `\rule{9999em}{9999em}` is a black square many+ // viewports wide and no overflow rule can help: the element's own height is the problem.+ const html = render(String.raw`\[\rule{9999em}{9999em}\]`);+ const sizes = [...html.matchAll(/(?:width|height)[:="]+([\d.]+)em/g)].map((m) => Number(m[1]));+ expect(sizes.length).toBeGreaterThan(0);+ expect(Math.max(...sizes)).toBeLessThanOrEqual(5);+ });++ it("renders \\[…\\] mid-sentence without breaking the paragraph open", () => {+ // Display math is emitted as a <span>, so it nests legally inside the surrounding <p>.+ const html = render(String.raw`before \[x\] after`);+ expect(isDisplay(html)).toBe(true);+ expect(html).not.toMatch(/<p>[\s\S]*<(?:div|pre)\b/);+ expect(text(html)).toContain("before");+ expect(text(html)).toContain("after");+ });++ it("carries a multi-line formula that sits inside one paragraph", () => {+ const html = render(+ "start\n\\[\n\\begin{aligned}\na &= b \\\\\nc &= d\n\\end{aligned}\n\\]\nend",+ );+ expect(isDisplay(html)).toBe(true);+ expect(text(html)).toContain("start");+ expect(text(html)).toContain("end");+ });++ it("renders ordinary formulas: fractions, integrals, matrices, inline mass-energy", () => {+ for (const source of [+ String.raw`\[\frac{a}{b}\]`,+ String.raw`\[\int_0^\infty e^{-x^2}\,dx = \frac{\sqrt{\pi}}{2}\]`,+ String.raw`\[\begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix}\]`,+ String.raw`\(E=mc^2\)`,+ ]) {+ const html = render(source);+ expect(isMath(html), source).toBe(true);+ expect(html, source).not.toContain("katex-error");+ }+ });++ it("gives CJK inside \\text{} the class the stylesheet hangs a font fallback on", () => {+ // KaTeX's own faces have no CJK glyphs; it tags the run `cjk_fallback` and defines nothing for+ // it, so styles.css points that class at the app's stack. Without the class there is no hook.+ expect(render(String.raw`\[\text{采集}\]`)).toContain("cjk_fallback");+ });+});++describe("delimiters that are not math", () => {+ it("leaves shell variables and prices alone (single-dollar math is off)", () => {+ for (const prose of [+ "Set $PATH and $HOME before running.",+ "It costs $5 and $10 in total.",+ "The range is $5-$10 per seat.",+ "Use $HOME/.penguin/data or $PENGUIN_HOME.",+ "echo $PATH; echo $HOME",+ "Prices: $1,200 and $3,400.",+ "50% off: $20 to $10",+ "Balance: $0. Fee: $3.",+ ]) {+ const html = render(prose);+ expect(isMath(html), prose).toBe(false);+ // Every dollar sign survives, and so does the wording around it.+ expect(text(html), prose).toBe(prose);+ }+ });++ it("never renders math inside inline code", () => {+ for (const source of ["`$$x$$`", "`\\(x\\)`", "`\\[x\\]`", "`$PATH`"]) {+ const html = render(source);+ expect(isMath(html), source).toBe(false);+ expect(html, source).toContain("<code>");+ }+ });++ it("does not reach into a code span for a closer", () => {+ // The opener is safe by construction — the tokenizer is only entered where inline content is+ // read — but a closer inside a code span is just more raw characters to a scan already inside+ // a formula. Prose about the delimiters is the shape that breaks.+ for (const source of [+ "In LaTeX you open with \\( and close with `\\)`.",+ "Open with \\[ and close with `\\]`.",+ "Write \\( then `\\)` then more text.",+ ]) {+ const html = render(source);+ expect(isMath(html), source).toBe(false);+ expect(html, source).toContain("<code>");+ // The code span survives intact: no backtick spilled into the surrounding prose.+ expect(text(html), source).not.toContain("`");+ }+ });++ it("never renders math inside a fenced or indented code block", () => {+ for (const source of [+ "```\n\\[x\\]\n$$y$$\n\\(z\\)\n```",+ "```bash\necho $PATH\n\\[x\\]\n```",+ "~~~\n\\[x\\]\n~~~",+ " \\[x\\]\n $$y$$",+ ]) {+ expect(isMath(render(source)), source).toBe(false);+ }+ });++ it("leaves an escaped backslash-bracket as literal text", () => {+ const html = render(String.raw`escaped \\[not math\\] here`);+ expect(isMath(html)).toBe(false);+ expect(text(html)).toBe(String.raw`escaped \[not math\] here`);+ });++ it("does not disturb the other character escapes", () => {+ const html = render(String.raw`a \* b and \_c\_ and \# d`);+ expect(text(html)).toBe("a * b and _c_ and # d");+ expect(html).not.toContain("<em>");+ });+});++describe("collisions resolved on purpose", () => {+ it("reads CommonMark's escaped brackets as math", () => {+ // `\[` and `\]` are also the escapes for a literal bracket, so a footnote marker or a+ // placeholder written that way becomes a formula — and, `\[…\]` being display, a centred one+ // that splits the sentence. Two syntaxes over one character, and only one can win; it goes to+ // the one models actually emit. Pinned so the trade stays a decision rather than a surprise.+ for (const source of [+ String.raw`See \[1\] and \[2\] for details.`,+ String.raw`Write \[TODO\] in the file.`,+ String.raw`Use \(foo\) to capture a group.`,+ ]) {+ expect(isMath(render(source)), source).toBe(true);+ }+ });+});++describe("input that arrives broken or half-written", () => {+ it("renders a malformed expression as its own source instead of throwing", () => {+ const html = render(String.raw`\[\frac{1\]`);+ expect(html).toContain("katex-error");+ expect(text(html)).toContain(String.raw`\frac{1`);+ });++ it("keeps the rest of the message when one formula fails", () => {+ const html = render(String.raw`before \(\frac{1\) after \(E=mc^2\) end`);+ expect(text(html)).toContain("before");+ expect(text(html)).toContain("after");+ expect(text(html)).toContain("end");+ expect(html).toContain("katex-error"); // the broken one+ expect(html).toContain('class="katex"'); // the good one still rendered+ });++ it("renders the user's own mangled paste rather than blanking the reply", () => {+ // `\text(…)` — braces typed as parentheses. LaTeX-incompatible, still renderable.+ const html = render(String.raw`\[\text(采集) \rightarrow \text(解码)\]`);+ expect(text(html)).toContain("采集");+ expect(html).not.toBe("");+ });++ it("shows an unterminated delimiter as ordinary text, then settles when the closer lands", () => {+ // The three states a streaming reply passes through, delta by delta.+ const partial = String.raw`结论:\[\text{采集} \right`;+ expect(isMath(render(partial))).toBe(false);+ expect(text(render(partial))).toContain(String.raw`\text{采集}`);++ const stillPartial = String.raw`结论:\[\text{采集} \rightarrow \text{解码}`;+ expect(isMath(render(stillPartial))).toBe(false);++ const settled = String.raw`结论:\[\text{采集} \rightarrow \text{解码}\]`;+ expect(isDisplay(render(settled))).toBe(true);+ expect(text(render(settled))).toContain("结论:");+ });++ it("an unclosed opener costs one scan, not one per opener", () => {+ // Each opener with no closer used to scan the rest of the paragraph, so a paragraph full of+ // stray ones cost a full pass each — 1000 of them in an 18k-character paragraph measured ~235x+ // the same paragraph on its own, and chat bodies re-parse as they stream. Guards the give-up+ // memo in remark-math-brackets.ts. Compared as a ratio against a control render in the same+ // process rather than against a wall clock, so a loaded CI box moves both numbers together.+ const paragraph = "中文段落内容".repeat(3000);+ const hostile = "\\[".repeat(1000) + paragraph;+ const measure = (source: string) => {+ const started = performance.now();+ render(source);+ return performance.now() - started;+ };+ measure(hostile); // warm the pipeline, JIT included+ measure(paragraph);+ const control = Math.max(measure(paragraph), 1);+ expect(measure(hostile) / control).toBeLessThan(20);+ });+});++describe("the chat renderer", () => {+ const renderMd = (text: string, streaming = false) =>+ renderToStaticMarkup(createElement(Md, { text, streaming }));++ it("typesets a formula on settle and shows its source until then", () => {+ // rehype-katex is the expensive half of the pipeline — KaTeX's markup is re-parsed into hast+ // and rebuilt as several hundred React elements per formula — and a streaming body re-renders+ // on every delta. So the stage is held back to the settle render, the same one that+ // re-highlights code blocks. Losing this is invisible in a screenshot and quadratic in a chat.+ expect(isDisplay(renderMd(String.raw`\[\frac{a}{b}\]`))).toBe(true);+ expect(isMath(renderMd(String.raw`\(E=mc^2\)`))).toBe(true);++ for (const [source, formula] of [+ [String.raw`\[\frac{a}{b}\]`, String.raw`\frac{a}{b}`],+ [String.raw`\(E=mc^2\)`, "E=mc^2"],+ ["$$E=mc^2$$", "E=mc^2"],+ ] as const) {+ const html = renderMd(source, true);+ expect(isMath(html), source).toBe(false);+ // The source, delimiters aside, stays legible while it streams.+ expect(text(html), source).toBe(formula);+ }+ });++ it("keeps a streaming $$ block out of the CodeBlock chrome", () => {+ // remark-math models block math as a `language-math` fence, which is exactly what the `pre`+ // override turns into CodeBlock. Settled, rehype-katex replaces the pair before the override+ // is consulted; streaming, nothing does — so a formula would grow a language label and a copy+ // button for as long as the reply takes to arrive, then lose them.+ const html = renderMd("$$\n\\frac{a}{b}\n$$", true);+ expect(html).not.toContain("code-block");+ expect(html).toContain("<pre>");+ expect(text(html)).toContain(String.raw`\frac{a}{b}`);+ });++ it("a $$ block becomes a formula, not a code block", () => {+ // remark-math models block math as <pre><code class="language-math">, which is exactly what the+ // chat renderer's `pre` override turns into CodeBlock chrome. rehype-katex replaces the <pre>+ // outright before that override is ever consulted, so the two never collide.+ const html = renderMd("$$\n\\frac{a}{b}\n$$");+ expect(isDisplay(html)).toBe(true);+ expect(html).not.toContain("code-block");+ });++ it("still routes real fenced code through CodeBlock", () => {+ const html = renderMd("```js\nconst a = 1;\n```");+ expect(html).toContain("code-block");+ expect(isMath(html)).toBe(false);+ });+});++describe("the pipeline every renderer shares", () => {+ const read = (relative: string) =>+ readFileSync(fileURLToPath(new URL(relative, import.meta.url)), "utf8");++ /**+ * A renderer that quietly dropped the shared list would still render Markdown, so no behavioural+ * test would fail — only its math and its URL boundaries would be wrong, on one surface. Hence a+ * source scan: every `<ReactMarkdown` in the app has to carry both stages.+ */+ const RENDERERS = [+ "../src/features/chat/md.tsx",+ "../src/features/chat/workspace-browser.tsx",+ "../src/features/benchmark/benchmark-case-browser.tsx",+ "../src/features/traces/trace-event-row.tsx",+ ];++ /**+ * Matched by the constant each prop names rather than by an exact string, because md.tsx picks+ * its rehype stage by `streaming`. What is being guarded is that the name comes from the shared+ * module, not the shape of the expression around it.+ */+ const SHARED = { remarkPlugins: "REMARK_PLUGINS", rehypePlugins: "REHYPE_PLUGINS" };++ it("every ReactMarkdown in the app is given both shared plugin lists", () => {+ let total = 0;+ for (const relative of RENDERERS) {+ const source = read(relative);+ const uses = source.split("<ReactMarkdown").length - 1;+ expect(uses, relative).toBeGreaterThan(0);+ total += uses;+ for (const [prop, constant] of Object.entries(SHARED)) {+ const values = [...source.matchAll(new RegExp(`${prop}=\\{([^}]*)\\}`, "g"))];+ expect(values.length, `${relative} ${prop}`).toBe(uses);+ for (const [, value] of values) expect(value, `${relative} ${prop}`).toContain(constant);+ }+ expect(source, relative).toContain('from "../../lib/markdown-plugins"');+ }+ expect(total).toBe(5); // md.tsx, workspace, benchmark, and two in trace-event-row+ });++ it("no renderer assembles its own pipeline out of the underlying plugins", () => {+ for (const relative of RENDERERS) {+ const source = read(relative);+ // The quotes are the point: a renderer may name a plugin in a comment, not import one.+ for (const plugin of ["remark-gfm", "remark-math", "rehype-katex"]) {+ expect(source, `${relative} imports ${plugin} directly`).not.toContain(`"${plugin}"`);+ }+ }+ });+});++describe("KaTeX fonts ship locally, woff2 only", () => {+ const SRC = `@font-face{font-display:block;font-family:KaTeX_Main;src:url(fonts/KaTeX_Main-Regular.woff2) format("woff2"),url(fonts/KaTeX_Main-Regular.woff) format("woff"),url(fonts/KaTeX_Main-Regular.ttf) format("truetype")}`;++ it("keeps the woff2 source and drops the woff and truetype ones", () => {+ const stripped = dropNonWoff2FontSources(SRC);+ expect(stripped).toContain('url(fonts/KaTeX_Main-Regular.woff2) format("woff2")');+ expect(stripped).not.toContain(".woff)");+ expect(stripped).not.toContain(".ttf)");+ expect(stripped).toContain("font-family:KaTeX_Main");+ });++ it("leaves a stylesheet that has no fallbacks untouched", () => {+ const only = `@font-face{src:url(fonts/A.woff2) format("woff2")}`;+ expect(dropNonWoff2FontSources(only)).toBe(only);+ });+});diff --git a/packages/web/test/remark-autolink-boundary.test.ts b/packages/web/test/remark-autolink-boundary.test.tsindex 45317f56..7c6de1d9 100644--- a/packages/web/test/remark-autolink-boundary.test.ts+++ b/packages/web/test/remark-autolink-boundary.test.ts@@ -8,7 +8,7 @@ import { describe, expect, it } from "vitest";import React from "react";import { renderToStaticMarkup } from "react-dom/server";import ReactMarkdown from "react-markdown";-import { REMARK_PLUGINS } from "../src/lib/remark-autolink-boundary";+import { REMARK_PLUGINS } from "../src/lib/markdown-plugins";/** The rendered `[href, text]` of the first link, or null. */function firstLink(markdown: string): [string, string] | null {diff --git a/packages/web/vite.config.ts b/packages/web/vite.config.tsindex 8d4f9a6c..8011ff6b 100644--- a/packages/web/vite.config.ts+++ b/packages/web/vite.config.ts@@ -12,6 +12,7 @@import react from "@vitejs/plugin-react";import tailwindcss from "@tailwindcss/vite";import { defineConfig } from "vite";+import type { Plugin } from "vite";/*** Resolves the `/api` proxy target: PENGUIN_API_PROXY replaces it outright, otherwise the@@ -30,8 +31,42 @@ export function apiProxyTarget(env: Record<string, string | undefined> = processreturn env.PENGUIN_API_PROXY || `http://127.0.0.1:${env.PORT || "7368"}`;}+/**+ * Drops the `woff` and `truetype` fallbacks from a KaTeX stylesheet, leaving each `@font-face` with+ * its woff2 source alone.+ *+ * KaTeX ships twenty faces in three formats and lists all three in every `src`, so Vite — which+ * emits an asset for each URL a stylesheet references — copies sixty font files into the bundle.+ * The forty non-woff2 ones are ~800KB that nothing can request: woff2 has been supported by every+ * browser this SPA runs in since 2016, and the desktop shell is Chromium. A browser somehow without+ * it now falls back to the `serif` at the end of KaTeX's own font stack rather than failing.+ *+ * Exported for the unit test: a silent miss here (a Vite id format change, a KaTeX release that+ * reorders `src`) costs bundle size without breaking anything, so nothing would otherwise notice.+ */+export function dropNonWoff2FontSources(css: string): string {+ return css.replace(/\s*,\s*url\([^)]*\.(?:woff|ttf)\)\s*format\("(?:woff|truetype)"\)/g, "");+}++/**+ * Applies {@link dropNonWoff2FontSources} to KaTeX's stylesheet before Vite resolves the `url()`s+ * in it into emitted assets, which is what `enforce: "pre"` buys — by the time the `vite:css`+ * transform runs, the fallback URLs must already be gone or their files are copied regardless.+ */+function katexWoff2Only(): Plugin {+ return {+ name: "penguin:katex-woff2-only",+ enforce: "pre",+ transform(code, id) {+ if (!id.includes("/katex/dist/") || !id.includes(".css")) return null;+ const next = dropNonWoff2FontSources(code);+ return next === code ? null : { code: next, map: null };+ },+ };+}+export default defineConfig({- plugins: [react(), tailwindcss()],+ plugins: [react(), tailwindcss(), katexWoff2Only()],server: {// Fixed PenguinHarness dev port (stands alone — vite configs cannot import core TS,// so the numbers are literals here; the allocation table lives in core's internal/ports.ts).diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 48122b08..4c794b6a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -368,6 +368,9 @@ importers:'@xterm/xterm':specifier: ^5.5.0version: 5.5.0+ katex:+ specifier: ^0.16.47+ version: 0.16.47react:specifier: ^19.1.0version: 19.2.7@@ -380,9 +383,15 @@ importers:react-router:specifier: ^8.3.0+ rehype-katex:+ specifier: ^7.0.1+ version: 7.0.1remark-gfm:specifier: ^4.0.0version: 4.0.1([email protected])+ remark-math:+ specifier: ^6.0.0+ version: 6.0.0([email protected])shiki:specifier: ^4.3.1version: 4.3.1@@ -1474,6 +1483,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-L3LgimLHXtGkWikKnsPg0/VFx9OGZaC+eN1u4r+OB1XRqH3meBIAVC2zr1WdMH+RHmnRkqliQAOHNJ/E0j/e0Q==}+ '@types/[email protected]':+ resolution: {integrity: sha512-trgaNyfU+Xh2Tc+ABIb44a5AYUpicB3uwirOioeOkNPPbmgRNtcWyDeeFRzjPZENO9Vq8gvVqfhaaXWLlevVwg==}+'@types/[email protected]':resolution: {integrity: sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg==}@@ -1849,6 +1861,10 @@ packages:resolution: {integrity: sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg==}engines: {node: '>= 6'}+ resolution: {integrity: sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==}+ engines: {node: '>= 12'}+resolution: {integrity: sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==}engines: {node: ^12.20.0 || >=14}@@ -2330,9 +2346,21 @@ packages:resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-N+LqofjR2zuzTjCPzyDUdSshy4Ma6li7p/c3pA78uTwzFgENbgbUrm2ugwsOdcjI1muO+o6Dgzp9p8WHtn/39Q==}++ resolution: {integrity: sha512-zJfpXq44yff2hmE0XmwEOzdWin5xwH+QIhMLOScpX91e/NSGPsAzNCvLQDIEPyO2TXi+lBmU6hjLIhV8MwP2kw==}++ resolution: {integrity: sha512-CUSRHXyKjzHov8yKsQjGOElXy/3EKpyX56ELnkHH34vDVw1N1XSQ1ZcAvTyAPtGqLTuKP/uxM+aLkSPqF/EtMw==}+resolution: {integrity: sha512-3kxEVkEKt0zvcZ3hCRYI8rqrgwtlIOFMWkbclACvjlDw8Li9S2hk/d51OI0nr/gIpdMHNepwgOKqZ/sy0Clpyg==}+ resolution: {integrity: sha512-Val9mnv2IWpLbNPqc/pUem+a7Ipj2aHacCwgNfTiK0vJKl0LF+4Ba4+v1oPHFpf3bLYmreq0/l3Gud9S5OH42g==}+resolution: {integrity: sha512-wkQCkSYoOGCRKERFWcxMVMOcYE2K1AaNLU8DXS9arxnLOUEWbOXKXiJUNzEpqZ3JOKpnha3jkFrumEjVliDe7A==}@@ -2348,6 +2376,9 @@ packages:resolution: {integrity: sha512-MlWT6Pjt4CG9lFCjiz4BH7l9wmrMkfkJYCxFwKQic8+RTZgWPuWxwAfjJElsXkex7DJjfSJsQIt931ilUgmwdA==}+ resolution: {integrity: sha512-KK6y/BN8lbaq654j7JgBydev7wuNMcID54lkRav1P0CaE1e47P72AWWPiGKXTJU271ooYzcvTAn/Zt0REnvc7A==}+resolution: {integrity: sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==}@@ -2515,6 +2546,10 @@ packages:resolution: {integrity: sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==}+ resolution: {integrity: sha512-Eeo8Ys1doU1z+x8AZsPpQu+p/QcZBI5PeOo7QGQdy2x2m0MU/hYagBbGOmXwr5KVbEfVuWv9LpnQWeehogurjg==}+ hasBin: true+resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==}@@ -2683,6 +2718,9 @@ packages:resolution: {integrity: sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ==}+ resolution: {integrity: sha512-Tl9GBNeG/AhJnQM221bJR2HPvLOSnLE/T9cJI9tlc6zwQk2nPk/4f0cHkOdEixQPC/j8UtKDdITswvLAy1OZ1w==}+resolution: {integrity: sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ==}@@ -2739,6 +2777,9 @@ packages:resolution: {integrity: sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==}+ resolution: {integrity: sha512-lvEqd+fHjATVs+2v/8kg9i5Q0AP2k85H0WUOwpIVvUML8BapsMvh1XAogmQjOCsLpoKRCVQqEkQBB3NhVBcsOg==}+resolution: {integrity: sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==}@@ -3179,12 +3220,18 @@ packages:resolution: {integrity: sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg==}+ resolution: {integrity: sha512-OiM2wrZ/wuhKkigASodFoo8wimG3H12LWQaH8qSPVJn9apWKFSH3YOCtbKpBorTVw/eI7cuT21XBbvwEswbIOA==}+resolution: {integrity: sha512-/aE8hCfKlQeA8LmyeyQvQF3eBiLRGNlfBJEvWH7ivp9sBqs7TNqBL5X3v157rM4IFETqDnIOO+z5M/biZbo9Ww==}resolution: {integrity: sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==}+ resolution: {integrity: sha512-MMqgnP74Igy+S3WwnhQ7kqGlEerTETXMvJhrUzDikVZ2/uogJCb+WHUg97hK9/jcfc0dkD73s3LN8zU49cTEtA==}+resolution: {integrity: sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==}@@ -3571,12 +3618,18 @@ packages:resolution: {integrity: sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==}+ resolution: {integrity: sha512-amQa0Ep2m6hE2g72AugUItjbuM8X8cGQnFoHk0pGfrFeT9GZhzN5SW8nRsiGKK7Aif4CrACPENkA6P/Lw6fHGQ==}+resolution: {integrity: sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==}resolution: {integrity: sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==}+ resolution: {integrity: sha512-Hp5Kh3wLxv0PHj9m2yZhhLt58KzPtEYKQQ4yxfYFEO7EvHwzyDYnduhHnY1mDxoqr7VUwVuHXk9RXKIiYS1N8Q==}+resolution: {integrity: sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==}@@ -4593,7 +4646,7 @@ snapshots:dependencies:'@modelcontextprotocol/client': 2.0.0'@prismshadow/agenthub': 0.4.8([email protected])([email protected])- '@prismshadow/penguin-core': file:packages/core([email protected])+ '@prismshadow/penguin-core': file:packages/core([email protected])([email protected])'@prismshadow/penguin-server': file:packages/server([email protected])'@prismshadow/penguin-skills': file:packages/skillscommander: 13.1.0@@ -4609,22 +4662,6 @@ snapshots:- ws- zod- '@prismshadow/penguin-core@file:packages/core([email protected])':- dependencies:- '@modelcontextprotocol/client': 2.0.0- '@prismshadow/agenthub': 0.4.8([email protected])([email protected])- '@prismshadow/penguin-skills': file:packages/skills- arktype: 2.2.3- smol-toml: 1.6.1- yaml: 2.9.0- transitivePeerDependencies:- - '@modelcontextprotocol/sdk'- - bufferutil- - supports-color- - utf-8-validate- - ws- - zod-'@prismshadow/penguin-core@file:packages/core([email protected])([email protected])':dependencies:'@modelcontextprotocol/client': 2.0.0@@ -5204,6 +5241,8 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]': {}+'@types/[email protected]':dependencies:'@types/node': 24.13.3@@ -5633,6 +5672,8 @@ snapshots:+ [email protected]: {}+optional: true@@ -6224,6 +6265,28 @@ snapshots:dependencies:function-bind: 1.1.2+ dependencies:+ '@types/hast': 3.0.4+ hastscript: 9.0.1+ web-namespaces: 2.0.1++ dependencies:+ '@types/hast': 3.0.4+ hast-util-from-dom: 5.0.1+ hast-util-from-html: 2.0.3+ unist-util-remove-position: 5.0.0++ dependencies:+ '@types/hast': 3.0.4+ devlop: 1.1.0+ hast-util-from-parse5: 8.0.3+ parse5: 7.3.0+ vfile: 6.0.3+ vfile-message: 4.0.3+dependencies:'@types/hast': 3.0.4@@ -6235,6 +6298,10 @@ snapshots:vfile-location: 5.0.3web-namespaces: 2.0.1+ dependencies:+ '@types/hast': 3.0.4+dependencies:'@types/hast': 3.0.4@@ -6299,6 +6366,13 @@ snapshots:web-namespaces: 2.0.1zwitch: 2.0.4+ dependencies:+ '@types/hast': 3.0.4+ '@types/unist': 3.0.3+ hast-util-is-element: 3.0.0+ unist-util-find-after: 5.0.0+dependencies:'@types/hast': 3.0.4@@ -6460,6 +6534,10 @@ snapshots:jwa: 2.0.1safe-buffer: 5.2.1+ dependencies:+ commander: 8.3.0+dependencies:json-buffer: 3.0.1@@ -6643,6 +6721,18 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ '@types/hast': 3.0.4+ '@types/mdast': 4.0.4+ devlop: 1.1.0+ longest-streak: 3.1.0+ mdast-util-from-markdown: 2.0.3([email protected])+ mdast-util-to-markdown: 2.1.2+ unist-util-remove-position: 5.0.0+ transitivePeerDependencies:+ - supports-color+dependencies:'@types/estree-jsx': 1.0.5@@ -6798,6 +6888,16 @@ snapshots:micromark-util-combine-extensions: 2.0.1micromark-util-types: 2.0.2+ dependencies:+ '@types/katex': 0.16.8+ devlop: 1.1.0+ katex: 0.16.47+ micromark-factory-space: 2.0.1+ micromark-util-character: 2.1.1+ micromark-util-symbol: 2.0.1+ micromark-util-types: 2.0.2+dependencies:micromark-util-character: 2.1.1@@ -7276,6 +7376,16 @@ snapshots:dependencies:regex-utilities: 2.3.0+ dependencies:+ '@types/hast': 3.0.4+ '@types/katex': 0.16.8+ hast-util-from-html-isomorphic: 2.0.0+ hast-util-to-text: 4.0.2+ katex: 0.16.47+ unist-util-visit-parents: 6.0.2+ vfile: 6.0.3+dependencies:'@types/hast': 3.0.4@@ -7293,6 +7403,15 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ '@types/mdast': 4.0.4+ mdast-util-math: 3.0.0([email protected])+ micromark-extension-math: 3.1.0+ unified: 11.0.5+ transitivePeerDependencies:+ - supports-color+dependencies:'@types/mdast': 4.0.4@@ -7731,6 +7850,11 @@ snapshots:trough: 2.2.0vfile: 6.0.3+ dependencies:+ '@types/unist': 3.0.3+ unist-util-is: 6.0.1+dependencies:'@types/unist': 3.0.3@@ -7739,6 +7863,11 @@ snapshots:dependencies:'@types/unist': 3.0.3+ dependencies:+ '@types/unist': 3.0.3+ unist-util-visit: 5.1.0+dependencies:'@types/unist': 3.0.3