Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

refactor(ui): W5 — Markdown, code and the type roles move into the UI package (#900)

Yaowei Zheng8662e249e3ca
diff --git a/changelog/unreleased/2026-09-30-ui-migration-w5.md b/changelog/unreleased/2026-09-30-ui-migration-w5.md
new file mode 100644
index 00000000..0c661324
--- /dev/null
+++ b/changelog/unreleased/2026-09-30-ui-migration-w5.md
@@ -0,0 +1,33 @@
+# Markdown, code and the type roles move into the shared UI package
+
+- **Date:** 2026-09-30
+- **Type:** refactor
+- **Scope:** `ui`, `web`, `ui-gallery`
+
+[中文版](2026-09-30-ui-migration-w5.zh.md)
+
+W5 of the UI-package migration moves the Web App's content rendering into `@prismshadow/penguin-ui`: Markdown, code blocks and their highlighting, and adds the type roles and a diff viewer.
+
+## What moved
+
+- **Markdown:** `Md` (same props and name) and the new `Prose` reading box in three densities (`body`, `compact`, `flush`), with the shared plugin pipeline (`REMARK_PLUGINS`, `REHYPE_PLUGINS`, `NO_REHYPE_PLUGINS`) and its autolink and math passes. The `.md-body`, `.md-compact`, `.code-*`, Shiki and KaTeX rules leave the app's stylesheet for the package's `prose.css`, written in tokens. KaTeX's stylesheet now comes with the package.
+- **Links:** Markdown links open in a new tab unless a `ProseLinksProvider` decides otherwise; the app's `WorkspaceLinksProvider` (a conversation's links to Workspace files) is built on it.
+- **Code:** `CodeBlock` (the `ui-frame` host for code) and `CodeSurface`, with the language tables. The components never run Shiki themselves: they ask a `CodeHighlighter` handed to them by prop or by `CodeHighlighterProvider`. The engine is its own subpath, `@prismshadow/penguin-ui/highlighter`, and the Web App keeps running it on a worker.
+- **The Workspace Markdown preview** renders through `Prose` instead of a second copy of the pipeline.
+- **New:** `Heading` (the theme's h1–h6 rungs; `display` for a page's one display title), `Text` (body, small, caption, eyebrow, mono and label roles), `InlineCode`, and `DiffViewer` (unified or side by side, from two texts or a patch, with changed words marked and both sides highlighted).
+
+## Details
+
+- The package's accessibility fallbacks gain "Copy code", supplied by the Web App in the interface language.
+- `Md` takes extra remark plugins and element overrides on top of the shared pipeline; the company channel's mention chips and the tickets' path capsules render through them.
+- The gallery's component library gains a Content page.
+- KaTeX, Shiki and the remark / rehype plugins become dependencies of the package; the Web App keeps only `react-markdown`.
+
+## Visible changes in the default theme (Primer)
+
+- Inline code in Markdown, and code shown before it is highlighted, take the body ink: one step darker in light, one step lighter in dark.
+- A Markdown blockquote's text is one step lighter in light.
+- A Markdown link's underline is its own ink thinned; in dark it no longer darkens on hover.
+- A formula KaTeX cannot parse keeps a dotted underline one step lighter in dark.
+- Code in a message's code block follows the text-size setting (13 px at the default size).
+- Fenced code in the Files panel's Markdown preview gets the code-block frame, with its language and copy button.
diff --git a/changelog/unreleased/2026-09-30-ui-migration-w5.zh.md b/changelog/unreleased/2026-09-30-ui-migration-w5.zh.md
new file mode 100644
index 00000000..6568513c
--- /dev/null
+++ b/changelog/unreleased/2026-09-30-ui-migration-w5.zh.md
@@ -0,0 +1,33 @@
+# Markdown、代码与文字角色迁入共享 UI 包
+
+- **Date:** 2026-09-30
+- **Type:** refactor
+- **Scope:** `ui`, `web`, `ui-gallery`
+
+[English](2026-09-30-ui-migration-w5.md)
+
+UI 包迁移的 W5 把 Web App 的内容渲染搬进 `@prismshadow/penguin-ui`:Markdown、代码块及其高亮,并新增文字角色组件与差异视图。
+
+## 迁入的内容
+
+- **Markdown**:`Md`(属性与名称不变)与新增的阅读容器 `Prose`(`body`、`compact`、`flush` 三种密度),连同共享的插件管线(`REMARK_PLUGINS`、`REHYPE_PLUGINS`、`NO_REHYPE_PLUGINS`)及其自动链接与公式处理。`.md-body`、`.md-compact`、`.code-*`、Shiki 与 KaTeX 的样式从应用样式表移入包内的 `prose.css`,改以令牌书写;KaTeX 样式表也改由包加载。
+- **链接**:Markdown 链接默认在新标签页打开,由 `ProseLinksProvider` 决定例外;应用的 `WorkspaceLinksProvider`(对话里指向 Workspace 文件的链接)建立在它之上。
+- **代码**:`CodeBlock`(代码的 `ui-frame` 宿主)与 `CodeSurface`,连同语言表。组件自身从不运行 Shiki,而是调用经属性或 `CodeHighlighterProvider` 传入的 `CodeHighlighter`;引擎单独发布为子路径 `@prismshadow/penguin-ui/highlighter`,Web App 仍在 Worker 中运行它。
+- **Workspace 的 Markdown 预览** 改经 `Prose` 渲染,不再保留第二套管线。
+- **新增**:`Heading`(主题的 h1–h6 字阶,`display` 用于页面唯一的展示标题)、`Text`(正文、小字、说明、分组标签、等宽与字段标签六种角色)、`InlineCode`,以及 `DiffViewer`(合并或并排视图,接受两段文本或补丁,标出改动的词并高亮两侧代码)。
+
+## 细节
+
+- 包自带的无障碍兜底文案新增「复制代码」,由 Web App 按界面语言提供。
+- `Md` 可在共享管线之上追加 remark 插件与元素覆盖;公司频道的提及标签与工单的路径胶囊经由它们渲染。
+- 画廊的组件库新增「内容」页。
+- KaTeX、Shiki 与 remark / rehype 插件改由包依赖;Web App 只保留 `react-markdown`。
+
+## 通用主题下可见的变化
+
+- Markdown 中的行内代码与尚未高亮的代码改用正文墨色:浅色下深一档,深色下浅一档。
+- Markdown 引用块的文字在浅色下浅一档。
+- Markdown 链接的下划线改为其自身墨色的淡色;深色下悬停不再变深。
+- KaTeX 无法解析的公式,其虚线下划线在深色下浅一档。
+- 消息代码块中的代码跟随文字大小设置(默认大小下仍为 13 px)。
+- 文件面板 Markdown 预览中的代码块加上代码块外框,带语言标签与复制按钮。
diff --git a/packages/ui-gallery/src/app/main.tsx b/packages/ui-gallery/src/app/main.tsx
index b7ec057b..bb19c214 100644
--- a/packages/ui-gallery/src/app/main.tsx
+++ b/packages/ui-gallery/src/app/main.tsx
@@ -7,8 +7,8 @@
*
* The app's own entry reconciles browser storage against the server's data root before
* mounting; a frame's storage is fresh every load, so there is nothing to reconcile and the
- * app mounts at once. KaTeX's stylesheet and the app's come in the same order as in the app's
- * entry, so the app's `.katex` rules still win the cascade.
+ * app mounts at once. KaTeX's stylesheet comes with the shared UI package's Markdown (its prose
+ * component imports it), as it does in the app.
*
* `open=settings` (or `settings.<page>`) asks the app for its Settings dialog through the
* app's own request seam, which the account menu answers as soon as it mounts.
@@ -18,9 +18,6 @@ import { createRoot } from "react-dom/client";
import { App } from "../../../web/src/app";
import { requestSettings } from "../../../web/src/features/settings/settings-request";
import type { SettingsSectionKey } from "../../../web/src/lib/settings-sections";
-// The app's dependency, reached through its own node_modules: the gallery does not depend on
-// KaTeX, and the app's math rules expect this sheet ahead of the app's own.
-import "../../../web/node_modules/katex/dist/katex.min.css";
import "./app.css";
import { parseFrameParams } from "./frame";
import { installFetchShim } from "./mock/fetch-shim";
diff --git a/packages/ui-gallery/src/library/boards.tsx b/packages/ui-gallery/src/library/boards.tsx
index cb422c56..af7d1919 100644
--- a/packages/ui-gallery/src/library/boards.tsx
+++ b/packages/ui-gallery/src/library/boards.tsx
@@ -16,6 +16,7 @@ import { AvatarsBoard } from "./boards/avatars";
import { BadgesBoard } from "./boards/badges";
import { ButtonsBoard } from "./boards/buttons";
import { ChartsBoard } from "./boards/charts";
+import { ContentBoard } from "./boards/content";
import { DialogsBoard } from "./boards/dialogs";
import { EmptyBoard } from "./boards/empty";
import { FilesBoard } from "./boards/files";
@@ -45,6 +46,7 @@ export const BOARDS: Readonly<Record<TopicId, ComponentType>> = {
charts: ChartsBoard,
avatars: AvatarsBoard,
files: FilesBoard,
+ content: ContentBoard,
colour: ColourBoard,
type: TypeBoard,
shape: ShapeBoard,
diff --git a/packages/ui-gallery/src/library/boards/content.tsx b/packages/ui-gallery/src/library/boards/content.tsx
new file mode 100644
index 00000000..a40a6cd9
--- /dev/null
+++ b/packages/ui-gallery/src/library/boards/content.tsx
@@ -0,0 +1,138 @@
+/**
+ * 内容: the type roles (every heading rung, the display title, the text roles, inline code),
+ * Markdown as reading text in its two densities, a code block and a bare code surface with its
+ * gutter, and the diff viewer unified, side by side and read from a patch — all from the package.
+ * Code is highlighted by the highlighter the frame provides, as in the app.
+ */
+import {
+ CodeBlock,
+ CodeSurface,
+ DiffViewer,
+ Heading,
+ InlineCode,
+ Prose,
+ Text,
+} from "@prismshadow/penguin-ui";
+import type { HeadingLevel, TextVariant } from "@prismshadow/penguin-ui";
+import { BoardGroup } from "../../foundations/shared";
+import { useGallery } from "../../state";
+
+const LEVELS: readonly HeadingLevel[] = [1, 2, 3, 4, 5, 6];
+const TEXT_VARIANTS: readonly TextVariant[] = [
+ "body",
+ "small",
+ "caption",
+ "eyebrow",
+ "mono",
+ "label",
+];
+
+/** Code is the same in both languages: it is data, not copy. */
+const CODE = `export function greet(name: string, excited = false): string {
+ const mark = excited ? "!" : ".";
+ return \`Hello, \${name}\${mark}\`;
+}
+`;
+
+const BEFORE = `import { readFile } from "node:fs/promises";
+
+export async function loadConfig(path: string) {
+ const text = await readFile(path, "utf8");
+ return JSON.parse(text);
+}
+
+export const DEFAULT_PATH = "config.json";
+`;
+
+const AFTER = `import { readFile } from "node:fs/promises";
+
+export async function loadConfig(path: string, fallback = {}) {
+ const text = await readFile(path, "utf8").catch(() => null);
+ return text === null ? fallback : JSON.parse(text);
+}
+
+export const DEFAULT_PATH = "penguin.config.json";
+`;
+
+const PATCH = `diff --git a/src/limits.ts b/src/limits.ts
+--- a/src/limits.ts
++++ b/src/limits.ts
+@@ -1,4 +1,5 @@ export const LIMITS
+ export const LIMITS = {
+- uploadMb: 10,
++ uploadMb: 14,
++ previewKb: 256,
+ retries: 3,
+ };
+`;
+
+export function ContentBoard() {
+ const { S } = useGallery();
+ const t = S.library.content;
+ return (
+ <div className="gf-board">
+ <BoardGroup title={t.headings} aside={t.headingsHint}>
+ <div className="lib-stack lib-stack-wide">
+ <Heading level={1} display>
+ {t.display}
+ </Heading>
+ {LEVELS.map((level) => (
+ <Heading key={level} level={level}>
+ {t.heading(level)}
+ </Heading>
+ ))}
+ </div>
+ </BoardGroup>
+ <BoardGroup title={t.text}>
+ <div className="lib-stack lib-stack-wide">
+ {TEXT_VARIANTS.map((variant) => (
+ <div key={variant} className="lib-row">
+ <Text variant={variant}>{t.samples[variant]}</Text>
+ <code className="lib-caption">{variant}</code>
+ </div>
+ ))}
+ <div className="lib-row">
+ <Text>
+ {t.inline.before}
+ <InlineCode>{t.inline.code}</InlineCode>
+ {t.inline.after}
+ </Text>
+ <code className="lib-caption">InlineCode</code>
+ </div>
+ </div>
+ </BoardGroup>
+ <BoardGroup title={t.prose}>
+ <div className="lib-stack lib-stack-wide">
+ <Prose text={t.proseSample} className="text-base leading-relaxed text-fg" />
+ <span className="lib-caption">{t.compact}</span>
+ <Prose variant="compact" text={t.compactSample} className="text-sm text-fg" />
+ </div>
+ </BoardGroup>
+ <BoardGroup title={t.code}>
+ <div className="lib-stack lib-stack-wide">
+ <CodeBlock language="ts" code={CODE} />
+ <span className="lib-caption">{t.surface}</span>
+ <div className="lib-box text-xs leading-relaxed">
+ <CodeSurface language="ts" code={CODE} lineNumbers />
+ </div>
+ </div>
+ </BoardGroup>
+ <BoardGroup title={t.diff}>
+ <div className="lib-stack lib-stack-wide">
+ <span className="lib-caption">{t.unified}</span>
+ <DiffViewer before={BEFORE} after={AFTER} language="ts" label={t.diffLabel} />
+ <span className="lib-caption">{t.split}</span>
+ <DiffViewer
+ before={BEFORE}
+ after={AFTER}
+ language="ts"
+ mode="split"
+ label={t.diffLabel}
+ />
+ <span className="lib-caption">{t.patch}</span>
+ <DiffViewer patch={PATCH} language="ts" label={t.patchLabel} />
+ </div>
+ </BoardGroup>
+ </div>
+ );
+}
diff --git a/packages/ui-gallery/src/library/main.tsx b/packages/ui-gallery/src/library/main.tsx
index bc4f390f..709ff94c 100644
--- a/packages/ui-gallery/src/library/main.tsx
+++ b/packages/ui-gallery/src/library/main.tsx
@@ -7,15 +7,16 @@
* renders exactly as the app would.
*
* The mock network is installed as in the app frame: a component that fetches (the file
- * browser's preview, a chart) gets the demo store's answer.
+ * browser's preview, a chart) gets the demo store's answer. Code is highlighted by the app's own
+ * worker-backed highlighter, handed to the package's code surfaces as the app hands it; KaTeX's
+ * stylesheet comes with the package's Markdown.
*/
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
-import { Toaster, TooltipLayer } from "@prismshadow/penguin-ui";
+import { CodeHighlighterProvider, Toaster, TooltipLayer } from "@prismshadow/penguin-ui";
+import { highlightCode } from "../../../web/src/features/chat/code-highlight";
import { LocaleProvider, LocaleScope } from "../../../web/src/state/locale";
import { ThemeProvider } from "../../../web/src/state/theme";
-// The app's dependency, reached through its own node_modules, ahead of the app's own sheet.
-import "../../../web/node_modules/katex/dist/katex.min.css";
import "./library.css";
import { installFetchShim } from "../app/mock/fetch-shim";
import { getStore } from "../app/mock/store";
@@ -46,16 +47,18 @@ if (!container) throw new Error("#root mount point not found");
createRoot(container).render(
<StrictMode>
- <LocaleProvider>
- <ThemeProvider>
- <LocaleScope>
- <GalleryProvider>
- <LibraryBoardPage topic={params.topic} />
- </GalleryProvider>
- <Toaster />
- <TooltipLayer />
- </LocaleScope>
- </ThemeProvider>
- </LocaleProvider>
+ <CodeHighlighterProvider highlight={highlightCode}>
+ <LocaleProvider>
+ <ThemeProvider>
+ <LocaleScope>
+ <GalleryProvider>
+ <LibraryBoardPage topic={params.topic} />
+ </GalleryProvider>
+ <Toaster />
+ <TooltipLayer />
+ </LocaleScope>
+ </ThemeProvider>
+ </LocaleProvider>
+ </CodeHighlighterProvider>
</StrictMode>,
);
diff --git a/packages/ui-gallery/src/library/topics.ts b/packages/ui-gallery/src/library/topics.ts
index 55020779..e75af7d7 100644
--- a/packages/ui-gallery/src/library/topics.ts
+++ b/packages/ui-gallery/src/library/topics.ts
@@ -27,6 +27,7 @@ export const TOPIC_IDS = [
"charts",
"avatars",
"files",
+ "content",
"colour",
"type",
"shape",
@@ -62,6 +63,7 @@ export const TOPICS: readonly Topic[] = [
component("charts"),
component("avatars"),
component("files"),
+ component("content"),
foundation("colour"),
foundation("type"),
foundation("shape"),
diff --git a/packages/ui-gallery/src/strings-en.ts b/packages/ui-gallery/src/strings-en.ts
index 9f301c9c..bba30aa9 100644
--- a/packages/ui-gallery/src/strings-en.ts
+++ b/packages/ui-gallery/src/strings-en.ts
@@ -449,6 +449,11 @@ export const en: GalleryStrings = {
description: "The user and agent avatars at their sizes, and a stack of them.",
},
files: { title: "Files", description: "The file tree and the read-only file browser." },
+ content: {
+ title: "Content",
+ description:
+ "Headings and text roles, inline code, Markdown prose, code blocks and surfaces, and the diff viewer.",
+ },
colour: {
title: "Colour",
description: "Surfaces, inks, lines, the accent, the tones, chart series and code colours.",
@@ -848,5 +853,34 @@ export const en: GalleryStrings = {
readme:
"# Docs Expert\n\nBuilds a BM25 index over `corpus/` and answers questions about the Claude Code docs.\n\n- `src/rag.ts` — retrieval\n- `test/` — cases",
},
+ content: {
+ headings: "Headings",
+ headingsHint: "Each level takes the theme's rung; the display title is for a page's h1 only.",
+ display: "Page display title",
+ heading: (level: number) => `Heading ${level}`,
+ text: "Text roles",
+ samples: {
+ body: "Body: the size of messages, notes and settings.",
+ small: "Small: secondary information and metadata.",
+ caption: "Caption: a note under a chart or a control.",
+ eyebrow: "Group label",
+ mono: "sess_7f3a · ~/work/penguin",
+ label: "Field label",
+ },
+ inline: { before: "Run ", code: "pnpm install", after: " to install the dependencies." },
+ prose: "Markdown prose",
+ proseSample:
+ "## Release checks\n\nConfirm **three things** before you release, then run `pnpm -r build`. See the [release notes](https://penguin.ooo).\n\n- Type checks pass\n- Every test passes\n- The changelog is written\n\n> When a data root is taken, use another one — never end someone else's process.\n\n| Check | Command |\n| --- | --- |\n| Types | `pnpm typecheck` |\n| Tests | `pnpm test` |\n\n```bash\npnpm -r build && pnpm test\n```\n\nThe cache hit rate is \\(r = h / (h + m)\\).",
+ compact: "Compact: a channel message",
+ compactSample: "Merged **#897** — `feat/ui-w2` can go.",
+ code: "Code",
+ surface: "Code surface: line numbers, no frame",
+ diff: "Diff",
+ unified: "Unified",
+ split: "Side by side",
+ patch: "From a patch",
+ diffLabel: "Changes to src/config.ts",
+ patchLabel: "Changes to src/limits.ts",
+ },
},
};
diff --git a/packages/ui-gallery/src/strings.ts b/packages/ui-gallery/src/strings.ts
index 9de9fcd5..0baf0324 100644
--- a/packages/ui-gallery/src/strings.ts
+++ b/packages/ui-gallery/src/strings.ts
@@ -9,7 +9,13 @@
* the component library's topics (src/library/topics.ts), in both dictionaries; a test checks
* each covers every id.
*/
-import type { HookName, StreamReveal, ThemeId, ToneName } from "@prismshadow/penguin-ui";
+import type {
+ HookName,
+ StreamReveal,
+ TextVariant,
+ ThemeId,
+ ToneName,
+} from "@prismshadow/penguin-ui";
import type { TextSize } from "@prismshadow/penguin-ui/boot";
import type { SurfaceGroupId, SurfaceId } from "./app/surfaces";
import type { ChartToken } from "./library/chart-tokens";
@@ -439,6 +445,10 @@ export const zh = {
},
avatars: { title: "头像", description: "用户头像与智能体头像的各个尺寸,以及头像组。" },
files: { title: "文件", description: "文件树与只读文件浏览器。" },
+ content: {
+ title: "内容",
+ description: "标题与文字角色、行内代码、Markdown 正文、代码块与代码面,以及差异视图。",
+ },
colour: {
title: "颜色",
description: "表面、文字、线条、强调色、语义色调、图表序列与代码色。",
@@ -812,6 +822,35 @@ export const zh = {
readme:
"# Docs Expert\n\n从 `corpus/` 建立 BM25 索引,回答关于 Claude Code 文档的问题。\n\n- `src/rag.ts` — 检索\n- `test/` — 用例",
},
+ content: {
+ headings: "标题",
+ headingsHint: "每一级取主题的字阶;展示标题只用于页面的一级标题。",
+ display: "页面展示标题",
+ heading: (level: number) => `${level} 级标题`,
+ text: "文字角色",
+ samples: {
+ body: "正文:消息、说明与设置项的字号。",
+ small: "小字:次要信息与元数据。",
+ caption: "说明:图表或控件下方的注释。",
+ eyebrow: "分组标签",
+ mono: "sess_7f3a · ~/work/penguin",
+ label: "字段标签",
+ } as Record<TextVariant, string>,
+ inline: { before: "先运行 ", code: "pnpm install", after: " 安装依赖。" },
+ prose: "Markdown 正文",
+ proseSample:
+ "## 部署检查\n\n发布前确认 **三件事**,再运行 `pnpm -r build`。详见[发布说明](https://penguin.ooo)。\n\n- 类型检查通过\n- 测试全部通过\n- 更新日志已写好\n\n> 数据根被占用时,换一个数据根,不要结束别人的进程。\n\n| 检查 | 命令 |\n| --- | --- |\n| 类型 | `pnpm typecheck` |\n| 测试 | `pnpm test` |\n\n```bash\npnpm -r build && pnpm test\n```\n\n缓存命中率为 \\(r = h / (h + m)\\)。",
+ compact: "紧凑:频道消息",
+ compactSample: "已合并 **#897**,`feat/ui-w2` 可以删了。",
+ code: "代码",
+ surface: "代码面:行号,无外框",
+ diff: "差异",
+ unified: "合并视图",
+ split: "并排视图",
+ patch: "读取补丁",
+ diffLabel: "src/config.ts 的改动",
+ patchLabel: "src/limits.ts 的改动",
+ },
},
};
diff --git a/packages/ui-gallery/test/library.test.ts b/packages/ui-gallery/test/library.test.ts
index 62487296..9987d5ef 100644
--- a/packages/ui-gallery/test/library.test.ts
+++ b/packages/ui-gallery/test/library.test.ts
@@ -64,6 +64,7 @@ describe("the library's topics", () => {
"charts",
"avatars",
"files",
+ "content",
]);
const foundations = TOPIC_GROUPS.find((group) => group.id === "foundations")!.topics;
expect(foundations.map((topic) => topic.id)).toEqual([
@@ -237,6 +238,50 @@ describe("the charts board", () => {
});
});
+describe("the content board", () => {
+ it("shows every content component from the package, and nothing from the app", () => {
+ const board = read("../src/library/boards/content.tsx");
+ expect(board).toMatch(/from "@prismshadow\/penguin-ui";/);
+ expect(board).not.toMatch(/web\/src/);
+ for (const component of [
+ "Heading",
+ "Text",
+ "InlineCode",
+ "Prose",
+ "CodeBlock",
+ "CodeSurface",
+ "DiffViewer",
+ ]) {
+ expect(board).toMatch(new RegExp(`<${component}[\\s/>]`));
+ }
+ // Both densities of prose, both diff layouts and a patch.
+ expect(board).toMatch(/<Prose variant="compact"/);
+ expect(board).toMatch(/mode="split"/);
+ expect(board).toMatch(/<DiffViewer patch=\{PATCH\}/);
+ });
+
+ it("highlights through the app's highlighter, handed over by the frame", () => {
+ const entry = read("../src/library/main.tsx");
+ expect(entry).toMatch(/<CodeHighlighterProvider highlight=\{highlightCode\}>/);
+ expect(entry).toMatch(/from "\.\.\/\.\.\/\.\.\/web\/src\/features\/chat\/code-highlight"/);
+ // KaTeX's sheet comes with the package's Markdown; neither frame reaches into node_modules.
+ for (const frame of ["../src/library/main.tsx", "../src/app/main.tsx"]) {
+ expect(read(frame)).not.toMatch(/katex\.min\.css/);
+ }
+ });
+
+ it("names every text role in both dictionaries", () => {
+ for (const S of [zh, en]) {
+ const t = S.library.content;
+ for (const text of Object.values(t.samples)) expect(text.trim()).not.toBe("");
+ expect(Object.keys(t.samples).sort()).toEqual(
+ ["body", "caption", "eyebrow", "label", "mono", "small"].sort(),
+ );
+ expect(t.heading(2)).toContain("2");
+ }
+ });
+});
+
describe("the streaming board", () => {
it("plays the streaming Session's answer through the app's reply body, on one seed, with a replay", () => {
const board = read("../src/library/boards/streaming.tsx");
diff --git a/packages/ui/package.json b/packages/ui/package.json
index 85d74110..f25c1a47 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -19,6 +19,7 @@
"default": "./src/fonts/index.css"
},
"./boot": "./src/boot.ts",
+ "./highlighter": "./src/components/content/code-block/highlighter-core.ts",
"./fonts-credits": "./src/fonts/credits.ts",
"./testing": "./src/testing/index.ts"
},
@@ -38,6 +39,14 @@
"@fontsource-variable/mona-sans": "^5.3.0",
"@fontsource-variable/noto-sans-sc": "^5.3.0",
"@fontsource/ibm-plex-sans-condensed": "^5.3.0",
+ "@shikijs/langs": "^4.3.1",
+ "@shikijs/themes": "^4.3.1",
+ "katex": "^0.16.47",
+ "react-markdown": "^10.1.0",
+ "rehype-katex": "^7.0.1",
+ "remark-gfm": "^4.0.0",
+ "remark-math": "^6.0.0",
+ "shiki": "^4.3.1",
"zustand": "^5.0.15"
},
"devDependencies": {
diff --git a/packages/ui/src/components/content/code-block/code-block.tsx b/packages/ui/src/components/content/code-block/code-block.tsx
new file mode 100644
index 00000000..9337c52a
--- /dev/null
+++ b/packages/ui/src/components/content/code-block/code-block.tsx
@@ -0,0 +1,232 @@
+/**
+ * Code rendering, in two layers.
+ *
+ * `CodeSurface` is the code itself: a `<pre>` highlighted by Shiki — the light colours inline and
+ * the dark ones as `--shiki-dark` variables, switched under the dark mode by prose.css, so switching
+ * the mode doesn't require re-highlighting. The surface never runs Shiki itself: it asks a
+ * {@link CodeHighlighter} — its `highlight` prop, or the one the nearest `CodeHighlighterProvider`
+ * supplies — and until that answers, and for languages it doesn't carry, it shows the code
+ * unhighlighted. The Web App supplies a worker-backed highlighter once, around its tree; the engine
+ * lives on its own subpath (highlighter-core.ts) so no static import of this module reaches Shiki.
+ * The surface carries no chrome at all, which is what lets the Files panel put its source view and
+ * its editor on the same layer and know they agree.
+ *
+ * `CodeBlock` is that surface inside a message's chrome (visual reference: better-chatbot's
+ * pre-block): a bordered box with a head carrying the language label and a copy button. It is the
+ * `ui-frame` host for code, so a theme may redraw the box. Message code blocks keep no line numbers
+ * and no wrapping — wrapping is a file viewer's answer, not a transcript's.
+ *
+ * `highlight={false}` (while a message is streaming) skips highlighting and shows plain text: every
+ * streaming frame re-renders the full code with a growing length, re-tokenizing the whole block
+ * each time would be O(n^2) work, and an in-progress highlight can't be cancelled; once streaming
+ * settles, `highlight` flips back and a single final highlight is done.
+ *
+ * The code's own look — the surface metrics, the gutter, the editor overlay — is in prose.css.
+ */
+import { createContext, useContext, useEffect, useMemo, useState } from "react";
+import type { CSSProperties, ReactElement, ReactNode } from "react";
+import { useUiStrings } from "../../../strings";
+import { CopyButton } from "../../actions/copy-button/copy-button";
+import type { CodeHighlighter } from "./highlight-options";
+import "../prose/prose.css";
+
+export type { CodeHighlighter, CodeMark, HighlightOptions } from "./highlight-options";
+
+const CodeHighlighterContext = createContext<CodeHighlighter | null>(null);
+
+/**
+ * Supplies the highlighter every code surface below it uses unless it is handed its own. Mount it
+ * once, around the app; pass a module-level function, since a new one re-highlights every block.
+ */
+export function CodeHighlighterProvider({
+ highlight,
+ children,
+}: {
+ highlight: CodeHighlighter | null;
+ children?: ReactNode;
+}): ReactElement {
+ return (
+ <CodeHighlighterContext.Provider value={highlight}>{children}</CodeHighlighterContext.Provider>
+ );
+}
+
+/** The nearest provider's highlighter, or null where none is mounted. */
+export function useCodeHighlighter(): CodeHighlighter | null {
+ return useContext(CodeHighlighterContext);
+}
+
+/**
+ * What a `highlight` prop resolves to: a function is used as given, `true` means the provider's,
+ * `false` means none.
+ */
+export function resolveHighlighter(
+ highlight: boolean | CodeHighlighter,
+ provided: CodeHighlighter | null,
+): CodeHighlighter | null {
+ if (typeof highlight === "function") return highlight;
+ return highlight ? provided : null;
+}
+
+/**
+ * The highlighted code, with no box around it.
+ *
+ * With `lineNumbers`, the lines become blocks (see highlighter-core.ts's BLOCK_LINES) so a CSS
+ * counter can draw a gutter that survives wrapping, and the unhighlighted fallback is split
+ * into the same line elements — one gutter, whichever path rendered the code, and one shape for
+ * a caller that needs to lay something else over it.
+ */
+export function CodeSurface({
+ language,
+ code,
+ highlight = true,
+ lineNumbers = false,
+ wrap = false,
+ settleMs = 0,
+ className = "",
+ children,
+}: {
+ language: string;
+ code: string;
+ /**
+ * Who highlights: `true` (the default) the nearest `CodeHighlighterProvider`'s highlighter, a
+ * function that one, `false` nobody — the code shows plain.
+ */
+ highlight?: boolean | CodeHighlighter;
+ /** Draw a line-number gutter (and, with it, put each line in a block of its own). */
+ lineNumbers?: boolean;
+ /** Soft-wrap long lines instead of scrolling sideways. */
+ wrap?: boolean;
+ /**
+ * Wait this long after the last change before highlighting. 0 (the default) highlights every
+ * change, which is right for code that is rendered once; an editor passes a delay so that
+ * typing costs nothing but a re-render. While a highlight is pending the surface shows the
+ * CURRENT text unhighlighted rather than the previous text's colours — a code layer that
+ * lags the keystrokes it sits under is worse than a colourless one.
+ */
+ settleMs?: number;
+ className?: string;
+ /** Laid over the code in the same scroll box (the Files panel's editor puts its textarea here). */
+ children?: ReactNode;
+}) {
+ const highlighter = resolveHighlighter(highlight, useCodeHighlighter());
+ const [highlighted, setHighlighted] = useState<{ code: string; html: string }>();
+
+ useEffect(() => {
+ if (highlighter === null) {
+ setHighlighted(undefined);
+ return;
+ }
+ let alive = true;
+ const run = () => {
+ // Through a resolved promise, so a highlighter that throws instead of rejecting lands in the
+ // same catch.
+ void Promise.resolve()
+ .then(() => highlighter(code, language, { blockLines: lineNumbers }))
+ .then((out) => {
+ if (alive && out !== undefined) setHighlighted({ code, html: out });
+ })
+ .catch(() => {
+ // Unknown language / failed to load: keep the unhighlighted fallback.
+ });
+ };
+ if (settleMs <= 0) {
+ run();
+ return () => {
+ alive = false;
+ };
+ }
+ const timer = window.setTimeout(run, settleMs);
+ return () => {
+ alive = false;
+ window.clearTimeout(timer);
+ };
+ }, [code, language, highlighter, lineNumbers, settleMs]);
+
+ // Split once per code change, and only where a gutter needs it: the digit count sizes the
+ // gutter, and the unhighlighted fallback renders the lines it returns.
+ const lines = useMemo(() => (lineNumbers ? code.split("\n") : null), [code, lineNumbers]);
+ // Only the current text's own highlight may be shown (see settleMs).
+ const html = highlighted?.code === code ? highlighted.html : undefined;
+ /**
+ * The `dangerouslySetInnerHTML` payload, held stable across renders that do not change the
+ * markup. React compares this prop by object identity and re-sets `innerHTML` whenever it
+ * differs, so a fresh `{ __html }` literal rebuilds every node in the block on every render
+ * of the surrounding component — discarding any selection the reader had made inside it, and
+ * re-parsing the whole highlighted body for nothing.
+ */
+ const htmlProp = useMemo(() => (html === undefined ? undefined : { __html: html }), [html]);
+
+ return (
+ <div
+ className={`code-surface ${wrap ? "code-wrap" : "code-nowrap"} ${
+ lines === null ? "" : "code-lines"
+ } ${className}`}
+ style={
+ lines === null
+ ? undefined
+ : // `ch` and not `rem`: an overlaid textarea has to indent by exactly this much, and
+ // only a character-relative unit is the same length in both layers. +2 is the
+ // clearance between the number and the code.
+ ({ "--code-gutter": `${String(lines.length).length + 2}ch` } as CSSProperties)
+ }
+ >
+ {htmlProp !== undefined ? (
+ <div dangerouslySetInnerHTML={htmlProp} />
+ ) : (
+ <pre>
+ <code>
+ {lines === null
+ ? code
+ : // No newline between the spans: they are blocks, and the text a selection
+ // serialises out of a run of blocks already carries the breaks.
+ lines.map((line, i) => (
+ <span key={i} className="line">
+ {line}
+ </span>
+ ))}
+ </code>
+ </pre>
+ )}
+ {children}
+ </div>
+ );
+}
+
+/**
+ * A fenced block in a message: the language and a copy button over the code. The frame's
+ * fill, rules and body read the `--ui-code-*` tokens; the size is the theme's code rung.
+ */
+export function CodeBlock({
+ language,
+ code,
+ highlight = true,
+ copyLabel,
+}: {
+ language: string;
+ code: string;
+ /** As on `CodeSurface`: `false` while the code is still streaming in. */
+ highlight?: boolean | CodeHighlighter;
+ /** The copy button's name and tooltip; the interface's "Copy code" when omitted. */
+ copyLabel?: string;
+}) {
+ const strings = useUiStrings();
+ return (
+ <div className="code-block ui-frame my-2 overflow-hidden rounded-lg border border-[var(--ui-code-line)]">
+ <div
+ data-slot="head"
+ className="flex items-center justify-between border-b border-[var(--ui-code-line)] bg-[var(--ui-code-bg)] px-3 py-1"
+ >
+ {/* The language is an identifier, not copy: the same in every interface language. */}
+ <span className="font-mono text-xs lowercase text-fg-muted">{language || "text"}</span>
+ {/* Always visible — the head has no hover-gated container. */}
+ <CopyButton text={code} label={copyLabel ?? strings.copyCode} />
+ </div>
+ <div
+ data-slot="body"
+ className="overflow-x-auto bg-canvas text-[length:var(--ui-text-code-size)] leading-relaxed"
+ >
+ <CodeSurface language={language} code={code} highlight={highlight} />
+ </div>
+ </div>
+ );
+}
diff --git a/packages/web/src/features/chat/code-languages.ts b/packages/ui/src/components/content/code-block/code-languages.ts
similarity index 94%
rename from packages/web/src/features/chat/code-languages.ts
rename to packages/ui/src/components/content/code-block/code-languages.ts
index b242ae03..ddd34ef9 100644
--- a/packages/web/src/features/chat/code-languages.ts
+++ b/packages/ui/src/components/content/code-block/code-languages.ts
@@ -2,12 +2,12 @@
* Which languages the code viewer can highlight, and how a fence info string or a file extension
* resolves to one. Pure lookup tables — no Shiki import, so this is safe to pull into the main
* bundle; the grammars themselves are behind the dynamic imports in LANGUAGE_LOADERS and only
- * materialize as separate chunks when highlighter.ts actually loads one.
+ * materialize as separate chunks when the engine (highlighter-core.ts) actually loads one.
*
* The list is explicit rather than "whatever Shiki bundles" because the full bundle costs an
* oniguruma WASM chunk and a 332-grammar registry on the first code block of a conversation (see
- * highlighter.ts). Adding a language means a loader entry plus, where the grammar declares aliases
- * of its own, the alias rows that route a fence info string to it.
+ * highlighter-core.ts). Adding a language means a loader entry plus, where the grammar declares
+ * aliases of its own, the alias rows that route a fence info string to it.
*
* The tables are Maps, not objects: the keys are file extensions and fence info strings, and a
* plain object would resolve `constructor` or `__proto__` through Object.prototype to a function or
diff --git a/packages/ui/src/components/content/code-block/highlight-options.ts b/packages/ui/src/components/content/code-block/highlight-options.ts
new file mode 100644
index 00000000..4f4bfb6e
--- /dev/null
+++ b/packages/ui/src/components/content/code-block/highlight-options.ts
@@ -0,0 +1,37 @@
+/**
+ * The contract between the code components and whatever highlights for them. Types only, so the
+ * engine (highlighter-core.ts), a worker's message protocol and the React components can all name
+ * it without pulling in each other.
+ */
+
+/**
+ * A character range of one line wrapped in an element of its own: `line` is 0-based, `start` and
+ * `end` are UTF-16 offsets into that line, end exclusive. The diff viewer marks changed words so.
+ */
+export interface CodeMark {
+ line: number;
+ start: number;
+ end: number;
+ className: string;
+}
+
+export interface HighlightOptions {
+ /**
+ * Emit each line as a block with no newline between them, for a surface that draws a line-number
+ * gutter or lays lines out itself.
+ */
+ blockLines?: boolean;
+ /** Ranges to wrap in their own element; they must not overlap. */
+ marks?: readonly CodeMark[];
+}
+
+/**
+ * Turns code into Shiki's dual-theme HTML, or undefined when the language is not one it carries.
+ * May reject; a caller shows the code unhighlighted either way. The Web App's is worker-backed; any
+ * function with this shape serves, and none at all leaves every surface plain.
+ */
+export type CodeHighlighter = (
+ code: string,
+ language: string,
+ options?: HighlightOptions,
+) => Promise<string | undefined>;
diff --git a/packages/web/src/features/chat/highlighter-core.ts b/packages/ui/src/components/content/code-block/highlighter-core.ts
similarity index 60%
rename from packages/web/src/features/chat/highlighter-core.ts
rename to packages/ui/src/components/content/code-block/highlighter-core.ts
index decb723d..b1199a14 100644
--- a/packages/web/src/features/chat/highlighter-core.ts
+++ b/packages/ui/src/components/content/code-block/highlighter-core.ts
@@ -1,25 +1,41 @@
/**
- * The Shiki engine itself: the core, the lazily loaded grammars, and one call that turns code
- * into dual-theme HTML. Imported by `highlighter.worker.ts` and, when a worker cannot be had, by
- * `highlighter.ts` directly — so the two paths share the engine rather than agreeing about it.
+ * The Shiki engine itself: the core, the lazily loaded grammars, and one call that turns code into
+ * dual-theme HTML. The package's code components never import it: `CodeSurface` asks a
+ * {@link CodeHighlighter} it is handed (by prop or by `CodeHighlighterProvider`), and the app
+ * decides where the engine runs — the Web App runs it on a worker and falls back to this thread.
+ * So it is published on its own subpath (`@prismshadow/penguin-ui/highlighter`), which a worker can
+ * import without React, and kept out of the root barrel, so no static import of the barrel can put
+ * a copy of Shiki in the entry chunk.
*
* Assembled from `shiki/core` with the language list in code-languages.ts instead of importing
* `shiki` (its full bundle): that entry point drags in the oniguruma WASM engine and a registry of
* all 332 bundled grammars, and both land on the *first* code block a conversation renders — 230 KB
* gzip of WASM before a single token is colored. The pure-JS regex engine replaces it for free:
* every pattern in every bundled grammar translates to a JS RegExp, and its token output is
- * byte-identical to oniguruma's. Measured on this app: ~308 KB -> ~70 KB gzip for the first block.
+ * byte-identical to oniguruma's. Measured on the Web App: ~308 KB -> ~70 KB gzip for the first
+ * block.
*
* The trade is coverage — a fence in a language not listed in code-languages.ts renders
* unhighlighted instead of highlighted, where the full bundle would have known it.
*
- * Both themes are baked into one pass as CSS variables (`--shiki-dark`, see styles.css), so
- * switching light/dark never re-highlights. Grammars load lazily and are cached per language, so a
+ * Both themes of {@link CODE_THEMES} are baked into one pass: the light colours inline, the dark
+ * ones as `--shiki-dark` variables that prose.css switches to under the dark mode, so switching
+ * light/dark never re-highlights. Grammars load lazily and are cached per language, so a
* conversation downloads only the languages it shows, once each.
*/
import { createHighlighterCore, type HighlighterCore, type LanguageInput } from "shiki/core";
import { createJavaScriptRegexEngine } from "shiki/engine/javascript";
import { LANGUAGE_LOADERS, isPlainTextLanguage, resolveLanguage } from "./code-languages";
+import type { HighlightOptions } from "./highlight-options";
+
+export type { CodeHighlighter, CodeMark, HighlightOptions } from "./highlight-options";
+
+/**
+ * The syntax palette, one Shiki theme per mode. The token contract has no syntax colours, so every
+ * app theme shares this pair; the surface around the code — its fill, rules, gutter and selection —
+ * is the theme's own, from the `--ui-code-*` tokens.
+ */
+export const CODE_THEMES = { light: "github-light", dark: "github-dark" } as const;
let corePromise: Promise<HighlighterCore> | undefined;
const grammarPromises = new Map<string, Promise<void>>();
@@ -73,20 +89,35 @@ const BLOCK_LINES = {
* Highlights `code` as `language`, returning Shiki's dual-theme HTML, or undefined when the
* language isn't one this bundle carries. Rejects only on an unexpected failure (chunk fetch,
* grammar error); callers fall back to unhighlighted text either way.
+ *
+ * `marks` wrap character ranges in an element of their own (Shiki's decorations), splitting the
+ * tokens they cross — the diff viewer's changed words. Always a new element, never a class merged
+ * onto a token or a line that a range happens to cover whole, so a line stays a bare
+ * `<span class="line">` a caller can cut the markup at. Empty ranges are dropped; the ranges must
+ * not overlap.
*/
export async function highlight(
code: string,
language: string,
- blockLines: boolean,
+ options: HighlightOptions = {},
): Promise<string | undefined> {
const id = resolveLanguage(language);
if (!id) return undefined;
const core = await getCore();
const load = isPlainTextLanguage(id) ? undefined : LANGUAGE_LOADERS.get(id);
if (load) await loadGrammar(core, id, load);
+ const decorations = (options.marks ?? [])
+ .filter((mark) => mark.end > mark.start)
+ .map((mark) => ({
+ start: { line: mark.line, character: mark.start },
+ end: { line: mark.line, character: mark.end },
+ properties: { class: mark.className },
+ alwaysWrap: true,
+ }));
return core.codeToHtml(code, {
lang: id,
- themes: { light: "github-light", dark: "github-dark" },
- ...(blockLines ? { transformers: [BLOCK_LINES] } : {}),
+ themes: CODE_THEMES,
+ ...(options.blockLines === true ? { transformers: [BLOCK_LINES] } : {}),
+ ...(decorations.length > 0 ? { decorations } : {}),
});
}
diff --git a/packages/ui/src/components/content/diff-viewer/diff-viewer.tsx b/packages/ui/src/components/content/diff-viewer/diff-viewer.tsx
new file mode 100644
index 00000000..fdc95b7e
--- /dev/null
+++ b/packages/ui/src/components/content/diff-viewer/diff-viewer.tsx
@@ -0,0 +1,245 @@
+/**
+ * A diff, unified or side by side: hunk headers, both line numbers, the removed and added lines on
+ * the theme's diff washes (`--ui-diff-*`), the words that changed within a paired line on the
+ * stronger wash, and the code highlighted like any other code surface.
+ *
+ * It takes two texts (and computes the line diff, diff.ts) or a unified patch (and draws its hunks
+ * as given). Highlighting goes through the same {@link CodeHighlighter} as `CodeSurface` — the
+ * `highlight` prop, or the nearest `CodeHighlighterProvider`'s — once per side: the old side (the
+ * context and removed lines) and the new (the context and added lines), each with its changed
+ * words marked so the highlighter wraps them between tokens. Until that answers, or with no
+ * highlighter, the lines render plain with the same word marks.
+ *
+ * A removed line's text is a `<del>` and an added line's an `<ins>`, so a screen reader announces
+ * the change and not only a colour; the `-` / `+` sign stays visible and is left out of a copy.
+ * The look is in prose.css (`.code-diff`) and the classes below.
+ */
+import { useEffect, useMemo, useState } from "react";
+import type { ReactNode } from "react";
+import { resolveHighlighter, useCodeHighlighter } from "../code-block/code-block";
+import type { CodeHighlighter } from "../code-block/highlight-options";
+import {
+ DIFF_WORD_CLASS,
+ diffTexts,
+ parsePatch,
+ splitHighlightedLines,
+ splitRows,
+ wordMarks,
+} from "./diff";
+import type { DiffLine, DiffModel, WordRange } from "./diff";
+import "../prose/prose.css";
+
+export type DiffMode = "unified" | "split";
+
+interface DiffViewerBase {
+ /** The language both sides are highlighted as; plain text by default. */
+ language?: string;
+ mode?: DiffMode;
+ /** Soft-wrap long lines instead of scrolling sideways. */
+ wrap?: boolean;
+ /** As on `CodeSurface`: `true` the provider's highlighter, a function that one, `false` none. */
+ highlight?: boolean | CodeHighlighter;
+ /** The table's accessible name ("Changes to app.ts"). */
+ label?: string;
+ className?: string;
+}
+
+export type DiffViewerProps = DiffViewerBase &
+ (
+ | {
+ before: string;
+ after: string;
+ /** Unchanged lines kept around each change; 3 by default. */
+ context?: number;
+ patch?: never;
+ }
+ | { patch: string; before?: never; after?: never; context?: never }
+ );
+
+/** The highlighted markup of each side, per line, for the model it was made from. */
+interface SideMarkup {
+ model: DiffModel;
+ oldSide: readonly { __html: string }[] | null;
+ newSide: readonly { __html: string }[] | null;
+}
+
+const ROW: Record<DiffLine["kind"], string> = {
+ context: "",
+ add: "bg-[var(--ui-diff-add-bg)]",
+ del: "bg-[var(--ui-diff-del-bg)]",
+};
+const SIGN: Record<DiffLine["kind"], string> = { context: " ", add: "+", del: "-" };
+const NUMBER_CELL =
+ "w-px select-none whitespace-nowrap px-2 text-right align-top text-[var(--ui-code-gutter)]";
+const SIGN_CELL = "w-px select-none pl-2 align-top text-fg-subtle";
+
+/** A line's text with its changed words wrapped, for the unhighlighted rendering. */
+function plainWords(text: string, words: readonly WordRange[]): ReactNode {
+ if (words.length === 0) return text;
+ const out: ReactNode[] = [];
+ let at = 0;
+ for (const [start, end] of words) {
+ if (start > at) out.push(text.slice(at, start));
+ out.push(
+ <span key={start} className={DIFF_WORD_CLASS}>
+ {text.slice(start, end)}
+ </span>,
+ );
+ at = end;
+ }
+ if (at < text.length) out.push(text.slice(at));
+ return out;
+}
+
+/** The side a line's markup is found in. */
+function sideOf(markup: SideMarkup | null, line: DiffLine) {
+ const side = line.kind === "del" ? markup?.oldSide : markup?.newSide;
+ return side?.[line.at];
+}
+
+/** One line's code: `<del>` / `<ins>` for a change, highlighted markup when there is some. */
+function LineCode({ line, markup }: { line: DiffLine; markup: SideMarkup | null }) {
+ const html = sideOf(markup, line);
+ const Tag = line.kind === "del" ? "del" : line.kind === "add" ? "ins" : "span";
+ return html === undefined ? (
+ <Tag>{plainWords(line.text, line.words)}</Tag>
+ ) : (
+ // `shiki` lets the dark palette rule reach the token spans inside.
+ <Tag className="shiki" dangerouslySetInnerHTML={html} />
+ );
+}
+
+/** A diff of two texts or a unified patch. */
+export function DiffViewer(props: DiffViewerProps) {
+ const {
+ language = "text",
+ mode = "unified",
+ wrap = false,
+ highlight = true,
+ label,
+ className = "",
+ } = props;
+ const { before, after, patch, context } = props;
+ const model = useMemo(
+ () =>
+ patch !== undefined ? parsePatch(patch) : diffTexts(before ?? "", after ?? "", context ?? 3),
+ [before, after, patch, context],
+ );
+ const highlighter = resolveHighlighter(highlight, useCodeHighlighter());
+ const [markup, setMarkup] = useState<SideMarkup | null>(null);
+
+ useEffect(() => {
+ if (highlighter === null) return;
+ let alive = true;
+ const side = (lines: readonly string[], kind: "add" | "del"): Promise<string[] | null> =>
+ lines.length === 0
+ ? Promise.resolve(null)
+ : Promise.resolve()
+ .then(() =>
+ highlighter(lines.join("\n"), language, {
+ blockLines: true,
+ marks: wordMarks(model, kind),
+ }),
+ )
+ .then((html) => (html === undefined ? null : splitHighlightedLines(html, lines.length)))
+ .catch(() => null);
+ void Promise.all([side(model.oldSide, "del"), side(model.newSide, "add")]).then(
+ ([oldLines, newLines]) => {
+ if (!alive) return;
+ // Built once per highlight, so every row keeps the same payload object across renders.
+ const payloads = (lines: string[] | null) => lines?.map((__html) => ({ __html })) ?? null;
+ setMarkup({ model, oldSide: payloads(oldLines), newSide: payloads(newLines) });
+ },
+ );
+ return () => {
+ alive = false;
+ };
+ }, [model, language, highlighter]);
+
+ // Only the current model's markup is drawn; a stale one would put old lines on new rows.
+ const current = highlighter !== null && markup?.model === model ? markup : null;
+ const code = wrap ? "whitespace-pre-wrap [overflow-wrap:anywhere]" : "whitespace-pre";
+
+ const hunkRow = (header: string, span: number) => (
+ <tr className="bg-[var(--ui-diff-hunk-bg)] text-fg-muted">
+ <td colSpan={span} className="select-none px-3 py-1">
+ {header}
+ </td>
+ </tr>
+ );
+
+ return (
+ <div
+ className={`code-diff overflow-hidden rounded-lg border border-[var(--ui-code-line)] bg-canvas ${className}`}
+ >
+ <div className="overflow-x-auto">
+ <table
+ aria-label={label}
+ className="w-full border-collapse font-mono text-[length:var(--ui-text-code-size)] leading-relaxed"
+ >
+ {model.hunks.map((hunk, h) => (
+ <tbody key={h}>
+ {hunkRow(hunk.header, mode === "split" ? 6 : 4)}
+ {mode === "split"
+ ? splitRows(hunk.lines).map((row, r) => (
+ <tr key={r}>
+ {[row.left, row.right].map((line, side) =>
+ line === null ? (
+ <td key={side} colSpan={3} className="bg-surface-muted" />
+ ) : (
+ <SplitCells
+ key={side}
+ line={line}
+ number={side === 0 ? line.oldNo : line.newNo}
+ markup={current}
+ code={code}
+ />
+ ),
+ )}
+ </tr>
+ ))
+ : hunk.lines.map((line, l) => (
+ <tr key={l} data-kind={line.kind} className={ROW[line.kind]}>
+ <td className={NUMBER_CELL}>{line.oldNo ?? ""}</td>
+ <td className={NUMBER_CELL}>{line.newNo ?? ""}</td>
+ <td className={SIGN_CELL}>{SIGN[line.kind]}</td>
+ <td className={`w-full pr-3 pl-1 ${code}`}>
+ <LineCode line={line} markup={current} />
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ ))}
+ </table>
+ </div>
+ </div>
+ );
+}
+
+/** One side of a split row: its number, sign and code, on its own wash. */
+function SplitCells({
+ line,
+ number,
+ markup,
+ code,
+}: {
+ line: DiffLine;
+ number: number | null;
+ markup: SideMarkup | null;
+ code: string;
+}) {
+ const wash = ROW[line.kind];
+ return (
+ <>
+ <td data-kind={line.kind} className={`${NUMBER_CELL} ${wash}`}>
+ {number ?? ""}
+ </td>
+ <td data-kind={line.kind} className={`${SIGN_CELL} ${wash}`}>
+ {SIGN[line.kind]}
+ </td>
+ <td data-kind={line.kind} className={`w-1/2 pr-3 pl-1 ${code} ${wash}`}>
+ <LineCode line={line} markup={markup} />
+ </td>
+ </>
+ );
+}
diff --git a/packages/ui/src/components/content/diff-viewer/diff.ts b/packages/ui/src/components/content/diff-viewer/diff.ts
new file mode 100644
index 00000000..830c54a5
--- /dev/null
+++ b/packages/ui/src/components/content/diff-viewer/diff.ts
@@ -0,0 +1,429 @@
+/**
+ * The diff viewer's model, as pure functions: a line diff of two texts (or a unified patch read as
+ * given) grouped into hunks, the changed words of each paired line, the side-by-side rows of a
+ * split view, and the per-line markup a highlighter's output splits into.
+ *
+ * The line diff is Myers' O(ND) algorithm over the lines between the common head and tail, so an
+ * edit costs time in proportion to its size, not the file's. Its trace grows with the square of
+ * the edit distance, so past {@link MAX_EDIT} changed lines the middle is shown as replaced
+ * outright — a diff that large reads as "rewritten", not line by line.
+ */
+import type { CodeMark } from "../code-block/highlight-options";
+
+export type DiffLineKind = "context" | "add" | "del";
+
+/** A character range `[start, end)` of a line, in UTF-16 offsets. */
+export type WordRange = readonly [start: number, end: number];
+
+export interface DiffLine {
+ kind: DiffLineKind;
+ text: string;
+ /** 1-based number in the old text; null for an added line. */
+ oldNo: number | null;
+ /** 1-based number in the new text; null for a removed line. */
+ newNo: number | null;
+ /**
+ * The line's index in the side it is drawn from — the old side for a removed line, the new side
+ * for an added or a context line — which is where its highlighted markup is found.
+ */
+ at: number;
+ /** The words that changed against the paired line on the other side; empty when unpaired. */
+ words: readonly WordRange[];
+}
+
+export interface DiffHunk {
+ /** The `@@ -a,b +c,d @@` line, with any section heading a patch carried after it. */
+ header: string;
+ lines: readonly DiffLine[];
+}
+
+export interface DiffModel {
+ hunks: readonly DiffHunk[];
+ /** The old side's lines in order (context and removed): what the highlighter reads for it. */
+ oldSide: readonly string[];
+ /** The new side's lines in order (context and added). */
+ newSide: readonly string[];
+}
+
+/** Changed lines past which the middle of a diff is drawn as replaced whole. */
+export const MAX_EDIT = 1000;
+
+/** The class a changed word carries, in the highlighted markup and the plain fallback alike. */
+export const DIFF_WORD_CLASS = "diff-word";
+
+/** A text's lines: CRLF read as LF, and a final newline ending the last line, not opening one. */
+export function splitLines(text: string): string[] {
+ if (text === "") return [];
+ const lines = text.replace(/\r\n?/g, "\n").split("\n");
+ if (lines[lines.length - 1] === "") lines.pop();
+ return lines;
+}
+
+type Edit = "equal" | "insert" | "delete";
+
+const run = (length: number, edit: Edit): Edit[] => Array<Edit>(length).fill(edit);
+
+/**
+ * The shortest edit script from `a` to `b`, one entry per element: `equal` consumes one of each,
+ * `delete` one of `a`, `insert` one of `b`. When the edit distance exceeds `limit`, the part
+ * between the common head and tail is `replaced` (all deleted, then all inserted) — or, without
+ * that fallback, the answer is null.
+ */
+export function editScript<T>(
+ a: readonly T[],
+ b: readonly T[],
+ limit = MAX_EDIT,
+ fallback: "replace" | "none" = "replace",
+): Edit[] | null {
+ // The common head and tail cost nothing and are most of a typical edit.
+ let head = 0;
+ while (head < a.length && head < b.length && a[head] === b[head]) head++;
+ let tail = 0;
+ while (
+ tail < a.length - head &&
+ tail < b.length - head &&
+ a[a.length - 1 - tail] === b[b.length - 1 - tail]
+ ) {
+ tail++;
+ }
+ const midA = a.slice(head, a.length - tail);
+ const midB = b.slice(head, b.length - tail);
+ const middle =
+ myers(midA, midB, limit) ??
+ (fallback === "replace"
+ ? [...run(midA.length, "delete"), ...run(midB.length, "insert")]
+ : null);
+ if (middle === null) return null;
+ return [...run(head, "equal"), ...middle, ...run(tail, "equal")];
+}
+
+function myers<T>(a: readonly T[], b: readonly T[], limit: number): Edit[] | null {
+ const n = a.length;
+ const m = b.length;
+ if (n === 0) return run(m, "insert");
+ if (m === 0) return run(n, "delete");
+ const max = Math.min(n + m, limit);
+ // v[k + offset] is the furthest x reached on diagonal k; the offset keeps negative k in range.
+ const offset = max + 1;
+ const v = new Int32Array(2 * max + 3);
+ const at = (k: number) => v[k + offset] ?? 0;
+ // Before each step, the diagonals it reads (-d-1 … d+1), so the trace grows with the square of
+ // the edit distance rather than with the distance times the input.
+ const trace: Int32Array[] = [];
+ for (let d = 0; d <= max; d++) {
+ trace.push(v.slice(offset - d - 1, offset + d + 2));
+ for (let k = -d; k <= d; k += 2) {
+ let x = k === -d || (k !== d && at(k - 1) < at(k + 1)) ? at(k + 1) : at(k - 1) + 1;
+ let y = x - k;
+ while (x < n && y < m && a[x] === b[y]) {
+ x++;
+ y++;
+ }
+ v[k + offset] = x;
+ if (x >= n && y >= m) return backtrack(trace, n, m);
+ }
+ }
+ return null;
+}
+
+function backtrack(trace: readonly Int32Array[], n: number, m: number): Edit[] {
+ const edits: Edit[] = [];
+ let x = n;
+ let y = m;
+ for (let d = trace.length - 1; d >= 0; d--) {
+ const snapshot = trace[d]!;
+ const at = (k: number) => snapshot[k + d + 1] ?? 0;
+ const k = x - y;
+ const prevK = k === -d || (k !== d && at(k - 1) < at(k + 1)) ? k + 1 : k - 1;
+ const prevX = at(prevK);
+ const prevY = prevX - prevK;
+ while (x > prevX && y > prevY) {
+ edits.push("equal");
+ x--;
+ y--;
+ }
+ if (d > 0) edits.push(x === prevX ? "insert" : "delete");
+ x = prevX;
+ y = prevY;
+ }
+ return edits.reverse();
+}
+
+/**
+ * Word tokens: one Han or kana character (CJK runs have no spaces to split on), a run of other
+ * letters, digits and underscores, a run of spaces, or one other character. Every character falls
+ * in exactly one, so the tokens concatenate back to the line.
+ */
+const WORD =
+ /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]|(?:(?![\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}])[\p{L}\p{N}_])+|\s+|[^\p{L}\p{N}_\s]/gu;
+
+/**
+ * The changed words of a removed line and the added line it is paired with, as ranges of each.
+ * Nothing is marked when too little is shared — below 40% of the longer line, a word diff marks
+ * most of the line and reads as noise, so the line's own wash says enough.
+ */
+export function changedWords(
+ before: string,
+ after: string,
+): { removed: WordRange[]; added: WordRange[] } {
+ const none = { removed: [], added: [] };
+ if (before === after) return none;
+ const a = before.match(WORD) ?? [];
+ const b = after.match(WORD) ?? [];
+ const script = editScript(a, b, 500, "none");
+ if (script === null) return none;
+ const removed: WordRange[] = [];
+ const added: WordRange[] = [];
+ let i = 0;
+ let j = 0;
+ let aAt = 0;
+ let bAt = 0;
+ let shared = 0;
+ const push = (ranges: WordRange[], start: number, end: number) => {
+ const last = ranges[ranges.length - 1];
+ // Adjacent changed words join into one range, so the highlight is one run, not a stripe.
+ if (last !== undefined && last[1] === start) ranges[ranges.length - 1] = [last[0], end];
+ else ranges.push([start, end]);
+ };
+ for (const edit of script) {
+ if (edit === "equal") {
+ const token = a[i++]!;
+ j++;
+ if (token.trim() !== "") shared += token.length;
+ aAt += token.length;
+ bAt += token.length;
+ } else if (edit === "delete") {
+ const token = a[i++]!;
+ push(removed, aAt, aAt + token.length);
+ aAt += token.length;
+ } else {
+ const token = b[j++]!;
+ push(added, bAt, bAt + token.length);
+ bAt += token.length;
+ }
+ }
+ if (shared < 0.4 * Math.max(before.trim().length, after.trim().length)) return none;
+ return { removed, added };
+}
+
+/** Pairs each run of removed lines with the run of added lines right after it, and marks their words. */
+function markWords(lines: DiffLine[]): void {
+ let i = 0;
+ while (i < lines.length) {
+ if (lines[i]!.kind !== "del") {
+ i++;
+ continue;
+ }
+ const delStart = i;
+ while (i < lines.length && lines[i]!.kind === "del") i++;
+ const addStart = i;
+ while (i < lines.length && lines[i]!.kind === "add") i++;
+ const pairs = Math.min(addStart - delStart, i - addStart);
+ for (let p = 0; p < pairs; p++) {
+ const del = lines[delStart + p]!;
+ const add = lines[addStart + p]!;
+ const words = changedWords(del.text, add.text);
+ lines[delStart + p] = { ...del, words: words.removed };
+ lines[addStart + p] = { ...add, words: words.added };
+ }
+ }
+}
+
+function hunkHeader(lines: readonly DiffLine[], oldBefore: number, newBefore: number): string {
+ const oldCount = lines.filter((l) => l.kind !== "add").length;
+ const newCount = lines.filter((l) => l.kind !== "del").length;
+ // An empty side names the line it sits after, as `diff -u` does.
+ const oldStart = oldCount === 0 ? oldBefore : oldBefore + 1;
+ const newStart = newCount === 0 ? newBefore : newBefore + 1;
+ return `@@ -${oldStart},${oldCount} +${newStart},${newCount} @@`;
+}
+
+/** The side arrays and each line's index in its side, assigned in reading order. */
+function withSides(hunks: { header: string; lines: DiffLine[] }[]): DiffModel {
+ const oldSide: string[] = [];
+ const newSide: string[] = [];
+ const out: DiffHunk[] = hunks.map((hunk) => ({
+ header: hunk.header,
+ lines: hunk.lines.map((line) => {
+ let at: number;
+ if (line.kind === "del") {
+ at = oldSide.length;
+ oldSide.push(line.text);
+ } else {
+ if (line.kind === "context") oldSide.push(line.text);
+ at = newSide.length;
+ newSide.push(line.text);
+ }
+ return { ...line, at };
+ }),
+ }));
+ return { hunks: out, oldSide, newSide };
+}
+
+/**
+ * The diff of two texts, in hunks with `context` unchanged lines around each change (two changes
+ * closer than twice that share a hunk). Identical texts have no hunks.
+ */
+export function diffTexts(before: string, after: string, context = 3): DiffModel {
+ const a = splitLines(before);
+ const b = splitLines(after);
+ const script = editScript(a, b) ?? [];
+ const all: DiffLine[] = [];
+ let i = 0;
+ let j = 0;
+ for (const edit of script) {
+ if (edit === "equal") {
+ all.push({ kind: "context", text: b[j]!, oldNo: i + 1, newNo: j + 1, at: 0, words: [] });
+ i++;
+ j++;
+ } else if (edit === "delete") {
+ all.push({ kind: "del", text: a[i]!, oldNo: i + 1, newNo: null, at: 0, words: [] });
+ i++;
+ } else {
+ all.push({ kind: "add", text: b[j]!, oldNo: null, newNo: j + 1, at: 0, words: [] });
+ j++;
+ }
+ }
+ // Group: every change keeps `context` lines either side; overlapping windows merge.
+ const hunks: { header: string; lines: DiffLine[] }[] = [];
+ let k = 0;
+ while (k < all.length) {
+ if (all[k]!.kind === "context") {
+ k++;
+ continue;
+ }
+ const start = Math.max(0, k - context);
+ let end = k;
+ for (let scan = k; scan < all.length; scan++) {
+ if (all[scan]!.kind !== "context") end = scan;
+ else if (scan - end > 2 * context) break;
+ }
+ const stop = Math.min(all.length, end + context + 1);
+ const lines = all.slice(start, stop);
+ markWords(lines);
+ let oldBefore = 0;
+ let newBefore = 0;
+ for (const line of all.slice(0, start)) {
+ if (line.kind !== "add") oldBefore++;
+ if (line.kind !== "del") newBefore++;
+ }
+ hunks.push({ header: hunkHeader(lines, oldBefore, newBefore), lines });
+ k = stop;
+ }
+ return withSides(hunks);
+}
+
+const HUNK_HEADER = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
+
+/**
+ * A unified patch read as given: its hunks, their headers verbatim, and the file headers and
+ * `\ No newline at end of file` notes around them dropped. Several files' hunks run on in order.
+ */
+export function parsePatch(patch: string): DiffModel {
+ const hunks: { header: string; lines: DiffLine[] }[] = [];
+ let current: { header: string; lines: DiffLine[] } | null = null;
+ let oldNo = 0;
+ let newNo = 0;
+ let oldLeft = 0;
+ let newLeft = 0;
+ for (const raw of patch.replace(/\r\n?/g, "\n").split("\n")) {
+ const header = HUNK_HEADER.exec(raw);
+ if (header !== null) {
+ current = { header: raw, lines: [] };
+ hunks.push(current);
+ oldNo = Number(header[1]);
+ newNo = Number(header[3]);
+ oldLeft = header[2] === undefined ? 1 : Number(header[2]);
+ newLeft = header[4] === undefined ? 1 : Number(header[4]);
+ continue;
+ }
+ // Outside a hunk, or past the lines its header counted: file headers and trailing text.
+ if (current === null || (oldLeft <= 0 && newLeft <= 0)) continue;
+ if (raw.startsWith("\\")) continue;
+ const sign = raw[0];
+ const text = raw.slice(1);
+ if (sign === "+") {
+ current.lines.push({ kind: "add", text, oldNo: null, newNo, at: 0, words: [] });
+ newNo++;
+ newLeft--;
+ } else if (sign === "-") {
+ current.lines.push({ kind: "del", text, oldNo, newNo: null, at: 0, words: [] });
+ oldNo++;
+ oldLeft--;
+ } else {
+ // A context line; an editor that strips trailing spaces leaves an empty one bare.
+ current.lines.push({ kind: "context", text, oldNo, newNo, at: 0, words: [] });
+ oldNo++;
+ newNo++;
+ oldLeft--;
+ newLeft--;
+ }
+ }
+ for (const hunk of hunks) markWords(hunk.lines);
+ return withSides(hunks);
+}
+
+/** One row of a split view: the old line on the left, the new on the right, either may be absent. */
+export interface SplitRow {
+ left: DiffLine | null;
+ right: DiffLine | null;
+}
+
+/**
+ * A hunk's rows side by side: a context line on both sides, and a run of removed lines beside the
+ * run of added lines that follows it, row for row, the shorter run padded with empty cells.
+ */
+export function splitRows(lines: readonly DiffLine[]): SplitRow[] {
+ const rows: SplitRow[] = [];
+ let i = 0;
+ while (i < lines.length) {
+ const line = lines[i]!;
+ if (line.kind === "context") {
+ rows.push({ left: line, right: line });
+ i++;
+ continue;
+ }
+ const dels: DiffLine[] = [];
+ while (i < lines.length && lines[i]!.kind === "del") dels.push(lines[i++]!);
+ const adds: DiffLine[] = [];
+ while (i < lines.length && lines[i]!.kind === "add") adds.push(lines[i++]!);
+ for (let r = 0; r < Math.max(dels.length, adds.length); r++) {
+ rows.push({ left: dels[r] ?? null, right: adds[r] ?? null });
+ }
+ }
+ return rows;
+}
+
+/**
+ * The marks a side's changed words become for the highlighter: one per word range, on the line's
+ * index in that side.
+ */
+export function wordMarks(model: DiffModel, kind: "add" | "del"): CodeMark[] {
+ return model.hunks.flatMap((hunk) =>
+ hunk.lines
+ .filter((line) => line.kind === kind)
+ .flatMap((line) =>
+ line.words.map(([start, end]) => ({
+ line: line.at,
+ start,
+ end,
+ className: DIFF_WORD_CLASS,
+ })),
+ ),
+ );
+}
+
+/**
+ * Highlighted markup cut into its lines' inner markup, or null when it does not have the shape a
+ * block-lines highlight produces (a `<code>` of `<span class="line">` elements) or the count is
+ * not `expected`.
+ */
+export function splitHighlightedLines(html: string, expected: number): string[] | null {
+ const open = html.indexOf("<code>");
+ const close = html.lastIndexOf("</code>");
+ if (open === -1 || close < open) return null;
+ const parts = html.slice(open + "<code>".length, close).split(/<span class="line(?: [^"]*)?">/);
+ if (parts.shift() !== "") return null;
+ const lines = parts.map((part) => (part.endsWith("</span>") ? part.slice(0, -7) : part));
+ return lines.length === expected ? lines : null;
+}
diff --git a/packages/web/src/lib/markdown-plugins.ts b/packages/ui/src/components/content/prose/markdown-plugins.ts
similarity index 99%
rename from packages/web/src/lib/markdown-plugins.ts
rename to packages/ui/src/components/content/prose/markdown-plugins.ts
index 7cd6cb63..cb610e62 100644
--- a/packages/web/src/lib/markdown-plugins.ts
+++ b/packages/ui/src/components/content/prose/markdown-plugins.ts
@@ -53,7 +53,7 @@ type PluginList = NonNullable<Options["remarkPlugins"]>;
* 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
+ * render as their own source in the body colour; `.katex-error` in prose.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.
diff --git a/packages/ui/src/components/content/prose/prose.css b/packages/ui/src/components/content/prose/prose.css
new file mode 100644
index 00000000..ae1a6fdf
--- /dev/null
+++ b/packages/ui/src/components/content/prose/prose.css
@@ -0,0 +1,371 @@
+/*
+ * The content stylesheet: Markdown typography (`.md-body` and its two densities), the code surface
+ * (`.code-*`, CodeSurface and CodeBlock), Shiki's dark half and KaTeX's local fixes. prose.tsx and
+ * code-block.tsx import it; a bundler emits it once.
+ *
+ * Plain CSS on purpose: no `@apply`, so it needs no Tailwind pass of its own, and every colour and
+ * length reads a token (`--ui-*`), so it follows the theme and the mode with no `.dark` rule of its
+ * own — the one exception is Shiki's dark palette, which lives in the highlighted markup itself.
+ *
+ * Every rule here is unlayered, and that is load-bearing: an unlayered declaration beats anything
+ * in a cascade layer whatever its specificity, so these margins and paddings hold against the
+ * utilities a call site adds (a `[&>*:first-child]:mt-0` on a body would be inert — hence
+ * `.md-body-flush`). The rules keep the specificities and the order they had in the Web App's
+ * stylesheet, because the code-surface rules below reset what `.md-body pre` sets at equal
+ * specificity and win by coming later.
+ */
+
+/* ---------- Minimal typography for Markdown body content (no typography plugin) ---------- */
+
+.md-body {
+ /* Long unspaced strings like attachment paths / long URLs wrap within the narrow container
+ instead of breaking the layout (especially important for mobile message streams). */
+ overflow-wrap: break-word;
+}
+.md-body :is(p, ul, ol, pre, blockquote, table) {
+ margin: 0.5rem 0;
+}
+.md-body li {
+ margin: 0.25rem 0;
+}
+.md-body p {
+ line-height: 1.7;
+}
+.md-body :is(h1, h2, h3, h4) {
+ font-weight: var(--ui-weight-strong);
+ margin: 0.75rem 0 0.5rem;
+}
+/* A body that provides its own inset — a disclosure row's expanded thinking or compaction text —
+ drops the outermost block's margin, so the gap at each end is that padding alone rather than the
+ padding plus whatever margin the first and last blocks carry. It has to be a rule here rather
+ than a `[&>*:first-child]:mt-0` utility at the call site: the utility would be inert against the
+ unlayered margins above. */
+.md-body-flush > :first-child {
+ margin-top: 0;
+}
+.md-body-flush > :last-child {
+ margin-bottom: 0;
+}
+.md-body h1 {
+ font-size: var(--ui-md-h1-size);
+}
+.md-body h2 {
+ font-size: var(--ui-md-h2-size);
+}
+.md-body h3 {
+ font-size: var(--ui-md-h3-size);
+}
+.md-body ul {
+ list-style: disc;
+ padding-left: 1.25rem;
+}
+.md-body ol {
+ list-style: decimal;
+ padding-left: 1.25rem;
+}
+/* The link colour is the theme's (the Link component's tokens); the underline is the same ink
+ thinned, so it reads as a link without striking through a line of CJK. */
+.md-body a {
+ color: var(--ui-fg-link);
+ text-decoration-line: underline;
+ text-decoration-color: color-mix(in srgb, var(--ui-fg-link) 45%, transparent);
+ text-underline-offset: 2px;
+ transition-property: color;
+ transition-duration: var(--ui-dur-fast);
+ transition-timing-function: var(--ui-ease-in-out);
+ /* `anywhere` rather than `word-break: break-all`: it only breaks a token that would otherwise
+ overflow, so long URLs wrap cleanly (filling each line) while short Latin words in mixed
+ CJK/Latin link text never split mid-word; unlike `break-word` it also counts the break
+ opportunities toward min-content sizing, so a long link can't blow out flex/table layouts. */
+ overflow-wrap: anywhere;
+}
+@media (hover: hover) {
+ .md-body a:hover {
+ color: var(--ui-fg-link-hover);
+ }
+}
+/* The same chip the InlineCode component draws. */
+.md-body code {
+ border-radius: var(--ui-radius-sm);
+ background-color: var(--ui-tone-neutral-bg);
+ padding: calc(var(--ui-space-unit) * 0.5) var(--ui-space-unit);
+ font-size: 0.85em;
+ color: var(--ui-fg);
+}
+/* Inline code in prose often holds long unbroken paths/identifiers: same rationale as the link
+ rule above (fenced blocks are excluded — .md-body pre scrolls horizontally instead). */
+.md-body :not(pre) > code {
+ overflow-wrap: anywhere;
+}
+.md-body pre {
+ overflow-x: auto;
+ border: var(--ui-border-w) solid var(--ui-code-line);
+ border-radius: var(--ui-radius-lg);
+ background-color: var(--ui-code-bg);
+ padding: calc(var(--ui-space-unit) * 3);
+ font-size: var(--ui-text-body-size);
+ line-height: var(--ui-text-body-lh);
+ /* Off-screen code blocks skip layout/paint: with several settled 200KB+ replies in the
+ transcript, their <pre> layout dominated every streaming commit (profiled ~90% native
+ layout) and froze the chat while large code streamed in. auto keeps the measured size for
+ stable scrollbar geometry; on-screen blocks render normally and stay find-in-page searchable. */
+ content-visibility: auto;
+ contain-intrinsic-size: auto 400px;
+}
+.md-body pre code {
+ background: transparent;
+ color: inherit;
+ padding: 0;
+}
+
+/* ---------- The code surface (code-block.tsx) ---------- */
+
+/* The code surface (CodeSurface) — the code itself, with no box around it. This resets the inner
+ pre's border/background/radius, overriding both .md-body pre's styles and Shiki's own inline
+ background colours (!important beats inline style); the background belongs to whatever the
+ surface was dropped into. Not scoped to .md-body: the Files panel's source view is not inside a
+ markdown container.
+
+ The metrics are stated once, for the pre AND for a textarea laid over it: the Files panel's
+ editor is a transparent-text textarea on top of this very surface, and the two only stay in
+ register while every value that decides where a glyph lands — family, size, line height,
+ letter spacing, tab size, padding, wrap mode — is the same in both. Size and line height are
+ inherited so one wrapper sets them for both layers. */
+.code-surface :is(pre, textarea) {
+ margin: 0;
+ border: 0;
+ border-radius: 0;
+ background: transparent !important;
+ /* The message code block's own padding, kept to the pixel; the Files panel's two layers only
+ need to agree. */
+ padding: 0.625rem 0.75rem;
+ font-size: inherit;
+ line-height: inherit;
+ letter-spacing: normal;
+ tab-size: 4;
+ font-family: var(--ui-font-mono);
+}
+.code-surface pre {
+ color: var(--ui-fg);
+}
+/* Wrapping is the file viewer's answer, never the message stream's: a transcript's code block
+ scrolls sideways (see CodeBlock), and only a caller that asked for `wrap` gets this. Both
+ layers need the textarea's own UA rule spelled out, because that is the one they must match. */
+.code-wrap :is(pre, textarea) {
+ white-space: pre-wrap;
+ overflow-wrap: break-word;
+}
+.code-nowrap :is(pre, textarea) {
+ white-space: pre;
+ overflow-wrap: normal;
+}
+/* Grown to its content so a horizontal scroll has something to scroll, and so the sticky gutter
+ below can travel the whole width — a sticky box cannot go past its containing block, which
+ would otherwise be only as wide as the visible strip. */
+.code-nowrap pre {
+ min-width: max-content;
+}
+
+/* Line numbers. A counter over the per-line elements both rendering paths produce — Shiki's own
+ `.line` wrappers and the same wrappers the unhighlighted fallback splits into — so the
+ highlighter needs no changes and the two paths cannot disagree.
+
+ The lines are blocks here (highlighter-core.ts strips the newlines Shiki puts between them),
+ which is what makes the gutter survive wrapping: `padding-left` reserves the gutter on every
+ visual row, and the negative `text-indent` pulls only the FIRST row back into it, so a wrapped
+ line's continuation rows line up under its own code instead of under its number. The code
+ therefore starts at exactly `--code-gutter` on every row, which is all an overlaid textarea has
+ to match — it indents by that much and needs no per-line rule of its own.
+
+ The number is generated content and `user-select: none`, so dragging across the code selects
+ the code alone; the copy affordances are unaffected either way, since they copy the string the
+ component was given and never the DOM. Its fill is the canvas the surface sits on, so code
+ scrolled under the sticky number is hidden. */
+.code-lines pre {
+ counter-reset: code-line;
+}
+.code-lines .line {
+ display: block;
+ counter-increment: code-line;
+ padding-left: var(--code-gutter, 4ch);
+ text-indent: calc(-1 * var(--code-gutter, 4ch));
+}
+.code-lines textarea {
+ padding-left: calc(0.75rem + var(--code-gutter, 4ch));
+}
+.code-lines .line::before {
+ content: counter(code-line);
+ position: sticky;
+ left: 0;
+ display: inline-block;
+ width: var(--code-gutter, 4ch);
+ padding-right: 1.25ch;
+ text-align: right;
+ text-indent: 0;
+ user-select: none;
+ -webkit-user-select: none;
+ background-color: var(--ui-canvas);
+ color: var(--ui-code-gutter);
+}
+
+/* The editor's two layers, stacked in one grid cell so the taller of them sizes the box and a
+ single scroll container moves both — no scroll syncing in JS, and so nothing to drift. The
+ textarea keeps a visible caret over transparent text and must not scroll on its own. */
+.code-editor {
+ display: grid;
+ min-height: 100%;
+}
+.code-editor > * {
+ grid-area: 1 / 1;
+}
+.code-editor textarea {
+ overflow: hidden;
+ resize: none;
+ color: transparent;
+ outline: none;
+ caret-color: var(--ui-fg);
+}
+.code-editor textarea::selection {
+ background-color: var(--ui-code-selection);
+}
+/* While an IME is composing, the candidate text lives only in the textarea's own rendering — it
+ has not reached `value` on every platform — so the layers swap: the code layer steps aside and
+ the textarea shows its own text, underline and all, until the composition commits. */
+.code-editor-host[data-composing="true"] textarea {
+ color: var(--ui-fg);
+}
+.code-editor-host[data-composing="true"] .code-editor > :not(textarea) {
+ visibility: hidden;
+}
+
+/* Shiki's dark palette. The highlighted markup carries both themes: the light colours inline, the
+ dark ones as `--shiki-dark*` variables. The dark mode swaps them in here, so a mode switch never
+ re-highlights. The mode is the `dark` class on the root (theme.css), and the swap is spelled out
+ per property because the font style, weight and decoration change with it — `light-dark()` takes
+ colours only. */
+html.dark .shiki,
+html.dark .shiki span {
+ color: var(--shiki-dark) !important;
+ font-style: var(--shiki-dark-font-style) !important;
+ font-weight: var(--shiki-dark-font-weight) !important;
+ text-decoration: var(--shiki-dark-text-decoration) !important;
+}
+
+/* ---------- Markdown blocks ---------- */
+
+.md-body blockquote {
+ border-left: var(--ui-border-w-thick) solid var(--ui-line-emphasis);
+ padding-left: calc(var(--ui-space-unit) * 3);
+ color: var(--ui-fg-muted);
+}
+.md-body table {
+ border-collapse: collapse;
+ /* A wide table scrolls horizontally inside the body instead of pushing the whole page wide. */
+ display: block;
+ overflow-x: auto;
+}
+/* `:where` keeps the cell rule at a class's weight, so a surface's own cell rule (a channel
+ bubble's deeper line) wins whichever stylesheet a bundle emits first. */
+.md-body :where(th, td) {
+ border: var(--ui-border-w) solid var(--ui-line);
+ padding: var(--ui-space-unit) calc(var(--ui-space-unit) * 2);
+ font-size: var(--ui-text-body-size);
+ line-height: var(--ui-text-body-lh);
+}
+
+/* A message that is a line in a stream (a channel message body): the same Markdown typography,
+ one size tighter. Its blocks sit closer, its headings step down towards body size, and the
+ first and last block give up their outer margins so a one-paragraph message occupies exactly
+ its row. Used together with .md-body, after it, so these win at equal specificity. */
+.md-compact :is(p, ul, ol, pre, blockquote, table) {
+ margin: 0.25rem 0;
+}
+.md-compact li {
+ margin: 0.125rem 0;
+}
+.md-compact p {
+ line-height: 1.6;
+}
+.md-compact :is(h1, h2, h3, h4) {
+ margin: 0.5rem 0 0.25rem;
+}
+.md-compact h1 {
+ font-size: 1.0625rem;
+}
+.md-compact h2 {
+ font-size: 1rem;
+}
+.md-compact h3 {
+ font-size: 0.9375rem;
+}
+.md-compact h4 {
+ font-size: 0.875rem;
+}
+.md-compact > :first-child {
+ margin-top: 0;
+}
+.md-compact > :last-child {
+ margin-bottom: 0;
+}
+
+/* ---------- KaTeX (math rendering; see 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 reading face 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(--ui-font-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-decoration-color: var(--ui-fg-subtle);
+ text-underline-offset: 3px;
+ cursor: help;
+}
+
+/* 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;
+}
+
+/* ---------- The diff viewer (diff-viewer.tsx) ---------- */
+
+/* A changed word inside a changed line: the stronger wash of its side. The row carries the light
+ wash; the word, marked by the highlighter's decoration or by the plain fallback alike, the
+ strong one. */
+.code-diff [data-kind="add"] .diff-word {
+ background-color: var(--ui-diff-add-word);
+}
+.code-diff [data-kind="del"] .diff-word {
+ background-color: var(--ui-diff-del-word);
+}
+.code-diff .diff-word {
+ border-radius: var(--ui-radius-xs);
+}
+.code-diff :is(ins, del) {
+ text-decoration: none;
+}
diff --git a/packages/ui/src/components/content/prose/prose.tsx b/packages/ui/src/components/content/prose/prose.tsx
new file mode 100644
index 00000000..e851f5e2
--- /dev/null
+++ b/packages/ui/src/components/content/prose/prose.tsx
@@ -0,0 +1,220 @@
+/**
+ * Markdown as reading text: `Md` renders a Markdown string through the shared pipeline
+ * (markdown-plugins.ts), and `Prose` is `Md` in its reading box — the `.md-body` typography in
+ * prose.css, in one of three densities.
+ *
+ * `Md` is memoized by text identity. A chat's stream model mutates items in place and only
+ * reassigns `text` when a delta arrives, so every settled message keeps the same string instance
+ * across the per-frame version bumps — the shallow prop compare then skips its entire
+ * micromark → mdast → React re-parse, and only the actively-streaming message re-renders. Without
+ * this, each animation frame during a stream re-parsed the WHOLE transcript (O(n²) over a long
+ * reply), which visibly froze the UI while large code blocks streamed in.
+ *
+ * Fenced code blocks render through CodeBlock (language chrome + copy button + highlighting).
+ * `streaming` disables highlighting while deltas are still arriving — re-tokenizing a growing
+ * block every frame is O(n²) work — and the settle re-render (new string instance,
+ * streaming=false) highlights each block exactly once. Inline code keeps the default rendering
+ * (`.md-body code` in prose.css).
+ *
+ * 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 markdown-plugins.ts for the measurements). KaTeX's own stylesheet is
+ * imported here, so a consumer never loads it on its own; the `.katex` rules in prose.css out-rank
+ * it by specificity, whichever of the two a bundle happens to emit first.
+ *
+ * Links open in a new tab unless a `ProseLinksProvider` above decides otherwise — the Web App's
+ * conversation sends a link to a Workspace file to its Files panel that way.
+ *
+ * Two optional props open the renderer to a surface with its own nodes — the channel message body,
+ * which keeps `@mentions` as chips — without a second copy of the pipeline drifting from this one.
+ * They only ever ADD to the shared stage and to the maps below; nothing a surface passes can take
+ * the shared plugins away.
+ */
+import { createContext, isValidElement, memo, useContext } from "react";
+import type { ComponentPropsWithoutRef, MouseEvent, ReactElement, ReactNode } from "react";
+import ReactMarkdown from "react-markdown";
+import type { Components, ExtraProps, Options } from "react-markdown";
+import { CodeBlock } from "../code-block/code-block";
+import { NO_REHYPE_PLUGINS, REHYPE_PLUGINS, REMARK_PLUGINS } from "./markdown-plugins";
+import "katex/dist/katex.min.css";
+import "./prose.css";
+
+/** Flatten a react-markdown code element's children to plain text (string or string array in practice). */
+function codeText(children: unknown): string {
+ if (typeof children === "string") return children;
+ if (Array.isArray(children)) return children.filter((c) => typeof c === "string").join("");
+ return "";
+}
+
+/**
+ * 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 (
+ <CodeBlock
+ language={language}
+ code={codeText(props.children).replace(/\n$/, "")}
+ highlight={!streaming}
+ />
+ );
+ }
+ return <pre>{children}</pre>;
+}
+
+/** The attributes a rendered link adds on top of its own. */
+export interface ProseLinkBehavior {
+ target?: "_blank";
+ rel?: "noreferrer";
+ onClick?: (event: MouseEvent<HTMLAnchorElement>) => void;
+}
+
+/** Decides what a link does from its href. */
+export type ProseLinkResolver = (href: string | undefined) => ProseLinkBehavior;
+
+/**
+ * A new tab with no handle back to this window (`noreferrer` implies `noopener`): every link when
+ * no resolver is provided.
+ */
+export const PROSE_NEW_TAB: ProseLinkBehavior = { target: "_blank", rel: "noreferrer" };
+
+const ProseLinksContext = createContext<ProseLinkResolver | null>(null);
+
+/**
+ * Hands the Markdown below a link resolver; `null` restores the default, a new tab for every link.
+ * A context change re-renders every link in the tree, memoized bodies included, so pass a resolver
+ * that keeps its identity while its inputs do.
+ */
+export function ProseLinksProvider({
+ resolve,
+ children,
+}: {
+ resolve: ProseLinkResolver | null;
+ children?: ReactNode;
+}): ReactElement {
+ return <ProseLinksContext.Provider value={resolve}>{children}</ProseLinksContext.Provider>;
+}
+
+/**
+ * Link adapter. With no resolver above, every link opens in a new tab (`target="_blank"` +
+ * `rel="noreferrer"`, which also implies `noopener`), unconditionally, so a click never navigates
+ * the app away. A resolver decides per href. All other anchor props react-markdown supplies
+ * (`href`, ...) are forwarded as-is — only its non-DOM `node` prop is stripped — and the behaviour
+ * sits after the spread so it always wins. A link title (`[text](url "title")`) becomes the shared
+ * tooltip's text rather than a native `title`, like every other hover hint. Long-URL wrapping is
+ * CSS (`.md-body a` in prose.css).
+ */
+function MdLink({
+ node: _node,
+ children,
+ title,
+ ...anchorProps
+}: ComponentPropsWithoutRef<"a"> & ExtraProps) {
+ const resolve = useContext(ProseLinksContext);
+ const behavior = resolve === null ? PROSE_NEW_TAB : resolve(anchorProps.href);
+ return (
+ <a {...anchorProps} data-tooltip={title} {...behavior}>
+ {children}
+ </a>
+ );
+}
+
+/**
+ * The two `components` maps, built once at module scope instead of inline per render.
+ * react-markdown uses `components.pre` as the element **type**, so a fresh arrow each render is
+ * a new type on every commit: React unmounts and remounts every code block, dropping the user's
+ * 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 same render the rehype stage
+ * flips on. The `a` adapter closes over nothing — its resolver comes from context, not from a
+ * closure — so both maps share the one `MdLink` reference.
+ */
+const STREAMING_COMPONENTS: Components = {
+ pre: (props) => <MdPre streaming>{props.children}</MdPre>,
+ a: MdLink,
+};
+const SETTLED_COMPONENTS: Components = {
+ pre: (props) => <MdPre streaming={false}>{props.children}</MdPre>,
+ a: MdLink,
+};
+
+/**
+ * The settled map, for a read-only Markdown surface that keeps the code-block chrome and swaps
+ * only the link and image adapters (the shared file browser).
+ */
+export const SETTLED_MD_COMPONENTS: Components = SETTLED_COMPONENTS;
+
+export interface MdProps {
+ text: string;
+ /** The text is still arriving: no highlighting, no KaTeX, until it settles. */
+ streaming?: boolean;
+ /**
+ * Remark plugins a surface adds to the shared stage, for a node of its own — the channel
+ * message body adds the pass that turns its `@mentions` into elements. They are appended to
+ * REMARK_PLUGINS rather than replacing it: a renderer that dropped the shared list would end
+ * bare URLs and typeset math differently from every other one, which is the drift
+ * markdown-plugins.ts exists to prevent.
+ */
+ extraPlugins?: NonNullable<Options["remarkPlugins"]>;
+ /**
+ * Element overrides merged over the two maps above, which keep `pre` and `a`. A module
+ * constant, for the same reason those are: react-markdown uses a component as the element
+ * *type*, so a fresh function per render remounts everything it renders.
+ */
+ components?: Components;
+}
+
+/** The Markdown alone, for a caller that supplies its own `.md-body` box. */
+export const Md = memo(function Md({ text, streaming = false, extraPlugins, components }: MdProps) {
+ const base = streaming ? STREAMING_COMPONENTS : SETTLED_COMPONENTS;
+ return (
+ <ReactMarkdown
+ remarkPlugins={
+ extraPlugins === undefined ? REMARK_PLUGINS : [...REMARK_PLUGINS, ...extraPlugins]
+ }
+ rehypePlugins={streaming ? NO_REHYPE_PLUGINS : REHYPE_PLUGINS}
+ components={components === undefined ? base : { ...base, ...components }}
+ >
+ {text}
+ </ReactMarkdown>
+ );
+});
+
+/**
+ * How dense the reading box is: `body` the full typography; `compact` one size tighter, for a
+ * message that is a line in a stream (a channel bubble); `flush` the full typography with the
+ * outermost block's margins dropped, for a box that brings its own inset.
+ */
+export type ProseVariant = "body" | "compact" | "flush";
+
+const VARIANT: Record<ProseVariant, string> = {
+ body: "md-body",
+ compact: "md-body md-compact",
+ flush: "md-body md-body-flush",
+};
+
+export interface ProseProps extends MdProps {
+ variant?: ProseVariant;
+ /** Size, ink and layout from the caller; the box sets the reading face and the typography. */
+ className?: string;
+}
+
+/** Markdown in its reading box. */
+export function Prose({ variant = "body", className = "", ...md }: ProseProps) {
+ return (
+ <div className={`${VARIANT[variant]} font-sans ${className}`}>
+ <Md {...md} />
+ </div>
+ );
+}
diff --git a/packages/web/src/lib/remark-autolink-boundary.ts b/packages/ui/src/components/content/prose/remark-autolink-boundary.ts
similarity index 100%
rename from packages/web/src/lib/remark-autolink-boundary.ts
rename to packages/ui/src/components/content/prose/remark-autolink-boundary.ts
diff --git a/packages/web/src/lib/remark-math-brackets.ts b/packages/ui/src/components/content/prose/remark-math-brackets.ts
similarity index 100%
rename from packages/web/src/lib/remark-math-brackets.ts
rename to packages/ui/src/components/content/prose/remark-math-brackets.ts
diff --git a/packages/web/src/lib/remark-math-dollars.ts b/packages/ui/src/components/content/prose/remark-math-dollars.ts
similarity index 96%
rename from packages/web/src/lib/remark-math-dollars.ts
rename to packages/ui/src/components/content/prose/remark-math-dollars.ts
index e2dae537..1895fb63 100644
--- a/packages/web/src/lib/remark-math-dollars.ts
+++ b/packages/ui/src/components/content/prose/remark-math-dollars.ts
@@ -11,7 +11,7 @@
* 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
+ * separate guard in prose.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
diff --git a/packages/ui/src/components/content/typography/typography.tsx b/packages/ui/src/components/content/typography/typography.tsx
new file mode 100644
index 00000000..e8a1ef96
--- /dev/null
+++ b/packages/ui/src/components/content/typography/typography.tsx
@@ -0,0 +1,126 @@
+/**
+ * The type roles as components: `Heading` on the theme's h1–h6 rungs, `Text` for the body, small,
+ * caption, eyebrow, mono and label roles, and `InlineCode` for a code span in running text.
+ *
+ * Every size, line height, weight, tracking, case and face comes from the theme's rung tokens
+ * (`--ui-h<n>-*`, `--ui-text-*`), written as utilities rather than inline styles on purpose: a
+ * theme's hook recipe (`ui-display`, `ui-eyebrow`, in the `ui-theme` layer after the utilities)
+ * must be able to restyle what the rung set, and an inline style would out-rank it. The rung is the
+ * look — a caller wanting a bigger title picks a lower level, not a size class — and a caller's
+ * `className` adds layout and ink.
+ *
+ * Two hooks ride on these: `Heading level={1} display` is the page's one display title
+ * (`ui-display`), and `Text variant="eyebrow"` is a group label (`ui-eyebrow`) — which names the
+ * items below it and never sits directly above an h1–h4 (the de-slop guard reads this component's
+ * variant for that).
+ */
+import type { HTMLAttributes, ReactNode } from "react";
+
+export type HeadingLevel = 1 | 2 | 3 | 4 | 5 | 6;
+
+/** Each level's rung, spelled whole so Tailwind finds every class in the source. */
+const RUNG: Record<HeadingLevel, string> = {
+ 1: "[font-family:var(--ui-h1-font)] [font-size:var(--ui-h1-size)] [line-height:var(--ui-h1-lh)] [font-weight:var(--ui-h1-weight)] [letter-spacing:var(--ui-h1-tracking)] [text-transform:var(--ui-h1-transform)]",
+ 2: "[font-family:var(--ui-h2-font)] [font-size:var(--ui-h2-size)] [line-height:var(--ui-h2-lh)] [font-weight:var(--ui-h2-weight)] [letter-spacing:var(--ui-h2-tracking)] [text-transform:var(--ui-h2-transform)]",
+ 3: "[font-family:var(--ui-h3-font)] [font-size:var(--ui-h3-size)] [line-height:var(--ui-h3-lh)] [font-weight:var(--ui-h3-weight)] [letter-spacing:var(--ui-h3-tracking)] [text-transform:var(--ui-h3-transform)]",
+ 4: "[font-family:var(--ui-h4-font)] [font-size:var(--ui-h4-size)] [line-height:var(--ui-h4-lh)] [font-weight:var(--ui-h4-weight)] [letter-spacing:var(--ui-h4-tracking)] [text-transform:var(--ui-h4-transform)]",
+ 5: "[font-family:var(--ui-h5-font)] [font-size:var(--ui-h5-size)] [line-height:var(--ui-h5-lh)] [font-weight:var(--ui-h5-weight)] [letter-spacing:var(--ui-h5-tracking)] [text-transform:var(--ui-h5-transform)]",
+ 6: "[font-family:var(--ui-h6-font)] [font-size:var(--ui-h6-size)] [line-height:var(--ui-h6-lh)] [font-weight:var(--ui-h6-weight)] [letter-spacing:var(--ui-h6-tracking)] [text-transform:var(--ui-h6-transform)]",
+};
+
+type HeadingTag = "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "div" | "p" | "span";
+
+export interface HeadingProps extends HTMLAttributes<HTMLElement> {
+ /** The rung, and the outline level: an `h<level>` unless `as` says otherwise. */
+ level: HeadingLevel;
+ /**
+ * The element to render. A non-heading element keeps the outline level through
+ * `role="heading"` and `aria-level`.
+ */
+ as?: HeadingTag;
+ /** The page's one display title (the `ui-display` hook); honoured on level 1 only. */
+ display?: boolean;
+ children?: ReactNode;
+}
+
+/** A heading on the theme's rung for its level. */
+export function Heading({
+ level,
+ as,
+ display = false,
+ className = "",
+ children,
+ ...rest
+}: HeadingProps) {
+ const Tag = as ?? (`h${level}` as const);
+ const outline = /^h[1-6]$/.test(Tag) ? {} : { role: "heading", "aria-level": level };
+ return (
+ <Tag
+ {...outline}
+ {...rest}
+ className={`${display && level === 1 ? "ui-display " : ""}${RUNG[level]} ${className}`}
+ >
+ {children}
+ </Tag>
+ );
+}
+
+export type TextVariant = "body" | "small" | "caption" | "eyebrow" | "mono" | "label";
+
+/**
+ * - `body` — the body rung, in the ink around it.
+ * - `small` — the small rung, in the ink around it.
+ * - `caption` — the caption rung in the muted ink: a note under a figure or a control.
+ * - `eyebrow` — a group label on the h6 rung (`ui-eyebrow`), in the subtle ink.
+ * - `mono` — the data face at the mono tracking, for ids, paths and commands; the size is the
+ * surrounding text's.
+ * - `label` — a field's label: the small rung, semibold, muted, as `FieldLabel` draws it.
+ */
+const VARIANT: Record<Exclude<TextVariant, "eyebrow">, string> = {
+ body: "text-sm",
+ small: "text-xs",
+ caption:
+ "[font-size:var(--ui-text-caption-size)] [line-height:var(--ui-text-caption-lh)] text-fg-muted",
+ mono: "font-mono [letter-spacing:var(--ui-tracking-mono)]",
+ label: "text-xs font-semibold text-fg-muted",
+};
+
+type TextTag = "p" | "span" | "div" | "label" | "dt" | "dd" | "figcaption";
+
+export interface TextProps extends HTMLAttributes<HTMLElement> {
+ variant?: TextVariant;
+ /** The element to render: a `span` for `mono` and `label`, a `p` for the rest, by default. */
+ as?: TextTag;
+ children?: ReactNode;
+}
+
+/** Running text in one of the type roles. */
+export function Text({ variant = "body", as, className = "", children, ...rest }: TextProps) {
+ const Tag = as ?? (variant === "mono" || variant === "label" ? "span" : "p");
+ const look = variant === "eyebrow" ? "ui-eyebrow text-fg-subtle" : VARIANT[variant];
+ return (
+ <Tag {...rest} className={`${look} ${className}`}>
+ {children}
+ </Tag>
+ );
+}
+
+/**
+ * A code span in running text: the data face on a neutral chip, at 0.85em of the text around it —
+ * the same chip `.md-body code` draws in Markdown. Long identifiers and paths break anywhere
+ * rather than widen their line.
+ */
+export function InlineCode({
+ className = "",
+ children,
+ ...rest
+}: HTMLAttributes<HTMLElement> & { children?: ReactNode }) {
+ return (
+ <code
+ {...rest}
+ className={`rounded-sm bg-tone-neutral-bg px-1 py-0.5 font-mono text-[0.85em] text-fg [overflow-wrap:anywhere] ${className}`}
+ >
+ {children}
+ </code>
+ );
+}
diff --git a/packages/ui/src/hooks.ts b/packages/ui/src/hooks.ts
index 5fac3954..80d4149a 100644
--- a/packages/ui/src/hooks.ts
+++ b/packages/ui/src/hooks.ts
@@ -17,7 +17,8 @@
* | `ui-glass` | a transient layer over content: menus, popovers, the | — |
* | | modal card, the floating composer, a sticky page header | |
* | `ui-eyebrow` | a group label naming the items below it (never directly | — |
- * | | above an `h1`–`h4`) | |
+ * | | above an `h1`–`h4`); hosts: `Text variant="eyebrow"`, | |
+ * | | the sidebar's and group headers' labels | |
* | `ui-display` | the one display title of a page or hero | only on an `h1` or `[aria-level="1"]` |
* | `ui-live` | motion for something that is running right now | `data-live="dot" \| "caret" \| "spinner"` |
* | | hosts: the Spinner, a pulsing Dot | |
diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts
index 3c8079a9..727fb72f 100644
--- a/packages/ui/src/index.ts
+++ b/packages/ui/src/index.ts
@@ -97,3 +97,13 @@ export * from "./motion/use-reduced-motion";
// (with the `toast*` functions and their store).
export * from "./components/feedback/notice/notice-strip";
export * from "./components/overlays/toaster/toaster";
+
+// W5 — content: Markdown as reading text and its pipeline, the code surface and block with the
+// language tables, the type roles, and the diff viewer. The Shiki engine is not here: it is the
+// `./highlighter` subpath, so no static import of this barrel reaches it.
+export * from "./components/content/prose/prose";
+export * from "./components/content/prose/markdown-plugins";
+export * from "./components/content/code-block/code-block";
+export * from "./components/content/code-block/code-languages";
+export * from "./components/content/typography/typography";
+export * from "./components/content/diff-viewer/diff-viewer";
diff --git a/packages/ui/src/strings.ts b/packages/ui/src/strings.ts
index 01fed6a9..3a969cf1 100644
--- a/packages/ui/src/strings.ts
+++ b/packages/ui/src/strings.ts
@@ -37,6 +37,8 @@ export interface UiStrings {
notifications: string;
/** What pressing a toast does, read after its text: it dismisses it (`Toaster`). */
dismiss: string;
+ /** The name and tooltip of a code block's copy button (`CodeBlock`). */
+ copyCode: string;
}
/** The English fallbacks, used wherever no provider is mounted (a test, a stand-alone page). */
@@ -51,6 +53,7 @@ export const DEFAULT_UI_STRINGS: UiStrings = {
moreInfoAbout: (subject) => `More info: ${subject}`,
notifications: "Notifications",
dismiss: "Dismiss",
+ copyCode: "Copy code",
};
const UiStringsContext = createContext<UiStrings>(DEFAULT_UI_STRINGS);
diff --git a/packages/ui/test/code-block.test.ts b/packages/ui/test/code-block.test.ts
new file mode 100644
index 00000000..30ca714a
--- /dev/null
+++ b/packages/ui/test/code-block.test.ts
@@ -0,0 +1,168 @@
+/**
+ * CodeBlock and CodeSurface: the framed block's anatomy and tokens, the surface's plain rendering
+ * and gutter, who highlights (the prop, the provider, or nobody), the language tables, and the
+ * boundary that keeps the Shiki engine off every static import of the package.
+ */
+import { readdirSync, readFileSync, statSync } from "node:fs";
+import { join, relative } from "node:path";
+import { createElement } from "react";
+import { describe, expect, it } from "vitest";
+import {
+ CodeBlock,
+ CodeHighlighterProvider,
+ CodeSurface,
+ resolveHighlighter,
+ useCodeHighlighter,
+} from "../src/components/content/code-block/code-block";
+import type { CodeHighlighter } from "../src/components/content/code-block/code-block";
+import {
+ LANGUAGE_ALIASES,
+ LANGUAGE_LOADERS,
+ PLAIN_TEXT_LANGUAGE,
+ languageForExtension,
+ resolveLanguage,
+} from "../src/components/content/code-block/code-languages";
+import { DEFAULT_UI_STRINGS, UiStringsProvider } from "../src/strings";
+import { classTokens, renderStatic } from "../src/testing";
+import { PACKAGE_DIR, SRC_DIR } from "./helpers/paths";
+
+const highlighter: CodeHighlighter = async () => "<pre></pre>";
+
+describe("CodeBlock", () => {
+ const html = renderStatic(createElement(CodeBlock, { language: "ts", code: "const a = 1;" }));
+
+ it("is a ruled frame with a head and a body, for a theme's ui-frame recipe", () => {
+ expect(html).toMatch(/^<div class="code-block ui-frame /);
+ expect(html).toContain('<div data-slot="head"');
+ expect(html).toContain('<div data-slot="body"');
+ });
+
+ it("paints its box, head and body from the code tokens and sets the code rung", () => {
+ expect(classTokens(html)).toEqual(
+ expect.arrayContaining([
+ "border-[var(--ui-code-line)]",
+ "bg-[var(--ui-code-bg)]",
+ "bg-canvas",
+ "text-[length:var(--ui-text-code-size)]",
+ "text-fg-muted",
+ ]),
+ );
+ expect(classTokens(html).filter((token) => /gray|dark:|white/.test(token))).toEqual([]);
+ });
+
+ it("labels the language as given, plain text when the fence named none", () => {
+ expect(html).toMatch(/>ts<\/span>/);
+ const bare = renderStatic(createElement(CodeBlock, { language: "", code: "x" }));
+ expect(bare).toMatch(/>text<\/span>/);
+ });
+
+ it("names its copy button in the interface's words, or the caller's", () => {
+ expect(html).toContain(`aria-label="${DEFAULT_UI_STRINGS.copyCode}"`);
+ const zh = renderStatic(
+ createElement(UiStringsProvider, {
+ strings: { ...DEFAULT_UI_STRINGS, copyCode: "复制代码" },
+ children: createElement(CodeBlock, { language: "ts", code: "x" }),
+ }),
+ );
+ expect(zh).toContain('aria-label="复制代码"');
+ const own = renderStatic(
+ createElement(CodeBlock, { language: "ts", code: "x", copyLabel: "Copy snippet" }),
+ );
+ expect(own).toContain('aria-label="Copy snippet"');
+ });
+});
+
+describe("CodeSurface", () => {
+ it("renders the code plain until a highlighter answers", () => {
+ const html = renderStatic(createElement(CodeSurface, { language: "ts", code: "a < b" }));
+ expect(html).toMatch(/^<div class="code-surface code-nowrap /);
+ expect(html).toContain("<pre><code>a &lt; b</code></pre>");
+ });
+
+ it("splits the lines into blocks and sizes the gutter by the digit count", () => {
+ const code = Array.from({ length: 12 }, (_, i) => `line ${i}`).join("\n");
+ const html = renderStatic(
+ createElement(CodeSurface, { language: "text", code, lineNumbers: true, wrap: true }),
+ );
+ expect(html).toContain("code-wrap");
+ expect(html).toContain("code-lines");
+ expect(html).toContain("--code-gutter:4ch");
+ expect(html.match(/<span class="line">/g)).toHaveLength(12);
+ });
+});
+
+describe("who highlights", () => {
+ it("is the prop's function, else the provider's, else nobody", () => {
+ const other: CodeHighlighter = async () => undefined;
+ expect(resolveHighlighter(other, highlighter)).toBe(other);
+ expect(resolveHighlighter(true, highlighter)).toBe(highlighter);
+ expect(resolveHighlighter(true, null)).toBeNull();
+ expect(resolveHighlighter(false, highlighter)).toBeNull();
+ });
+
+ it("is read from the nearest provider", () => {
+ let seen: CodeHighlighter | null | undefined;
+ function Probe() {
+ seen = useCodeHighlighter();
+ return null;
+ }
+ renderStatic(createElement(Probe));
+ expect(seen).toBeNull();
+ renderStatic(
+ createElement(CodeHighlighterProvider, {
+ highlight: highlighter,
+ children: createElement(Probe),
+ }),
+ );
+ expect(seen).toBe(highlighter);
+ });
+});
+
+describe("the language tables", () => {
+ it("route fence names and extensions to a grammar, and unknown ones to plain text or nothing", () => {
+ expect(resolveLanguage("ts")).toBe("typescript");
+ expect(resolveLanguage(" Bash ")).toBe("shellscript");
+ expect(resolveLanguage("")).toBe(PLAIN_TEXT_LANGUAGE);
+ expect(resolveLanguage("cobol")).toBeUndefined();
+ expect(languageForExtension("TSX")).toBe("tsx");
+ expect(languageForExtension("unknown")).toBe(PLAIN_TEXT_LANGUAGE);
+ });
+
+ it("never resolve a prototype key", () => {
+ expect(resolveLanguage("constructor")).toBeUndefined();
+ expect(languageForExtension("__proto__")).toBe(PLAIN_TEXT_LANGUAGE);
+ });
+
+ it("alias only languages there is a grammar for", () => {
+ for (const [alias, id] of LANGUAGE_ALIASES) expect(LANGUAGE_LOADERS.has(id), alias).toBe(true);
+ });
+});
+
+describe("the engine boundary", () => {
+ const files = (dir: string): string[] =>
+ readdirSync(dir).flatMap((name) => {
+ const path = join(dir, name);
+ return statSync(path).isDirectory() ? files(path) : /\.tsx?$/.test(name) ? [path] : [];
+ });
+
+ it("is imported by no module of the package, and not from the barrel", () => {
+ const importers = files(SRC_DIR)
+ .filter((path) => /from "[^"]*highlighter-core"/.test(readFileSync(path, "utf8")))
+ .map((path) => relative(SRC_DIR, path).split("\\").join("/"));
+ expect(importers).toEqual([]);
+ });
+
+ it("is published on its own subpath, for a worker to import without React", () => {
+ const manifest = JSON.parse(readFileSync(join(PACKAGE_DIR, "package.json"), "utf8")) as {
+ exports: Record<string, unknown>;
+ };
+ expect(manifest.exports["./highlighter"]).toBe(
+ "./src/components/content/code-block/highlighter-core.ts",
+ );
+ const engine = readFileSync(
+ join(SRC_DIR, "components/content/code-block/highlighter-core.ts"),
+ "utf8",
+ );
+ expect(engine).not.toMatch(/from "react"/);
+ });
+});
diff --git a/packages/ui/test/diff-viewer.test.ts b/packages/ui/test/diff-viewer.test.ts
new file mode 100644
index 00000000..2a7c716d
--- /dev/null
+++ b/packages/ui/test/diff-viewer.test.ts
@@ -0,0 +1,288 @@
+/**
+ * DiffViewer and its model (diff.ts): the line diff is a shortest edit script, changes group into
+ * hunks with their context and `diff -u` headers, paired lines mark the words that changed, a patch
+ * is read as given, the split view pairs removed with added lines, and highlighted markup cuts into
+ * lines. The component is rendered once, unhighlighted — the highlight lands in an effect, which
+ * static markup never runs.
+ */
+import { createElement } from "react";
+import { describe, expect, it } from "vitest";
+import {
+ DIFF_WORD_CLASS,
+ MAX_EDIT,
+ changedWords,
+ diffTexts,
+ editScript,
+ parsePatch,
+ splitHighlightedLines,
+ splitLines,
+ splitRows,
+ wordMarks,
+} from "../src/components/content/diff-viewer/diff";
+import { DiffViewer } from "../src/components/content/diff-viewer/diff-viewer";
+import { classTokens, renderStatic } from "../src/testing";
+
+/** The longest common subsequence's length, by the textbook table: what a shortest script keeps. */
+function lcs(a: readonly string[], b: readonly string[]): number {
+ const row = new Array<number>(b.length + 1).fill(0);
+ for (const x of a) {
+ let diagonal = 0;
+ for (let j = 1; j <= b.length; j++) {
+ const up = row[j]!;
+ row[j] = x === b[j - 1] ? diagonal + 1 : Math.max(up, row[j - 1]!);
+ diagonal = up;
+ }
+ }
+ return row[b.length]!;
+}
+
+/** A deterministic sequence over a small alphabet, so the pairs share a lot and differ a lot. */
+function sequence(seed: number, length: number): string[] {
+ let state = seed;
+ return Array.from({ length }, () => {
+ state = (state * 1103515245 + 12345) % 2147483648;
+ return "abcde"[state % 5]!;
+ });
+}
+
+describe("the edit script", () => {
+ it("rebuilds the new sequence from the old one, keeping a longest common subsequence", () => {
+ for (let seed = 1; seed <= 40; seed++) {
+ const a = sequence(seed, seed % 13);
+ const b = sequence(seed * 7 + 3, (seed * 5) % 11);
+ const script = editScript(a, b)!;
+ const rebuilt: string[] = [];
+ let i = 0;
+ let j = 0;
+ for (const edit of script) {
+ if (edit === "equal") {
+ expect(a[i]).toBe(b[j]);
+ rebuilt.push(a[i++]!);
+ j++;
+ } else if (edit === "delete") i++;
+ else rebuilt.push(b[j++]!);
+ }
+ expect(rebuilt, `seed ${seed}`).toEqual(b);
+ expect(i).toBe(a.length);
+ expect(script.filter((edit) => edit === "equal").length, `seed ${seed}`).toBe(lcs(a, b));
+ }
+ });
+
+ it("replaces the middle outright past the limit, or gives up when asked to", () => {
+ const a = ["head", "x", "y", "tail"];
+ const b = ["head", "p", "q", "tail"];
+ expect(editScript(a, b, 1)).toEqual(["equal", "delete", "delete", "insert", "insert", "equal"]);
+ expect(editScript(a, b, 1, "none")).toBeNull();
+ expect(MAX_EDIT).toBeGreaterThan(0);
+ });
+});
+
+describe("the line diff", () => {
+ it("reads lines as a text editor does", () => {
+ expect(splitLines("")).toEqual([]);
+ expect(splitLines("a\r\nb\n")).toEqual(["a", "b"]);
+ expect(splitLines("a\n\n")).toEqual(["a", ""]);
+ });
+
+ it("groups a change with its context under a diff -u header", () => {
+ const before = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"].join("\n");
+ const after = ["1", "2", "3", "4", "five", "6", "7", "8", "9", "10"].join("\n");
+ const { hunks } = diffTexts(before, after, 2);
+ expect(hunks).toHaveLength(1);
+ expect(hunks[0]!.header).toBe("@@ -3,5 +3,5 @@");
+ expect(hunks[0]!.lines.map((line) => `${line.kind}:${line.text}`)).toEqual([
+ "context:3",
+ "context:4",
+ "del:5",
+ "add:five",
+ "context:6",
+ "context:7",
+ ]);
+ const del = hunks[0]!.lines[2]!;
+ expect([del.oldNo, del.newNo]).toEqual([5, null]);
+ });
+
+ it("merges changes closer than twice the context, and splits farther ones", () => {
+ const lines = Array.from({ length: 30 }, (_, i) => `line ${i + 1}`);
+ const near = [...lines];
+ near[4] = "changed";
+ near[9] = "changed";
+ expect(diffTexts(lines.join("\n"), near.join("\n"), 3).hunks).toHaveLength(1);
+ const far = [...lines];
+ far[2] = "changed";
+ far[25] = "changed";
+ const { hunks } = diffTexts(lines.join("\n"), far.join("\n"), 3);
+ expect(hunks.map((hunk) => hunk.header)).toEqual(["@@ -1,6 +1,6 @@", "@@ -23,7 +23,7 @@"]);
+ });
+
+ it("has no hunks for identical texts, and names the line an insertion follows", () => {
+ expect(diffTexts("a\nb", "a\nb").hunks).toEqual([]);
+ expect(diffTexts("", "new\n").hunks[0]!.header).toBe("@@ -0,0 +1,1 @@");
+ });
+
+ it("lays the sides out for the highlighter, each line pointing at its own", () => {
+ const model = diffTexts("a\nb\nc", "a\nx\nc");
+ expect(model.oldSide).toEqual(["a", "b", "c"]);
+ expect(model.newSide).toEqual(["a", "x", "c"]);
+ const at = model.hunks[0]!.lines.map((line) => `${line.kind}@${line.at}`);
+ expect(at).toEqual(["context@0", "del@1", "add@1", "context@2"]);
+ });
+});
+
+describe("changed words", () => {
+ it("marks what changed within a paired line", () => {
+ const { removed, added } = changedWords(
+ "const total = price * count;",
+ "const total = price * quantity;",
+ );
+ expect(removed).toEqual([[22, 27]]);
+ expect(added).toEqual([[22, 30]]);
+ });
+
+ it("splits CJK by character, since it has no spaces to split on", () => {
+ const { removed, added } = changedWords("保存文件后关闭窗口", "保存文件后打开窗口");
+ expect(removed).toEqual([[5, 7]]);
+ expect(added).toEqual([[5, 7]]);
+ });
+
+ it("marks nothing when the lines share too little to be read as an edit", () => {
+ expect(changedWords("alpha beta", "gamma delta")).toEqual({ removed: [], added: [] });
+ });
+
+ it("feeds the highlighter one mark per range, on the line's index in its side", () => {
+ const model = diffTexts("x = 1;\nkeep\n", "x = 2;\nkeep\n");
+ expect(wordMarks(model, "del")).toEqual([
+ { line: 0, start: 4, end: 5, className: DIFF_WORD_CLASS },
+ ]);
+ expect(wordMarks(model, "add")).toEqual([
+ { line: 0, start: 4, end: 5, className: DIFF_WORD_CLASS },
+ ]);
+ });
+});
+
+describe("a patch", () => {
+ const PATCH = [
+ "diff --git a/src/limits.ts b/src/limits.ts",
+ "--- a/src/limits.ts",
+ "+++ b/src/limits.ts",
+ "@@ -1,4 +1,5 @@ export const LIMITS",
+ " export const LIMITS = {",
+ "- uploadMb: 10,",
+ "+ uploadMb: 14,",
+ "+ previewKb: 256,",
+ " retries: 3,",
+ " };",
+ "\\ No newline at end of file",
+ "",
+ ].join("\n");
+
+ it("is read hunk by hunk, its header verbatim and its file headers dropped", () => {
+ const { hunks, oldSide, newSide } = parsePatch(PATCH);
+ expect(hunks).toHaveLength(1);
+ expect(hunks[0]!.header).toBe("@@ -1,4 +1,5 @@ export const LIMITS");
+ expect(hunks[0]!.lines.map((line) => [line.kind, line.oldNo, line.newNo])).toEqual([
+ ["context", 1, 1],
+ ["del", 2, null],
+ ["add", null, 2],
+ ["add", null, 3],
+ ["context", 3, 4],
+ ["context", 4, 5],
+ ]);
+ expect(oldSide).toHaveLength(4);
+ expect(newSide).toHaveLength(5);
+ expect(hunks[0]!.lines[1]!.words).toEqual([[12, 14]]);
+ });
+
+ it("pairs removed and added runs side by side, the shorter padded", () => {
+ const rows = splitRows(parsePatch(PATCH).hunks[0]!.lines);
+ expect(rows.map((row) => [row.left?.kind ?? null, row.right?.kind ?? null])).toEqual([
+ ["context", "context"],
+ ["del", "add"],
+ [null, "add"],
+ ["context", "context"],
+ ["context", "context"],
+ ]);
+ });
+});
+
+describe("highlighted markup", () => {
+ it("cuts into its lines' inner markup, decorations and all", () => {
+ const html =
+ '<pre class="shiki" tabindex="0"><code><span class="line"><span style="color:#d73a49">const</span></span>' +
+ '<span class="line"><span class="diff-word"><span style="color:#005cc5">x</span></span></span>' +
+ '<span class="line"></span></code></pre>';
+ expect(splitHighlightedLines(html, 3)).toEqual([
+ '<span style="color:#d73a49">const</span>',
+ '<span class="diff-word"><span style="color:#005cc5">x</span></span>',
+ "",
+ ]);
+ });
+
+ it("is refused when the line count is not the side's", () => {
+ expect(
+ splitHighlightedLines('<pre><code><span class="line">a</span></code></pre>', 2),
+ ).toBeNull();
+ expect(splitHighlightedLines("<pre>no code</pre>", 1)).toBeNull();
+ });
+});
+
+describe("DiffViewer", () => {
+ const BEFORE = "const total = price * count;\nreturn total;\n";
+ const AFTER = "const total = price * quantity;\nreturn total;\n";
+
+ it("draws a unified diff: header row, both numbers, signs, and <del> / <ins> lines", () => {
+ const html = renderStatic(
+ createElement(DiffViewer, { before: BEFORE, after: AFTER, label: "Changes to cart.ts" }),
+ );
+ expect(html).toContain('aria-label="Changes to cart.ts"');
+ expect(html).toMatch(/<td colSpan="4"[^>]*>@@ -1,2 \+1,2 @@<\/td>/i);
+ expect(html).toContain(
+ `<del>const total = price * <span class="${DIFF_WORD_CLASS}">count</span>;</del>`,
+ );
+ expect(html).toContain(
+ `<ins>const total = price * <span class="${DIFF_WORD_CLASS}">quantity</span>;</ins>`,
+ );
+ expect(html).toMatch(/<tr data-kind="del" class="bg-\[var\(--ui-diff-del-bg\)\]">/);
+ expect(html).toMatch(/<tr data-kind="add" class="bg-\[var\(--ui-diff-add-bg\)\]">/);
+ expect(html).toMatch(/<tr data-kind="context"/);
+ });
+
+ it("draws the sides next to each other in split mode", () => {
+ const html = renderStatic(
+ createElement(DiffViewer, { before: "a\nb\n", after: "a\nb\nc\n", mode: "split" }),
+ );
+ expect(html).toMatch(/<td colSpan="6"/i);
+ // The added line has no old counterpart: its left half is one empty cell.
+ expect(html).toMatch(/<td colSpan="3" class="bg-surface-muted"><\/td>/i);
+ expect(html).toContain("<ins>c</ins>");
+ });
+
+ it("reads a patch as given", () => {
+ const html = renderStatic(
+ createElement(DiffViewer, {
+ patch: "@@ -1 +1 @@\n-old\n+new\n",
+ language: "text",
+ }),
+ );
+ expect(html).toContain("@@ -1 +1 @@");
+ expect(html).toContain("<del>old</del>");
+ expect(html).toContain("<ins>new</ins>");
+ });
+
+ it("paints from the diff and code tokens alone", () => {
+ const tokens = classTokens(
+ renderStatic(createElement(DiffViewer, { before: BEFORE, after: AFTER, mode: "split" })),
+ );
+ expect(tokens).toEqual(
+ expect.arrayContaining([
+ "code-diff",
+ "border-[var(--ui-code-line)]",
+ "bg-[var(--ui-diff-hunk-bg)]",
+ "bg-[var(--ui-diff-add-bg)]",
+ "bg-[var(--ui-diff-del-bg)]",
+ "text-[var(--ui-code-gutter)]",
+ ]),
+ );
+ expect(tokens.filter((token) => /gray|dark:|white(?!space)/.test(token))).toEqual([]);
+ });
+});
diff --git a/packages/ui/test/hooks.test.ts b/packages/ui/test/hooks.test.ts
index 6624d924..465e8262 100644
--- a/packages/ui/test/hooks.test.ts
+++ b/packages/ui/test/hooks.test.ts
@@ -92,8 +92,10 @@ const HOSTS: Readonly<Record<string, readonly string[]>> = {
"TooltipLayer",
"TooltipPanel",
],
- "ui-eyebrow": ["Sidebar", "GroupHeader", "PagedDialog"],
+ // `Text` carries it for its eyebrow role (W5), the one door a group label takes in new code.
+ "ui-eyebrow": ["Sidebar", "GroupHeader", "PagedDialog", "Text"],
"ui-display": [
+ "Heading",
"EmptyState",
"AgentsPage",
"ModelsPage",
diff --git a/packages/ui/test/prose-math.test.ts b/packages/ui/test/prose-math.test.ts
new file mode 100644
index 00000000..3f1e7f4e
--- /dev/null
+++ b/packages/ui/test/prose-math.test.ts
@@ -0,0 +1,317 @@
+/**
+ * Math rendering across the shared Markdown pipeline (src/components/content/prose/
+ * 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 what `Md` holds back while a reply
+ * streams. That every renderer in the app shares the one plugin list is the Web App's own guard
+ * (packages/web/test/markdown-math.test.ts).
+ */
+import { describe, expect, it } from "vitest";
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import ReactMarkdown from "react-markdown";
+import { REHYPE_PLUGINS, REMARK_PLUGINS } from "../src/components/content/prose/markdown-plugins";
+import { Md } from "../src/components/content/prose/prose";
+
+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 prose.css points that class at the reading face. 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("Md, the renderer every Markdown surface shares", () => {
+ 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
+ // 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);
+ });
+});
diff --git a/packages/ui/test/prose.test.ts b/packages/ui/test/prose.test.ts
new file mode 100644
index 00000000..510b731c
--- /dev/null
+++ b/packages/ui/test/prose.test.ts
@@ -0,0 +1,150 @@
+/**
+ * Prose and Md: Markdown in its reading box, the three densities, the link default and the
+ * resolver that overrides it, fenced code routed into CodeBlock, and the stylesheet the box reads.
+ * How the pipeline typesets math is prose-math.test.ts; where a bare URL ends is
+ * remark-autolink-boundary.test.ts.
+ */
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { createElement } from "react";
+import { describe, expect, it } from "vitest";
+import {
+ Md,
+ PROSE_NEW_TAB,
+ Prose,
+ ProseLinksProvider,
+ SETTLED_MD_COMPONENTS,
+} from "../src/components/content/prose/prose";
+import type { ProseLinkResolver } from "../src/components/content/prose/prose";
+import { DEFAULT_UI_STRINGS, UiStringsProvider } from "../src/strings";
+import { classTokens, renderStatic } from "../src/testing";
+import { SRC_DIR } from "./helpers/paths";
+
+const PROSE = join(SRC_DIR, "components/content/prose");
+const read = (name: string) => readFileSync(join(PROSE, name), "utf8");
+
+/** All rendered <a ...> opening tags. */
+const anchors = (html: string) => html.match(/<a\b[^>]*>/g) ?? [];
+
+describe("Prose", () => {
+ it("wraps the Markdown in the reading box, in the reading face, with the caller's ink", () => {
+ const html = renderStatic(
+ createElement(Prose, { text: "Hello **world**", className: "text-base text-fg" }),
+ );
+ expect(html).toMatch(/^<div class="md-body font-sans text-base text-fg">/);
+ expect(html).toContain("<strong>world</strong>");
+ });
+
+ it("takes the three densities as class sets prose.css styles", () => {
+ const tokens = (variant: "body" | "compact" | "flush") =>
+ classTokens(renderStatic(createElement(Prose, { text: "x", variant })));
+ expect(tokens("body")).toEqual(["font-sans", "md-body"]);
+ expect(tokens("compact")).toEqual(["font-sans", "md-body", "md-compact"]);
+ expect(tokens("flush")).toEqual(["font-sans", "md-body", "md-body-flush"]);
+ });
+});
+
+describe("Md links", () => {
+ it("open in a new tab when no resolver is provided", () => {
+ const tags = anchors(
+ renderStatic(createElement(Md, { text: "[a](https://example.com) and [b](notes.md)" })),
+ );
+ expect(tags).toHaveLength(2);
+ for (const tag of tags) {
+ expect(tag).toContain('target="_blank"');
+ expect(tag).toContain('rel="noreferrer"');
+ }
+ expect(PROSE_NEW_TAB).toEqual({ target: "_blank", rel: "noreferrer" });
+ });
+
+ it("take what a resolver decides, per href, after the href itself", () => {
+ const seen: (string | undefined)[] = [];
+ const resolve: ProseLinkResolver = (href) => {
+ seen.push(href);
+ return href?.startsWith("https:") ? PROSE_NEW_TAB : {};
+ };
+ const html = renderStatic(
+ createElement(ProseLinksProvider, {
+ resolve,
+ children: createElement(Md, { text: "[a](https://example.com) and [b](notes.md)" }),
+ }),
+ );
+ const [external, local] = anchors(html);
+ expect(external).toContain('target="_blank"');
+ expect(local).toContain('href="notes.md"');
+ expect(local).not.toContain("target=");
+ expect(seen).toEqual(["https://example.com", "notes.md"]);
+ });
+
+ it("carry a link title as the shared tooltip, not a native title", () => {
+ const [tag] = anchors(renderStatic(createElement(Md, { text: '[a](https://x.dev "Docs")' })));
+ expect(tag).toContain('data-tooltip="Docs"');
+ expect(tag).not.toContain("title=");
+ });
+});
+
+describe("Md code", () => {
+ it("routes a fenced block into CodeBlock, named in the interface's words", () => {
+ const zh = { ...DEFAULT_UI_STRINGS, copyCode: "复制代码" };
+ const html = renderStatic(
+ createElement(UiStringsProvider, {
+ strings: zh,
+ children: createElement(Md, { text: "```ts\nconst a = 1;\n```" }),
+ }),
+ );
+ expect(html).toContain("code-block");
+ expect(html).toContain('aria-label="复制代码"');
+ expect(html).toContain("const a = 1;");
+ });
+
+ it("keeps inline code a bare <code> for the stylesheet to dress", () => {
+ const html = renderStatic(createElement(Md, { text: "run `pnpm test` now" }));
+ expect(html).toContain("<code>pnpm test</code>");
+ });
+
+ it("lets a surface add adapters over the settled map without losing the code block", () => {
+ expect(Object.keys(SETTLED_MD_COMPONENTS).sort()).toEqual(["a", "pre"]);
+ const html = renderStatic(
+ createElement(Md, {
+ text: "![alt](pic.png)\n\n```\nx\n```",
+ components: { img: () => createElement("i", null, "image") },
+ }),
+ );
+ expect(html).toContain("<i>image</i>");
+ expect(html).toContain("code-block");
+ });
+});
+
+describe("the content stylesheet", () => {
+ const css = read("prose.css");
+
+ it("is loaded by the components that need it, KaTeX's sheet with the Markdown", () => {
+ expect(read("prose.tsx")).toMatch(/import "katex\/dist\/katex\.min\.css";/);
+ expect(read("prose.tsx")).toMatch(/import "\.\/prose\.css";/);
+ const code = readFileSync(
+ join(SRC_DIR, "components/content/code-block/code-block.tsx"),
+ "utf8",
+ );
+ expect(code).toMatch(/import "\.\.\/prose\/prose\.css";/);
+ });
+
+ it("stays unlayered and free of Tailwind directives, so it needs no build pass and beats utilities", () => {
+ const rules = css.replace(/\/\*[\s\S]*?\*\//g, "");
+ expect(rules).not.toMatch(/@layer|@apply|@reference|@import/);
+ });
+
+ it("colours through tokens alone, and switches mode only for Shiki's own palette", () => {
+ const rules = css.replace(/\/\*[\s\S]*?\*\//g, "");
+ expect(rules).not.toMatch(/#[0-9a-f]{3,8}\b|\brgb\(|\boklch\(/i);
+ expect(rules).not.toMatch(/--color-/);
+ expect(rules.match(/\.dark\b/g)).toHaveLength(2);
+ expect(rules).toMatch(/html\.dark \.shiki,\s*html\.dark \.shiki span \{/);
+ });
+
+ it("keeps the code-surface resets after the Markdown pre rule they override at equal weight", () => {
+ expect(css.indexOf(".md-body pre {")).toBeGreaterThan(-1);
+ expect(css.indexOf(".code-surface :is(pre, textarea) {")).toBeGreaterThan(
+ css.indexOf(".md-body pre {"),
+ );
+ });
+});
diff --git a/packages/web/test/remark-autolink-boundary.test.ts b/packages/ui/test/remark-autolink-boundary.test.ts
similarity index 96%
rename from packages/web/test/remark-autolink-boundary.test.ts
rename to packages/ui/test/remark-autolink-boundary.test.ts
index 33da63c8..f8cc83a5 100644
--- a/packages/web/test/remark-autolink-boundary.test.ts
+++ b/packages/ui/test/remark-autolink-boundary.test.ts
@@ -1,5 +1,6 @@
/**
- * Where a bare URL ends. GFM's autolink literal stops at whitespace and only then trims trailing
+ * Where a bare URL ends (src/components/content/prose/remark-autolink-boundary.ts, through the
+ * shared pipeline). GFM's autolink literal stops at whitespace and only then trims trailing
* punctuation, so anything that follows the URL without a space — CJK text, a comma, the `**` that
* was meant to close a bold span — is swallowed into the href. These pin the boundary where GFM
* stopped looking, and pin the three things that must not change: explicit links, URLs that are
@@ -9,7 +10,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/markdown-plugins";
+import { REMARK_PLUGINS } from "../src/components/content/prose/markdown-plugins";
/** The rendered `[href, text]` of the first link, or null. */
function firstLink(markdown: string): [string, string] | null {
diff --git a/packages/ui/test/strings.test.ts b/packages/ui/test/strings.test.ts
index adfc9d8e..c24112fe 100644
--- a/packages/ui/test/strings.test.ts
+++ b/packages/ui/test/strings.test.ts
@@ -26,6 +26,7 @@ describe("UiStrings", () => {
"clearSearch",
"close",
"copied",
+ "copyCode",
"dismiss",
"hidePassword",
"loading",
@@ -42,6 +43,7 @@ describe("UiStrings", () => {
hidePassword: "Hide password",
clearSearch: "Clear search",
moreInfo: "More info",
+ copyCode: "Copy code",
notifications: "Notifications",
dismiss: "Dismiss",
});
diff --git a/packages/ui/test/typography.test.ts b/packages/ui/test/typography.test.ts
new file mode 100644
index 00000000..5c41d5e6
--- /dev/null
+++ b/packages/ui/test/typography.test.ts
@@ -0,0 +1,98 @@
+/**
+ * Heading, Text and InlineCode: each reads its rung from the theme's tokens, the two hooks ride on
+ * the roles that own them (the display title on a level-1 heading, the eyebrow on the eyebrow
+ * role), the outline level survives a non-heading element, and the colours are tokens.
+ */
+import { createElement } from "react";
+import { describe, expect, it } from "vitest";
+import { Heading, InlineCode, Text } from "../src/components/content/typography/typography";
+import type { HeadingLevel, TextVariant } from "../src/components/content/typography/typography";
+import { classTokens, renderStatic } from "../src/testing";
+
+const LEVELS: readonly HeadingLevel[] = [1, 2, 3, 4, 5, 6];
+
+describe("Heading", () => {
+ it("renders its level's element on its level's rung", () => {
+ for (const level of LEVELS) {
+ const html = renderStatic(createElement(Heading, { level }, "Title"));
+ expect(html).toMatch(new RegExp(`^<h${level} class="`));
+ const tokens = classTokens(html);
+ for (const part of ["font", "size", "lh", "weight", "tracking", "transform"]) {
+ expect(
+ tokens.some((token) => token.includes(`--ui-h${level}-${part}`)),
+ part,
+ ).toBe(true);
+ }
+ const others = tokens.filter(
+ (token) => /--ui-h[1-6]-/.test(token) && !token.includes(`--ui-h${level}-`),
+ );
+ expect(others).toEqual([]);
+ }
+ });
+
+ it("carries the display hook on a level-1 display title only", () => {
+ const display = renderStatic(createElement(Heading, { level: 1, display: true }, "Agents"));
+ expect(classTokens(display)).toContain("ui-display");
+ const plain = renderStatic(createElement(Heading, { level: 1 }, "Agents"));
+ expect(classTokens(plain)).not.toContain("ui-display");
+ const lower = renderStatic(createElement(Heading, { level: 2, display: true }, "Agents"));
+ expect(classTokens(lower)).not.toContain("ui-display");
+ });
+
+ it("keeps the outline level on an element that is not a heading", () => {
+ const html = renderStatic(createElement(Heading, { level: 3, as: "div" }, "Section"));
+ expect(html).toMatch(/^<div role="heading" aria-level="3" class="/);
+ const h = renderStatic(createElement(Heading, { level: 4, as: "h2" }, "Section"));
+ expect(h).toMatch(/^<h2 class="/);
+ expect(h).not.toContain("aria-level");
+ });
+
+ it("adds the caller's classes and attributes", () => {
+ const html = renderStatic(
+ createElement(Heading, { level: 2, id: "models", className: "truncate" }, "Models"),
+ );
+ expect(html).toContain('id="models"');
+ expect(classTokens(html)).toContain("truncate");
+ });
+});
+
+describe("Text", () => {
+ const render = (variant: TextVariant) => renderStatic(createElement(Text, { variant }, "words"));
+
+ it("takes each role's element and rung", () => {
+ expect(render("body")).toMatch(/^<p class="text-sm /);
+ expect(render("small")).toMatch(/^<p class="text-xs /);
+ expect(render("caption")).toContain("[font-size:var(--ui-text-caption-size)]");
+ expect(render("mono")).toMatch(/^<span class="font-mono /);
+ expect(render("label")).toMatch(/^<span class="text-xs font-semibold text-fg-muted /);
+ expect(renderStatic(createElement(Text, { as: "dd" }, "x"))).toMatch(/^<dd /);
+ });
+
+ it("is a group label through the eyebrow hook, in the subtle ink", () => {
+ expect(classTokens(render("eyebrow"))).toEqual(
+ expect.arrayContaining(["ui-eyebrow", "text-fg-subtle"]),
+ );
+ });
+
+ it("colours through tokens alone", () => {
+ for (const variant of ["body", "small", "caption", "eyebrow", "mono", "label"] as const) {
+ expect(classTokens(render(variant)).filter((t) => /gray|dark:|white/.test(t))).toEqual([]);
+ }
+ });
+});
+
+describe("InlineCode", () => {
+ it("is a code span on the neutral chip, breaking long identifiers anywhere", () => {
+ const html = renderStatic(createElement(InlineCode, null, "packages/ui/src/index.ts"));
+ expect(html).toMatch(/^<code class="/);
+ expect(classTokens(html)).toEqual(
+ expect.arrayContaining([
+ "bg-tone-neutral-bg",
+ "text-fg",
+ "font-mono",
+ "rounded-sm",
+ "[overflow-wrap:anywhere]",
+ ]),
+ );
+ });
+});
diff --git a/packages/web/package.json b/packages/web/package.json
index c4fd101c..1e10e3f8 100644
--- a/packages/web/package.json
+++ b/packages/web/package.json
@@ -15,22 +15,15 @@
"dependencies": {
"@prismshadow/penguin-core": "workspace:*",
"@prismshadow/penguin-ui": "workspace:*",
- "@shikijs/langs": "^4.3.1",
- "@shikijs/themes": "^4.3.1",
"@xterm/addon-clipboard": "^0.1.0",
"@xterm/addon-fit": "^0.10.0",
"@xterm/addon-web-links": "^0.11.0",
"@xterm/xterm": "^5.5.0",
"copy-to-clipboard": "^4.0.2",
- "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",
"uqr": "^0.1.3",
"zustand": "^5.0.15"
},
diff --git a/packages/web/src/app.tsx b/packages/web/src/app.tsx
index 7927e0f7..1c85c23e 100644
--- a/packages/web/src/app.tsx
+++ b/packages/web/src/app.tsx
@@ -1,6 +1,8 @@
/**
- * App root component: Locale -> Theme -> Auth -> LocaleScope -> Router provider composition,
- * with the app's clipboard writer handed to the shared UI package's copy controls.
+ * App root component: ClipboardWriter -> CodeHighlighter -> Locale -> Theme -> Auth -> LocaleScope ->
+ * Router provider composition. The shared UI package's copy controls get the app's clipboard
+ * writer, and every code surface of the package gets the app's worker-backed code highlighter
+ * (features/chat/code-highlight.ts).
* LocaleScope (a remount boundary) sits inside AuthProvider: switching language rebuilds the UI tree without
* re-fetching auth, avoiding a full-screen white flash from RequireAuth briefly seeing user=undefined.
* Also installs the app-wide file-drop guard: a file dropped outside the chat area — the only
@@ -10,13 +12,19 @@
* drop on the sidebar do something; it makes it do nothing.
*/
import { useEffect } from "react";
-import { ClipboardWriterProvider, Toaster, TooltipLayer } from "@prismshadow/penguin-ui";
+import {
+ ClipboardWriterProvider,
+ CodeHighlighterProvider,
+ Toaster,
+ TooltipLayer,
+} from "@prismshadow/penguin-ui";
import { LocaleProvider, LocaleScope } from "./state/locale";
import { ThemeProvider } from "./state/theme";
import { AuthProvider } from "./state/auth";
import { AppRouter } from "./router";
import { writeClipboard } from "./lib/clipboard";
import { guardWindowDragOver, guardWindowDrop } from "./lib/file-drop";
+import { highlightCode } from "./features/chat/code-highlight";
/**
* `initialPath`: mount the app on an in-memory router opened at that path instead of the
@@ -37,19 +45,21 @@ export function App({ initialPath }: { initialPath?: string } = {}) {
}, []);
return (
<ClipboardWriterProvider write={writeClipboard}>
- <LocaleProvider>
- <ThemeProvider>
- <AuthProvider>
- <LocaleScope>
- <AppRouter {...(initialPath === undefined ? {} : { initialPath })} />
- {/* Top toast overlay: portaled to body, z-index above modals, shared site-wide. */}
- <Toaster />
- {/* The hover hints of every `data-tooltip` element: one listener set, one panel. */}
- <TooltipLayer />
- </LocaleScope>
- </AuthProvider>
- </ThemeProvider>
- </LocaleProvider>
+ <CodeHighlighterProvider highlight={highlightCode}>
+ <LocaleProvider>
+ <ThemeProvider>
+ <AuthProvider>
+ <LocaleScope>
+ <AppRouter {...(initialPath === undefined ? {} : { initialPath })} />
+ {/* Top toast overlay: portaled to body, z-index above modals, shared site-wide. */}
+ <Toaster />
+ {/* The hover hints of every `data-tooltip` element: one listener set, one panel. */}
+ <TooltipLayer />
+ </LocaleScope>
+ </AuthProvider>
+ </ThemeProvider>
+ </LocaleProvider>
+ </CodeHighlighterProvider>
</ClipboardWriterProvider>
);
}
diff --git a/packages/web/src/components/ui/file-browser.tsx b/packages/web/src/components/ui/file-browser.tsx
index c9d0c85c..d4d710fb 100644
--- a/packages/web/src/components/ui/file-browser.tsx
+++ b/packages/web/src/components/ui/file-browser.tsx
@@ -21,15 +21,18 @@ import { useMemo } from "react";
import type { CSSProperties, ReactNode } from "react";
import ReactMarkdown from "react-markdown";
import type { Components } from "react-markdown";
-import { SkeletonList } from "@prismshadow/penguin-ui";
-import { REHYPE_PLUGINS, REMARK_PLUGINS } from "../../lib/markdown-plugins";
-import { SETTLED_MD_COMPONENTS } from "../../features/chat/md";
+import {
+ CodeBlock,
+ REHYPE_PLUGINS,
+ REMARK_PLUGINS,
+ SETTLED_MD_COMPONENTS,
+ SkeletonList,
+ languageForExtension,
+} from "@prismshadow/penguin-ui";
import { bodyWithoutFrontmatter } from "../../lib/frontmatter";
import type { FileTreeRow } from "../../lib/file-tree";
import { S } from "../../lib/strings";
import { extOf, previewKindFor } from "../../lib/workspace-tree";
-import { CodeBlock } from "../../features/chat/code-block";
-import { languageForExtension } from "../../features/chat/code-languages";
import { FileTree } from "./file-tree";
import type { TreeToggle } from "./file-tree";
diff --git a/packages/web/src/features/agents/memory-tab.tsx b/packages/web/src/features/agents/memory-tab.tsx
index 174aa6ab..3d1fdb14 100644
--- a/packages/web/src/features/agents/memory-tab.tsx
+++ b/packages/web/src/features/agents/memory-tab.tsx
@@ -43,6 +43,7 @@ import {
ICONS,
IconButton,
InfoPopover,
+ Md,
Modal,
NoticeStrip,
RadioGroup,
@@ -65,7 +66,6 @@ import { useAuth } from "../../state/auth";
import { useLocale } from "../../state/locale";
import { useProject } from "../../state/project";
import { useSaveConfirm } from "./save-confirm";
-import { Md } from "../chat/md";
import { useAiBridge } from "../ai-create";
import { buildMemoryAddPrompt, buildMemoryEditPrompt } from "./memory-chat-prompts";
import {
diff --git a/packages/web/src/features/chat/assistant-reply-body.tsx b/packages/web/src/features/chat/assistant-reply-body.tsx
index 1d183486..edfd99ce 100644
--- a/packages/web/src/features/chat/assistant-reply-body.tsx
+++ b/packages/web/src/features/chat/assistant-reply-body.tsx
@@ -10,12 +10,12 @@
* soft veil at the body's foot, and Console types it out behind a block caret.
*
* Markdown renders the revealed prefix, so code blocks and lists grow as they are typed. It
- * stays in its streaming mode (no highlighting, no KaTeX; see md.tsx) until the reveal is done,
- * and `children` (the stop reason, a nested reply's files card) wait for the same moment, so
- * nothing lands under text that is still coming in.
+ * stays in its streaming mode (no highlighting, no KaTeX; see the UI package's Md) until the
+ * reveal is done, and `children` (the stop reason, a nested reply's files card) wait for the same
+ * moment, so nothing lands under text that is still coming in.
*/
import type { ReactNode } from "react";
-import { Md } from "./md";
+import { Md } from "@prismshadow/penguin-ui";
import { StreamingCaret } from "./streaming-caret";
import { useStreamReveal } from "./use-stream-reveal";
@@ -38,7 +38,7 @@ export function AssistantReplyBody({
className="ui-stream md-body anim-msg my-3 font-sans text-base leading-relaxed text-gray-800 dark:text-gray-100"
data-state={live ? "streaming" : "done"}
>
- {/* Re-renders the revealed text directly while live; memoized, so a settled reply skips the re-parse, and code blocks highlight once on settle (see md.tsx). */}
+ {/* Re-renders the revealed text directly while live; memoized, so a settled reply skips the re-parse, and code blocks highlight once on settle (see the UI package's Md). */}
<Md text={revealed} streaming={live} />
{live && <StreamingCaret />}
{!live && children}
diff --git a/packages/web/src/features/chat/code-block.tsx b/packages/web/src/features/chat/code-block.tsx
deleted file mode 100644
index 592c0c22..00000000
--- a/packages/web/src/features/chat/code-block.tsx
+++ /dev/null
@@ -1,168 +0,0 @@
-/**
- * Code rendering, in two layers.
- *
- * `CodeSurface` is the code itself: a `<pre>` highlighted via Shiki — inline CSS variables for
- * both the github-light / github-dark themes, with dark mode switched via style overrides under
- * html.dark (see styles.css), so theme switching doesn't require re-highlighting. The
- * highlighter is dynamically imported (its own chunk, loaded only once the first code block
- * appears; see highlighter.ts); before loading completes, and for languages that chunk doesn't
- * carry, it falls back to unhighlighted text. It carries no chrome at all, which is what lets
- * the Files panel put its source view and its editor on the same layer and know they agree.
- *
- * `CodeBlock` is that surface inside the chat message's chrome (visual reference:
- * better-chatbot's pre-block): a bordered box with a top bar carrying the language label and a
- * copy button. Message code blocks keep no line numbers and no wrapping — see the Files panel
- * for why wrapping is a file viewer's answer and not a transcript's.
- *
- * highlight=false (while a message is streaming) skips highlighting and falls back to plain
- * text: every streaming frame re-renders the full code with a growing length, and re-tokenizing
- * the whole block each time would be O(n^2) main-thread cost, and an in-progress highlight can't
- * be canceled; once streaming settles, highlight flips true and a single final highlight is done.
- */
-import { useEffect, useMemo, useState } from "react";
-import type { CSSProperties, ReactNode } from "react";
-import { CopyButton } from "@prismshadow/penguin-ui";
-import { S } from "../../lib/strings";
-
-/**
- * The highlighted code, with no box around it.
- *
- * With `lineNumbers`, the lines become blocks (see highlighter.ts's BLOCK_LINES) so a CSS
- * counter can draw a gutter that survives wrapping, and the unhighlighted fallback is split
- * into the same line elements — one gutter, whichever path rendered the code, and one shape for
- * a caller that needs to lay something else over it.
- */
-export function CodeSurface({
- language,
- code,
- highlight = true,
- lineNumbers = false,
- wrap = false,
- settleMs = 0,
- className = "",
- children,
-}: {
- language: string;
- code: string;
- highlight?: boolean;
- /** Draw a line-number gutter (and, with it, put each line in a block of its own). */
- lineNumbers?: boolean;
- /** Soft-wrap long lines instead of scrolling sideways. */
- wrap?: boolean;
- /**
- * Wait this long after the last change before highlighting. 0 (the default) highlights every
- * change, which is right for code that is rendered once; an editor passes a delay so that
- * typing costs nothing but a re-render. While a highlight is pending the surface shows the
- * CURRENT text unhighlighted rather than the previous text's colours — a code layer that
- * lags the keystrokes it sits under is worse than a colourless one.
- */
- settleMs?: number;
- className?: string;
- /** Laid over the code in the same scroll box (the Files panel's editor puts its textarea here). */
- children?: ReactNode;
-}) {
- const [highlighted, setHighlighted] = useState<{ code: string; html: string }>();
-
- useEffect(() => {
- if (!highlight) {
- setHighlighted(undefined);
- return;
- }
- let alive = true;
- const run = () => {
- void import("./highlighter")
- .then((mod) => mod.highlightToHtml(code, language, { blockLines: lineNumbers }))
- .then((out) => {
- if (alive && out !== undefined) setHighlighted({ code, html: out });
- })
- .catch(() => {
- // Unknown language / failed to load: keep the unhighlighted fallback.
- });
- };
- if (settleMs <= 0) {
- run();
- return () => {
- alive = false;
- };
- }
- const timer = window.setTimeout(run, settleMs);
- return () => {
- alive = false;
- window.clearTimeout(timer);
- };
- }, [code, language, highlight, lineNumbers, settleMs]);
-
- // Split once per code change, and only where a gutter needs it: the digit count sizes the
- // gutter, and the unhighlighted fallback renders the lines it returns.
- const lines = useMemo(() => (lineNumbers ? code.split("\n") : null), [code, lineNumbers]);
- // Only the current text's own highlight may be shown (see settleMs).
- const html = highlighted?.code === code ? highlighted.html : undefined;
- /**
- * The `dangerouslySetInnerHTML` payload, held stable across renders that do not change the
- * markup. React compares this prop by object identity and re-sets `innerHTML` whenever it
- * differs, so a fresh `{ __html }` literal rebuilds every node in the block on every render
- * of the surrounding component — discarding any selection the reader had made inside it, and
- * re-parsing the whole highlighted body for nothing.
- */
- const htmlProp = useMemo(() => (html === undefined ? undefined : { __html: html }), [html]);
-
- return (
- <div
- className={`code-surface ${wrap ? "code-wrap" : "code-nowrap"} ${
- lines === null ? "" : "code-lines"
- } ${className}`}
- style={
- lines === null
- ? undefined
- : // `ch` and not `rem`: an overlaid textarea has to indent by exactly this much, and
- // only a character-relative unit is the same length in both layers. +2 is the
- // clearance between the number and the code.
- ({ "--code-gutter": `${String(lines.length).length + 2}ch` } as CSSProperties)
- }
- >
- {htmlProp !== undefined ? (
- <div dangerouslySetInnerHTML={htmlProp} />
- ) : (
- <pre>
- <code>
- {lines === null
- ? code
- : // No newline between the spans: they are blocks, and the text a selection
- // serialises out of a run of blocks already carries the breaks.
- lines.map((line, i) => (
- <span key={i} className="line">
- {line}
- </span>
- ))}
- </code>
- </pre>
- )}
- {children}
- </div>
- );
-}
-
-export function CodeBlock({
- language,
- code,
- highlight = true,
-}: {
- language: string;
- code: string;
- highlight?: boolean;
-}) {
- return (
- <div className="code-block my-2 overflow-hidden rounded-lg border border-gray-200 dark:border-gray-800">
- <div className="flex items-center justify-between border-b border-gray-200 bg-gray-50 px-3 py-1 dark:border-gray-800 dark:bg-gray-900">
- <span className="font-mono text-xs lowercase text-gray-500 dark:text-gray-400">
- {language || "text"}
- </span>
- {/* Always visible — the header bar has no hover-gated container. */}
- <CopyButton text={code} label={S.chat.copyCode} />
- </div>
- <div className="overflow-x-auto bg-white text-[13px] leading-relaxed dark:bg-gray-950">
- <CodeSurface language={language} code={code} highlight={highlight} />
- </div>
- </div>
- );
-}
diff --git a/packages/web/src/features/chat/code-highlight.ts b/packages/web/src/features/chat/code-highlight.ts
new file mode 100644
index 00000000..299761ef
--- /dev/null
+++ b/packages/web/src/features/chat/code-highlight.ts
@@ -0,0 +1,12 @@
+/**
+ * The app's code highlighter, handed to the shared UI package's code surfaces once, around the app
+ * (`CodeHighlighterProvider` in app.tsx). The package never runs Shiki itself; this is where the
+ * Web App decides that it runs on a worker (highlighter.ts).
+ *
+ * The worker client is imported on the first call, not up front, so it stays in a chunk of its own
+ * that a session with no code block never fetches — as it did when the code block imported it.
+ */
+import type { CodeHighlighter } from "@prismshadow/penguin-ui";
+
+export const highlightCode: CodeHighlighter = (code, language, options) =>
+ import("./highlighter").then((mod) => mod.highlightToHtml(code, language, options));
diff --git a/packages/web/src/features/chat/compaction-banner.tsx b/packages/web/src/features/chat/compaction-banner.tsx
index 019f5bef..85ca573e 100644
--- a/packages/web/src/features/chat/compaction-banner.tsx
+++ b/packages/web/src/features/chat/compaction-banner.tsx
@@ -44,14 +44,13 @@
* turn ends** and manual compaction both go into the Session total (the Trace page lists
* compaction turns separately); see the task-stats module comments.
*/
-import { StatusIcon } from "@prismshadow/penguin-ui";
+import { Md, StatusIcon } from "@prismshadow/penguin-ui";
import { S } from "../../lib/strings";
import { humanizeDuration } from "../../lib/format";
import type { CompactionItem } from "../../lib/omni/stream-model";
import { compactionResultVisible, compactionSummaryText } from "../../lib/omni/compaction-summary";
import { DISCLOSURE_BODY_MD_CLASS, DisclosureRow } from "./disclosure-row";
import { LiveDuration } from "./live-duration";
-import { Md } from "./md";
import { StepBanner } from "./step-banner";
/**
diff --git a/packages/web/src/features/chat/highlighter.ts b/packages/web/src/features/chat/highlighter.ts
index 6e0ed742..2d00bde8 100644
--- a/packages/web/src/features/chat/highlighter.ts
+++ b/packages/web/src/features/chat/highlighter.ts
@@ -12,6 +12,7 @@
* CSP that forbids it, a construction that throws — the work falls back to this thread, which is
* exactly the old behaviour and still correct, only blocking.
*/
+import type { HighlightOptions } from "@prismshadow/penguin-ui";
import type { HighlightRequest, HighlightResponse } from "./highlighter.worker";
/** undefined: not tried yet. null: unavailable here, use the main thread. */
@@ -54,24 +55,24 @@ function getWorker(): Worker | null {
/**
* Highlights `code` as `language`, returning Shiki's dual-theme HTML, or undefined when the
* language isn't one this bundle carries. Rejects only on an unexpected failure (chunk fetch,
- * grammar error); callers fall back to unhighlighted text either way.
+ * grammar error); callers fall back to unhighlighted text either way. The shape is the shared UI
+ * package's `CodeHighlighter`, which is what the app hands its code surfaces (code-highlight.ts).
*/
export async function highlightToHtml(
code: string,
language: string,
- options?: { blockLines?: boolean },
+ options: HighlightOptions = {},
): Promise<string | undefined> {
- const blockLines = options?.blockLines === true;
const w = getWorker();
if (w === null) {
// Imported here and not at the top: the engine is already in the worker's bundle, and a
// static import would put a second copy of it on the main thread for every reader whose
// worker works — which is all of them.
- const { highlight } = await import("./highlighter-core");
- return highlight(code, language, blockLines);
+ const { highlight } = await import("@prismshadow/penguin-ui/highlighter");
+ return highlight(code, language, options);
}
const id = (nextId += 1);
- const request: HighlightRequest = { id, code, language, blockLines };
+ const request: HighlightRequest = { id, code, language, options };
const answer = await new Promise<HighlightResponse>((resolve) => {
pending.set(id, resolve);
w.postMessage(request);
diff --git a/packages/web/src/features/chat/highlighter.worker.ts b/packages/web/src/features/chat/highlighter.worker.ts
index be7f74c4..1f7d1686 100644
--- a/packages/web/src/features/chat/highlighter.worker.ts
+++ b/packages/web/src/features/chat/highlighter.worker.ts
@@ -10,13 +10,15 @@
* The protocol is one message each way, correlated by an id the caller mints, because several
* blocks can settle at once and their answers come back in whatever order they finish.
*/
-import { highlight } from "./highlighter-core";
+import { highlight } from "@prismshadow/penguin-ui/highlighter";
+import type { HighlightOptions } from "@prismshadow/penguin-ui/highlighter";
export interface HighlightRequest {
id: number;
code: string;
language: string;
- blockLines: boolean;
+ /** Block lines and marks, as the package's code surfaces ask for them. */
+ options: HighlightOptions;
}
export interface HighlightResponse {
@@ -27,8 +29,8 @@ export interface HighlightResponse {
}
self.onmessage = (event: MessageEvent<HighlightRequest>) => {
- const { id, code, language, blockLines } = event.data;
- highlight(code, language, blockLines).then(
+ const { id, code, language, options } = event.data;
+ highlight(code, language, options).then(
(html) => {
const done: HighlightResponse = html === undefined ? { id } : { id, html };
self.postMessage(done);
diff --git a/packages/web/src/features/chat/md.tsx b/packages/web/src/features/chat/md.tsx
deleted file mode 100644
index b2dd135a..00000000
--- a/packages/web/src/features/chat/md.tsx
+++ /dev/null
@@ -1,185 +0,0 @@
-/**
- * Markdown body memoized by text identity. The stream model mutates chat items in place and
- * only reassigns `text` when a delta arrives, so every settled message keeps the same string
- * instance across the per-frame version bumps — the shallow prop compare then skips its entire
- * micromark → mdast → React re-parse, and only the actively-streaming message re-renders.
- * Without this, each animation frame during a stream re-parsed the WHOLE transcript (O(n²)
- * over a long reply), which visibly froze the UI while large code blocks streamed in.
- *
- * Fenced code blocks render through CodeBlock (language chrome + copy button + Shiki
- * highlight). `streaming` disables highlighting while deltas are still arriving —
- * 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).
- *
- * Two optional props open the renderer to a surface with its own nodes — the channel message
- * body, which keeps `@mentions` as chips — without a second copy of the pipeline drifting from
- * this one. They only ever ADD to the shared stage and to the maps below; nothing a surface
- * passes can take the shared plugins away.
- */
-import { createContext, isValidElement, memo, useContext, useMemo } from "react";
-import type { ComponentPropsWithoutRef, ReactNode } from "react";
-import ReactMarkdown from "react-markdown";
-import type { Components, ExtraProps, Options } from "react-markdown";
-import { NO_REHYPE_PLUGINS, REHYPE_PLUGINS, REMARK_PLUGINS } from "../../lib/markdown-plugins";
-import { NEW_TAB, replyLinkBehavior } from "../../lib/reply-link";
-import type { WorkspaceLinks } from "../../lib/reply-link";
-import { CodeBlock } from "./code-block";
-
-/** Flatten a react-markdown code element's children to plain text (string or string array in practice). */
-function codeText(children: unknown): string {
- if (typeof children === "string") return children;
- if (Array.isArray(children)) return children.filter((c) => typeof c === "string").join("");
- return "";
-}
-
-/**
- * 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 (
- <CodeBlock
- language={language}
- code={codeText(props.children).replace(/\n$/, "")}
- highlight={!streaming}
- />
- );
- }
- return <pre>{children}</pre>;
-}
-
-/**
- * The Workspace the Markdown below belongs to, when it belongs to one. Only a conversation
- * provides it (MessageStream); every other surface — Memory, the handbook, tickets — renders
- * without it and keeps a new tab for every link.
- */
-const WorkspaceLinksContext = createContext<WorkspaceLinks | null>(null);
-
-/**
- * Makes the links in the Markdown below Workspace-aware: a link naming a file of `workspace`
- * opens it through `onOpenFile` (the Files panel) instead of a new tab — see lib/reply-link.ts
- * for how an href is sorted. With no `onOpenFile` the links keep the new-tab behaviour.
- *
- * The value is memoized on its two inputs: a context change re-renders every link in the
- * transcript, memoized message bodies included, so `onOpenFile` has to be a stable callback.
- */
-export function WorkspaceLinksProvider({
- workspace,
- onOpenFile,
- children,
-}: {
- workspace: string | null;
- onOpenFile: ((path: string) => void) | undefined;
- children: ReactNode;
-}) {
- const links = useMemo<WorkspaceLinks | null>(
- () => (onOpenFile === undefined ? null : { workspace, openFile: onOpenFile }),
- [workspace, onOpenFile],
- );
- return <WorkspaceLinksContext.Provider value={links}>{children}</WorkspaceLinksContext.Provider>;
-}
-
-/**
- * Link adapter. Outside a conversation every link opens in a new tab (`target="_blank"` +
- * `rel="noreferrer"`, which also implies `noopener`), unconditionally, so a click never
- * navigates the SPA away. Inside one (WorkspaceLinksProvider above) only an external link does;
- * a Workspace file opens in the Files panel, an `#anchor` scrolls within the page, and a
- * relative href with nowhere to go stays put — a relative href resolves against the SPA's own
- * route, so a new tab on it is a second copy of the App on a page that does not exist.
- * All other anchor props react-markdown supplies (`href`, ...) are forwarded as-is — only its
- * non-DOM `node` prop is stripped — and the behaviour sits after the spread so it always wins.
- * A link title (`[text](url "title")`) becomes the shared tooltip's text rather than a native
- * `title`, like every other hover hint in the app. Long-URL wrapping is CSS (`.md-body a` in styles.css).
- */
-function MdLink({
- node: _node,
- children,
- title,
- ...anchorProps
-}: ComponentPropsWithoutRef<"a"> & ExtraProps) {
- const links = useContext(WorkspaceLinksContext);
- const behavior = links === null ? NEW_TAB : replyLinkBehavior(anchorProps.href, links);
- return (
- <a {...anchorProps} data-tooltip={title} {...behavior}>
- {children}
- </a>
- );
-}
-
-/**
- * The two `components` maps, built once at module scope instead of inline per render.
- * react-markdown uses `components.pre` as the element **type**, so a fresh arrow each render is
- * a new type on every commit: React unmounts and remounts every code block, dropping the user's
- * 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 same render the rehype stage
- * flips on. The `a` adapter closes over nothing — the Workspace it needs comes from context, not
- * from a closure — so both maps share the one `MdLink` reference.
- */
-const STREAMING_COMPONENTS: Components = {
- pre: (props) => <MdPre streaming>{props.children}</MdPre>,
- a: MdLink,
-};
-const SETTLED_COMPONENTS: Components = {
- pre: (props) => <MdPre streaming={false}>{props.children}</MdPre>,
- a: MdLink,
-};
-
-/**
- * The settled map, for the read-only Markdown surfaces outside the chat (the shared file
- * browser) that keep the code-block chrome and swap only the link and image adapters.
- */
-export const SETTLED_MD_COMPONENTS: Components = SETTLED_COMPONENTS;
-
-export const Md = memo(function Md({
- text,
- streaming = false,
- extraPlugins,
- components,
-}: {
- text: string;
- streaming?: boolean;
- /**
- * Remark plugins a surface adds to the shared stage, for a node of its own — the channel
- * message body adds the pass that turns its `@mentions` into elements. They are appended to
- * REMARK_PLUGINS rather than replacing it: a renderer that dropped the shared list would end
- * bare URLs and typeset math differently from every other one, which is the drift
- * markdown-plugins.ts exists to prevent.
- */
- extraPlugins?: NonNullable<Options["remarkPlugins"]>;
- /**
- * Element overrides merged over the two maps below, which keep `pre` and `a`. A module
- * constant, for the same reason those are: react-markdown uses a component as the element
- * *type*, so a fresh function per render remounts everything it renders.
- */
- components?: Components;
-}) {
- const base = streaming ? STREAMING_COMPONENTS : SETTLED_COMPONENTS;
- return (
- <ReactMarkdown
- remarkPlugins={
- extraPlugins === undefined ? REMARK_PLUGINS : [...REMARK_PLUGINS, ...extraPlugins]
- }
- rehypePlugins={streaming ? NO_REHYPE_PLUGINS : REHYPE_PLUGINS}
- components={components === undefined ? base : { ...base, ...components }}
- >
- {text}
- </ReactMarkdown>
- );
-});
diff --git a/packages/web/src/features/chat/memory-view.tsx b/packages/web/src/features/chat/memory-view.tsx
index 48a58981..909b7765 100644
--- a/packages/web/src/features/chat/memory-view.tsx
+++ b/packages/web/src/features/chat/memory-view.tsx
@@ -14,7 +14,7 @@
*/
import { useEffect, useState } from "react";
import type { SessionInfo } from "@prismshadow/penguin-server/api";
-import { GlyphIcon, ICON_SIZE, SkeletonList } from "@prismshadow/penguin-ui";
+import { GlyphIcon, ICON_SIZE, Md, SkeletonList } from "@prismshadow/penguin-ui";
import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
import { formatRelativeDate } from "../../lib/format";
@@ -22,7 +22,6 @@ import { bodyWithoutFrontmatter } from "../../lib/frontmatter";
import type { MemoryChangeRow, MemoryLocateTarget } from "../../lib/omni/memory-changes";
import { memoryRowKey } from "../../lib/omni/memory-changes";
import { useLocale } from "../../state/locale";
-import { Md } from "./md";
import { buildMemoryList, memoryNavBack, memoryNavForRequest } from "./memory-nav";
import type { MemoryNavMode, ScopeFiles } from "./memory-nav";
diff --git a/packages/web/src/features/chat/message-stream.tsx b/packages/web/src/features/chat/message-stream.tsx
index 0a3140b4..92b2d0f2 100644
--- a/packages/web/src/features/chat/message-stream.tsx
+++ b/packages/web/src/features/chat/message-stream.tsx
@@ -16,7 +16,7 @@ import type { MemoryChangeRow } from "../../lib/omni/memory-changes";
import type { TaskStats } from "../../lib/omni/task-stats";
import type { PendingApproval } from "./use-session-stream";
import { MessageItem } from "./message-item";
-import { WorkspaceLinksProvider } from "./md";
+import { WorkspaceLinksProvider } from "./workspace-links";
import { WorkGroup, isWorkItem } from "./work-group";
import { createStreamFollow, stickToBottom } from "./stream-follow";
import type { StreamFollow } from "./stream-follow";
@@ -480,7 +480,7 @@ export function MessageStream({
<EmptyState title={S.chat.emptyStream} />
) : (
// Links in replies, reasoning and compaction summaries name files of this Session's
- // Workspace: they open in its Files panel rather than a new tab (see md.tsx).
+ // Workspace: they open in its Files panel rather than a new tab (see workspace-links.tsx).
<WorkspaceLinksProvider workspace={ctx.workspace ?? null} onOpenFile={ctx.onOpenFile}>
<MessageItems items={items} ctx={ctx} />
</WorkspaceLinksProvider>
diff --git a/packages/web/src/features/chat/thinking-block.tsx b/packages/web/src/features/chat/thinking-block.tsx
index b1087103..c21b2452 100644
--- a/packages/web/src/features/chat/thinking-block.tsx
+++ b/packages/web/src/features/chat/thinking-block.tsx
@@ -5,14 +5,13 @@
* same source every other disclosure row uses; shares the running-state icons (in progress /
* done / failed) with tool cards.
*/
-import { StatusIcon } from "@prismshadow/penguin-ui";
+import { Md, StatusIcon } from "@prismshadow/penguin-ui";
import type { RunState } from "@prismshadow/penguin-ui";
import { S } from "../../lib/strings";
import { humanizeDuration } from "../../lib/format";
import type { ThinkingItem } from "../../lib/omni/stream-model";
import { DISCLOSURE_BODY_MD_CLASS, DisclosureRow, activityState } from "./disclosure-row";
import { LiveDuration } from "./live-duration";
-import { Md } from "./md";
export function ThinkingBlock({ item }: { item: ThinkingItem }) {
const failed = item.stopReason !== undefined && item.stopReason !== "completed";
diff --git a/packages/web/src/features/chat/workspace-browser.tsx b/packages/web/src/features/chat/workspace-browser.tsx
index 9df375f8..e0457ddc 100644
--- a/packages/web/src/features/chat/workspace-browser.tsx
+++ b/packages/web/src/features/chat/workspace-browser.tsx
@@ -46,10 +46,10 @@ import type {
MouseEvent as ReactMouseEvent,
PointerEvent as ReactPointerEvent,
} from "react";
-import ReactMarkdown from "react-markdown";
import {
Button,
CloseIcon,
+ CodeSurface,
ConfirmModal,
CopiedStatus,
CopyCheckGlyph,
@@ -60,6 +60,7 @@ import {
ICONS,
ICON_SIZE,
Input,
+ Prose,
SearchInput,
SkeletonList,
Spinner,
@@ -67,6 +68,7 @@ import {
ZoomableImage,
isContextMenuKey,
isLongPressPointer,
+ languageForExtension,
noAutofill,
toastError,
toastInfo,
@@ -74,7 +76,6 @@ import {
useCopied,
useRowContextMenu,
} from "@prismshadow/penguin-ui";
-import { REHYPE_PLUGINS, REMARK_PLUGINS } from "../../lib/markdown-plugins";
import type { SessionInfo, WorkspaceSearchHit } from "@prismshadow/penguin-server/api";
import * as api from "../../api/endpoints";
import { ApiError } from "../../api/client";
@@ -134,8 +135,6 @@ import { tabKey } from "../dock/dock-state";
import { DOCK_TRANSITION_MS } from "../dock/use-dock-mount";
import { usePointerDrag } from "../dock/use-pointer-drag";
import { PAPERCLIP_ICON } from "./attached-files-banner";
-import { CodeSurface } from "./code-block";
-import { languageForExtension } from "./code-languages";
import { WorkspaceFileEditor } from "./workspace-editor";
import { WorkspaceFileMenuRows } from "./workspace-file-menu";
import type { FileMenuTarget } from "./workspace-file-menu";
@@ -2142,65 +2141,62 @@ export function WorkspaceBrowser({
/>
)
) : p.kind === "md" && richView === "rendered" ? (
- // Markdown's default rendered view: uses the same md-body layout as message bodies
- // (ReactMarkdown outputs pure static HTML with no script execution surface, so no iframe sandbox is needed).
+ // Markdown's default rendered view: the reading box and pipeline message bodies use
+ // (static HTML with no script execution surface, so no iframe sandbox is needed),
+ // with the image and link adapters swapped for ones that know the Workspace.
<>
- <div className="md-body text-base leading-relaxed text-gray-800 dark:text-gray-100">
- <ReactMarkdown
- remarkPlugins={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: a
- // Workspace image is rewritten under the same path, and without it a
- // re-read of the Markdown would keep painting the previous bytes from
- // the browser's image cache.
- img: ({ src, alt }) => (
- <img
- src={
- typeof src === "string" && !EXTERNAL_REF_RE.test(src)
- ? `${api.workspaceFileUrl(
- sessionId,
- resolveRelative(parentDir(p.path), src),
- )}&v=${p.nonce}`
- : src
- }
- alt={alt ?? ""}
- loading="lazy"
- className="max-w-full"
- />
- ),
- // External links open in a new tab; relative links point to a Workspace
- // file, clicking opens it in the tree and the preview; in-page anchors keep default behavior.
- a: ({ href, children }) => {
- if (typeof href !== "string" || href.startsWith("#")) {
- return <a href={href}>{children}</a>;
+ <Prose
+ text={p.content ?? ""}
+ className="text-base leading-relaxed text-gray-800 dark:text-gray-100"
+ 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: a
+ // Workspace image is rewritten under the same path, and without it a
+ // re-read of the Markdown would keep painting the previous bytes from
+ // the browser's image cache.
+ img: ({ src, alt }) => (
+ <img
+ src={
+ typeof src === "string" && !EXTERNAL_REF_RE.test(src)
+ ? `${api.workspaceFileUrl(
+ sessionId,
+ resolveRelative(parentDir(p.path), src),
+ )}&v=${p.nonce}`
+ : src
}
- if (EXTERNAL_REF_RE.test(href)) {
- return (
- <a href={href} target="_blank" rel="noreferrer">
- {children}
- </a>
- );
- }
- const target = resolveRelative(parentDir(p.path), href);
+ alt={alt ?? ""}
+ loading="lazy"
+ className="max-w-full"
+ />
+ ),
+ // External links open in a new tab; relative links point to a Workspace
+ // file, clicking opens it in the tree and the preview; in-page anchors keep default behavior.
+ a: ({ href, children }) => {
+ if (typeof href !== "string" || href.startsWith("#")) {
+ return <a href={href}>{children}</a>;
+ }
+ if (EXTERNAL_REF_RE.test(href)) {
return (
- <a
- href={api.workspaceFileUrl(sessionId, target)}
- onClick={(e) => {
- e.preventDefault();
- openFile(target, { locate: true });
- }}
- >
+ <a href={href} target="_blank" rel="noreferrer">
{children}
</a>
);
- },
- }}
- >
- {p.content ?? ""}
- </ReactMarkdown>
- </div>
+ }
+ const target = resolveRelative(parentDir(p.path), href);
+ return (
+ <a
+ href={api.workspaceFileUrl(sessionId, target)}
+ onClick={(e) => {
+ e.preventDefault();
+ openFile(target, { locate: true });
+ }}
+ >
+ {children}
+ </a>
+ );
+ },
+ }}
+ />
{p.truncated && (
<p className="mt-1 text-xs text-gray-400">… {S.files.previewTruncated}</p>
)}
diff --git a/packages/web/src/features/chat/workspace-editor.tsx b/packages/web/src/features/chat/workspace-editor.tsx
index fcad2384..20a50784 100644
--- a/packages/web/src/features/chat/workspace-editor.tsx
+++ b/packages/web/src/features/chat/workspace-editor.tsx
@@ -5,12 +5,12 @@
* editing a file looks exactly like reading it — same line numbers, same colours, same
* wrapping — and pressing Edit reflows nothing.
*
- * The two layers are stacked in a single grid cell (styles.css's `.code-editor`), so the taller
- * one sizes the box and the one scroll container carries both. Nothing is synchronised in JS,
- * which is what makes it impossible for them to drift apart: there is only one scroll position.
- * What they do have to agree on is every metric that decides where a glyph lands — family,
- * size, line height, letter spacing, tab size, padding, wrap mode — and those are stated once,
- * for both layers, in `.code-surface`.
+ * The two layers are stacked in a single grid cell (`.code-editor` in the UI package's prose.css),
+ * so the taller one sizes the box and the one scroll container carries both. Nothing is
+ * synchronised in JS, which is what makes it impossible for them to drift apart: there is only
+ * one scroll position. What they do have to agree on is every metric that decides where a glyph
+ * lands — family, size, line height, letter spacing, tab size, padding, wrap mode — and those
+ * are stated once, for both layers, in `.code-surface`.
*
* No spell-check or autocorrect, and the `editor.save` shortcut (⌘S / Ctrl+S by default) saves —
* the browser's own "save page" default is suppressed while the focus is here. Long lines scroll
@@ -20,13 +20,12 @@
*/
import { useEffect, useRef, useState } from "react";
import type { KeyboardEvent as ReactKeyboardEvent } from "react";
+import { CodeSurface, languageForExtension } from "@prismshadow/penguin-ui";
import { S } from "../../lib/strings";
import { isShortcut } from "../../lib/shortcuts/match";
import { currentPlatform } from "../../lib/shortcuts/platform";
import { keymap } from "../../lib/shortcuts/store";
import { TEXT_PREVIEW_LIMIT, baseName, extOf } from "../../lib/workspace-tree";
-import { CodeSurface } from "./code-block";
-import { languageForExtension } from "./code-languages";
/** Quiet period before re-highlighting, so a keystroke costs a re-render and not a tokenize. */
const EDIT_HIGHLIGHT_SETTLE_MS = 200;
diff --git a/packages/web/src/features/chat/workspace-links.tsx b/packages/web/src/features/chat/workspace-links.tsx
new file mode 100644
index 00000000..b956cbd8
--- /dev/null
+++ b/packages/web/src/features/chat/workspace-links.tsx
@@ -0,0 +1,35 @@
+/**
+ * Makes the links in the Markdown below Workspace-aware: a link naming a file of `workspace` opens
+ * it through `onOpenFile` (the Files panel) instead of a new tab — see lib/reply-link.ts for how an
+ * href is sorted. With no `onOpenFile` the links keep the package's default, a new tab for every
+ * link.
+ *
+ * Only a conversation provides it (MessageStream); every other surface — Memory, the handbook,
+ * tickets — renders without it and keeps a new tab for every link. The resolver is memoized on its
+ * two inputs: a context change re-renders every link in the transcript, memoized message bodies
+ * included, so `onOpenFile` has to be a stable callback.
+ */
+import { useMemo } from "react";
+import type { ReactNode } from "react";
+import { ProseLinksProvider } from "@prismshadow/penguin-ui";
+import type { ProseLinkResolver } from "@prismshadow/penguin-ui";
+import { replyLinkBehavior } from "../../lib/reply-link";
+
+export function WorkspaceLinksProvider({
+ workspace,
+ onOpenFile,
+ children,
+}: {
+ workspace: string | null;
+ onOpenFile: ((path: string) => void) | undefined;
+ children: ReactNode;
+}) {
+ const resolve = useMemo<ProseLinkResolver | null>(
+ () =>
+ onOpenFile === undefined
+ ? null
+ : (href) => replyLinkBehavior(href, { workspace, openFile: onOpenFile }),
+ [workspace, onOpenFile],
+ );
+ return <ProseLinksProvider resolve={resolve}>{children}</ProseLinksProvider>;
+}
diff --git a/packages/web/src/features/company/channel-markdown.tsx b/packages/web/src/features/company/channel-markdown.tsx
index e7dd43b1..c2cfe27c 100644
--- a/packages/web/src/features/company/channel-markdown.tsx
+++ b/packages/web/src/features/company/channel-markdown.tsx
@@ -22,9 +22,9 @@
import { createContext, useContext } from "react";
import type { ReactNode } from "react";
import type { Components, Options } from "react-markdown";
+import { Md } from "@prismshadow/penguin-ui";
import { S } from "../../lib/strings";
import { toneSurface } from "../../lib/tone";
-import { Md } from "../chat/md";
import { mentionIsMe, mentionLabel, mentionRuns } from "./channel-mentions";
/** The mdast shapes this pass touches, declared structurally rather than taking `@types/mdast` on. */
diff --git a/packages/web/src/features/company/handbook-page.tsx b/packages/web/src/features/company/handbook-page.tsx
index eacc9021..23bf4346 100644
--- a/packages/web/src/features/company/handbook-page.tsx
+++ b/packages/web/src/features/company/handbook-page.tsx
@@ -28,6 +28,7 @@ import {
ICON_GAP,
ICON_SIZE,
Input,
+ Md,
Modal,
Skeleton,
Textarea,
@@ -45,7 +46,6 @@ import { useShortcutLabel } from "../../lib/shortcuts/use-keymap";
import { useDocumentTitle } from "../../lib/use-document-title";
import { useLocale } from "../../state/locale";
import type { TreeToggle } from "../../components/ui/file-tree";
-import { Md } from "../chat/md";
import { OrgEmptyLine, OrgPage, OrgSection, useOrg } from "./org-layout";
import { ErrorLine } from "./shared";
import { COLLAPSE_ALL_ICON, HandbookExplorer } from "./handbook-explorer";
diff --git a/packages/web/src/features/company/path-capsule.tsx b/packages/web/src/features/company/path-capsule.tsx
index c503941c..8083343e 100644
--- a/packages/web/src/features/company/path-capsule.tsx
+++ b/packages/web/src/features/company/path-capsule.tsx
@@ -20,10 +20,9 @@
import { useMemo } from "react";
import type { ReactNode } from "react";
import type { Components, Options } from "react-markdown";
-import { CopiedStatus, GlyphIcon, ICONS, ICON_SIZE, useCopied } from "@prismshadow/penguin-ui";
+import { CopiedStatus, GlyphIcon, ICONS, ICON_SIZE, Md, useCopied } from "@prismshadow/penguin-ui";
import { S } from "../../lib/strings";
import { STAT_ICONS } from "../../lib/stat-icons";
-import { Md } from "../chat/md";
import { codePath, pathKind, pathLabel, spellAsWritten, splitPaths } from "./path-capsules";
import type { PathScope } from "./path-capsules";
diff --git a/packages/web/src/features/company/ticket-dialog.tsx b/packages/web/src/features/company/ticket-dialog.tsx
index 583a97b4..8edb21b9 100644
--- a/packages/web/src/features/company/ticket-dialog.tsx
+++ b/packages/web/src/features/company/ticket-dialog.tsx
@@ -46,6 +46,7 @@ import {
ICON_GAP,
ICON_SIZE,
Input,
+ Md,
Modal,
NoticeStrip,
Segmented,
diff --git a/packages/web/src/features/plugins/plugin-detail-page.tsx b/packages/web/src/features/plugins/plugin-detail-page.tsx
index 79eafce1..fc2c9153 100644
--- a/packages/web/src/features/plugins/plugin-detail-page.tsx
+++ b/packages/web/src/features/plugins/plugin-detail-page.tsx
@@ -19,10 +19,11 @@ import {
CopyCheckGlyph,
GlyphIcon,
ICONS,
+ REHYPE_PLUGINS,
+ REMARK_PLUGINS,
Skeleton,
useCopied,
} from "@prismshadow/penguin-ui";
-import { REHYPE_PLUGINS, REMARK_PLUGINS } from "../../lib/markdown-plugins";
import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
diff --git a/packages/web/src/features/traces/trace-event-row.tsx b/packages/web/src/features/traces/trace-event-row.tsx
index cdb001fb..88f1e736 100644
--- a/packages/web/src/features/traces/trace-event-row.tsx
+++ b/packages/web/src/features/traces/trace-event-row.tsx
@@ -12,10 +12,16 @@
* aren't highlighted together).
*/
import { Fragment, useState } from "react";
-import { Badge, ICONS, RequiredMark, ZoomableImage } from "@prismshadow/penguin-ui";
+import {
+ Badge,
+ ICONS,
+ REHYPE_PLUGINS,
+ REMARK_PLUGINS,
+ RequiredMark,
+ ZoomableImage,
+} from "@prismshadow/penguin-ui";
import type { BadgeStyle } from "@prismshadow/penguin-ui";
import ReactMarkdown from "react-markdown";
-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";
diff --git a/packages/web/src/lib/install-scope.ts b/packages/web/src/lib/install-scope.ts
index 363bc3d9..9082f7b5 100644
--- a/packages/web/src/lib/install-scope.ts
+++ b/packages/web/src/lib/install-scope.ts
@@ -84,8 +84,8 @@ export interface KeyRule {
* - `penguin.chatRouteApplied.<field>` (features/chat/draft-view.tsx) is `sessionStorage`,
* not `localStorage`: it is scoped to one tab's history and dies with the tab, so it
* cannot outlive a data root.
- * - `penguin.ooo` (lib/remark-autolink-boundary.ts) is the product's domain inside an
- * example URL in a doc comment. It is not a storage key.
+ * - `penguin.ooo` (the shared UI package's remark-autolink-boundary.ts) is the product's
+ * domain inside an example URL in a doc comment. It is not a storage key.
*/
export const KEY_RULES: readonly KeyRule[] = [
// ---------------------------------------------------------------- browser preferences
diff --git a/packages/web/src/lib/reply-link.ts b/packages/web/src/lib/reply-link.ts
index b58ee821..9c8fa104 100644
--- a/packages/web/src/lib/reply-link.ts
+++ b/packages/web/src/lib/reply-link.ts
@@ -77,8 +77,9 @@ export interface LinkBehavior {
}
/**
- * A new tab with no handle back to this window (`noreferrer` implies `noopener`): every Markdown
- * link outside a conversation, and an external one inside it.
+ * A new tab with no handle back to this window (`noreferrer` implies `noopener`): an external link
+ * inside a conversation — the same attributes the shared UI package gives every Markdown link
+ * outside one (`PROSE_NEW_TAB`).
*/
export const NEW_TAB: LinkBehavior = { target: "_blank", rel: "noreferrer" };
diff --git a/packages/web/src/lib/ui-strings.ts b/packages/web/src/lib/ui-strings.ts
index 852bd129..4bf105b0 100644
--- a/packages/web/src/lib/ui-strings.ts
+++ b/packages/web/src/lib/ui-strings.ts
@@ -24,6 +24,7 @@ export function uiStringsOf(dict: Strings): UiStrings {
moreInfoAbout: dict.common.moreInfoAbout,
notifications: dict.common.notifications,
dismiss: dict.common.dismiss,
+ copyCode: dict.chat.copyCode,
};
}
diff --git a/packages/web/src/main.tsx b/packages/web/src/main.tsx
index 031acc50..e5dd2514 100644
--- a/packages/web/src/main.tsx
+++ b/packages/web/src/main.tsx
@@ -27,11 +27,9 @@ import { bootInstallScope, watchInstallScope } from "./lib/install-scope";
// The global shortcut dispatcher installs itself at module evaluation (a React effect would
// leave a post-paint window where a chord is dead); the import is what evaluates it.
import { setShortcutBlocker } from "./lib/shortcuts/dispatcher";
-// 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";
+// KaTeX's stylesheet comes with the shared UI package's Markdown (content/prose/prose.tsx imports
+// it), resolved out of node_modules so Vite emits it and its woff2 faces as local assets: the
+// desktop app has to render math with no network.
import "./styles.css";
// No global command runs behind an open dialog or menu: they all join the UI package's Escape
diff --git a/packages/web/src/styles.css b/packages/web/src/styles.css
index df64fc62..a516fae3 100644
--- a/packages/web/src/styles.css
+++ b/packages/web/src/styles.css
@@ -44,9 +44,8 @@
@layer base {
:root {
- /* 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). An alias of the theme's
- token, so the two cannot drift. */
+ /* The body font stack under a name of the app's own, which the workflow frame reads off the
+ document (lib/workflow-theme.ts). An alias of the theme's token, so the two cannot drift. */
--font-app-sans: var(--ui-font-sans);
}
html,
@@ -483,270 +482,11 @@
);
}
-/* ---------- Minimal typography for Markdown body content (no typography plugin) ---------- */
+/* ---------- Markdown and code ---------- */
-.md-body {
- /* Long unspaced strings like attachment paths / long URLs wrap within the narrow container instead of breaking the layout (especially important for mobile message streams). */
- overflow-wrap: break-word;
-}
-.md-body :is(p, ul, ol, pre, blockquote, table) {
- margin: 0.5rem 0;
-}
-.md-body li {
- margin: 0.25rem 0;
-}
-.md-body p {
- line-height: 1.7;
-}
-.md-body :is(h1, h2, h3, h4) {
- font-weight: 600;
- margin: 0.75rem 0 0.5rem;
-}
-/* A body that provides its own inset — the disclosure rows' expanded thinking and compaction
- text (features/chat/disclosure-row.tsx) — drops the outermost block's margin, so the gap at
- each end is that padding alone rather than the padding plus whatever margin the first and
- last blocks carry. It has to be a rule here rather than a `[&>*:first-child]:mt-0` utility at
- the call site: every rule in this file is unlayered, and an unlayered declaration beats
- anything in `@layer utilities` whatever its specificity, so the utility would be inert
- against the margins set above. */
-.md-body-flush > :first-child {
- margin-top: 0;
-}
-.md-body-flush > :last-child {
- margin-bottom: 0;
-}
-.md-body h1 {
- font-size: 1.25rem;
-}
-.md-body h2 {
- font-size: 1.125rem;
-}
-.md-body h3 {
- font-size: 1rem;
-}
-.md-body ul {
- list-style: disc;
- padding-left: 1.25rem;
-}
-.md-body ol {
- list-style: decimal;
- padding-left: 1.25rem;
-}
-.md-body a {
- @apply text-brand-700 underline decoration-brand-300 underline-offset-2 transition-colors hover:text-brand-600 dark:text-brand-300 dark:decoration-brand-700;
- /* `anywhere` rather than `word-break: break-all`: it only breaks a token that would otherwise
- overflow, so long URLs wrap cleanly (filling each line) while short Latin words in mixed
- CJK/Latin link text never split mid-word; unlike `break-word` it also counts the break
- opportunities toward min-content sizing, so a long link can't blow out flex/table layouts. */
- overflow-wrap: anywhere;
-}
-.md-body code {
- @apply rounded bg-gray-100 px-1 py-0.5 text-[0.85em] text-gray-800 dark:bg-gray-800 dark:text-gray-200;
-}
-/* Inline code in prose often holds long unbroken paths/identifiers: same rationale as the link
- rule above (fenced blocks are excluded — .md-body pre scrolls horizontally instead). */
-.md-body :not(pre) > code {
- overflow-wrap: anywhere;
-}
-.md-body pre {
- @apply overflow-x-auto rounded-lg border border-gray-200 bg-gray-50 p-3 text-sm dark:border-gray-800 dark:bg-gray-900;
- /* Off-screen code blocks skip layout/paint: with several settled 200KB+ replies in the
- transcript, their <pre> layout dominated every streaming commit (profiled ~90% native
- layout) and froze the chat while large code streamed in. auto keeps the measured size for
- stable scrollbar geometry; on-screen blocks render normally and stay find-in-page searchable. */
- content-visibility: auto;
- contain-intrinsic-size: auto 400px;
-}
-.md-body pre code {
- background: transparent;
- color: inherit;
- padding: 0;
-}
-/* The code surface (features/chat/code-block.tsx's CodeSurface) — the code itself, with no box
- around it. This resets the inner pre's border/background/radius, overriding both .md-body
- pre's styles and Shiki's own inline background colours (!important beats inline style); the
- background belongs to whatever the surface was dropped into. Not scoped to .md-body: the
- Files panel's source view is not inside a markdown container. Dark text is overridden via
- the dual-theme inline variable --shiki-dark, so switching themes never re-highlights.
-
- The metrics are stated once, for the pre AND for a textarea laid over it: the Files panel's
- editor is a transparent-text textarea on top of this very surface, and the two only stay in
- register while every value that decides where a glyph lands — family, size, line height,
- letter spacing, tab size, padding, wrap mode — is the same in both. Size and line height are
- inherited so one wrapper sets them for both layers. */
-.code-surface :is(pre, textarea) {
- margin: 0;
- border: 0;
- border-radius: 0;
- background: transparent !important;
- /* The message code block's own padding, kept to the pixel so this refactor leaves the
- transcript exactly where it was; the Files panel's two layers only need to agree. */
- padding: 0.625rem 0.75rem;
- font-size: inherit;
- line-height: inherit;
- letter-spacing: normal;
- tab-size: 4;
- @apply font-mono;
-}
-.code-surface pre {
- @apply text-gray-800 dark:text-gray-200;
-}
-/* Wrapping is the file viewer's answer, never the message stream's: a transcript's code block
- scrolls sideways (see CodeBlock), and only a caller that asked for `wrap` gets this. Both
- layers need the textarea's own UA rule spelled out, because that is the one they must match. */
-.code-wrap :is(pre, textarea) {
- white-space: pre-wrap;
- overflow-wrap: break-word;
-}
-.code-nowrap :is(pre, textarea) {
- white-space: pre;
- overflow-wrap: normal;
-}
-/* Grown to its content so a horizontal scroll has something to scroll, and so the sticky gutter
- below can travel the whole width — a sticky box cannot go past its containing block, which
- would otherwise be only as wide as the visible strip. */
-.code-nowrap pre {
- min-width: max-content;
-}
-
-/* Line numbers. A counter over the per-line elements both rendering paths produce — Shiki's own
- `.line` wrappers and the same wrappers the unhighlighted fallback splits into — so the
- highlighter needs no changes and the two paths cannot disagree.
-
- The lines are blocks here (highlighter.ts strips the newlines Shiki puts between them), which
- is what makes the gutter survive wrapping: `padding-left` reserves the gutter on every visual
- row, and the negative `text-indent` pulls only the FIRST row back into it, so a wrapped line's
- continuation rows line up under its own code instead of under its number. The code therefore
- starts at exactly `--code-gutter` on every row, which is all an overlaid textarea has to
- match — it indents by that much and needs no per-line rule of its own.
-
- The number is generated content and `user-select: none`, so dragging across the code selects
- the code alone; the copy affordances are unaffected either way, since they copy the string the
- component was given and never the DOM. */
-.code-lines pre {
- counter-reset: code-line;
-}
-.code-lines .line {
- display: block;
- counter-increment: code-line;
- padding-left: var(--code-gutter, 4ch);
- text-indent: calc(-1 * var(--code-gutter, 4ch));
-}
-.code-lines textarea {
- padding-left: calc(0.75rem + var(--code-gutter, 4ch));
-}
-.code-lines .line::before {
- content: counter(code-line);
- position: sticky;
- left: 0;
- display: inline-block;
- width: var(--code-gutter, 4ch);
- padding-right: 1.25ch;
- text-align: right;
- text-indent: 0;
- user-select: none;
- -webkit-user-select: none;
- @apply bg-white text-gray-400;
-}
-/* The dark half is spelled out rather than applied as a `dark:` variant: that variant appends
- its `:where(.dark, .dark *)` to the END of the selector, which for a pseudo-element is
- invalid CSS and is dropped without a word — the same reason the Shiki theme overrides below
- are written this way. */
-html.dark .code-lines .line::before {
- @apply bg-gray-950 text-gray-600;
-}
-
-/* The editor's two layers, stacked in one grid cell so the taller of them sizes the box and a
- single scroll container moves both — no scroll syncing in JS, and so nothing to drift. The
- textarea keeps a visible caret over transparent text and must not scroll on its own. */
-.code-editor {
- display: grid;
- min-height: 100%;
-}
-.code-editor > * {
- grid-area: 1 / 1;
-}
-.code-editor textarea {
- overflow: hidden;
- resize: none;
- color: transparent;
- outline: none;
- @apply caret-gray-900 dark:caret-gray-100;
-}
-/* The dark half is a rule of its own for the same reason as the gutter's above: a `dark:`
- variant appends its `:where(.dark, .dark *)` to the END of the selector, which after a
- pseudo-element is invalid CSS and is dropped from the build without a word. */
-.code-editor textarea::selection {
- @apply bg-sky-200;
-}
-html.dark .code-editor textarea::selection {
- @apply bg-sky-500/40;
-}
-/* While an IME is composing, the candidate text lives only in the textarea's own rendering — it
- has not reached `value` on every platform — so the layers swap: the code layer steps aside and
- the textarea shows its own text, underline and all, until the composition commits. */
-.code-editor-host[data-composing="true"] textarea {
- @apply text-gray-800 dark:text-gray-200;
-}
-.code-editor-host[data-composing="true"] .code-editor > :not(textarea) {
- visibility: hidden;
-}
-html.dark .shiki,
-html.dark .shiki span {
- color: var(--shiki-dark) !important;
- font-style: var(--shiki-dark-font-style) !important;
- font-weight: var(--shiki-dark-font-weight) !important;
- text-decoration: var(--shiki-dark-text-decoration) !important;
-}
-.md-body blockquote {
- @apply border-l-2 border-gray-300 pl-3 text-gray-600 dark:border-gray-700 dark:text-gray-400;
-}
-.md-body table {
- border-collapse: collapse;
- /* Same rule as docs (packages/docs/src/styles.css): a wide table scrolls horizontally inside
- the message body instead of pushing the whole page wide. */
- display: block;
- overflow-x: auto;
-}
-.md-body :is(th, td) {
- @apply border border-gray-200 px-2 py-1 text-sm dark:border-gray-800;
-}
-
-/* A channel message body (features/company/channel-view.tsx): the same Markdown typography, one
- size tighter. A message is a line in a stream, not a document — its blocks sit closer, its
- headings step down towards body size, and the first and last block give up their outer margins
- so a one-paragraph message occupies exactly its row. Used together with .md-body, after it, so
- these win at equal specificity. */
-.md-compact :is(p, ul, ol, pre, blockquote, table) {
- margin: 0.25rem 0;
-}
-.md-compact li {
- margin: 0.125rem 0;
-}
-.md-compact p {
- line-height: 1.6;
-}
-.md-compact :is(h1, h2, h3, h4) {
- margin: 0.5rem 0 0.25rem;
-}
-.md-compact h1 {
- font-size: 1.0625rem;
-}
-.md-compact h2 {
- font-size: 1rem;
-}
-.md-compact h3 {
- font-size: 0.9375rem;
-}
-.md-compact h4 {
- font-size: 0.875rem;
-}
-.md-compact > :first-child {
- margin-top: 0;
-}
-.md-compact > :last-child {
- margin-bottom: 0;
-}
+/* The Markdown typography (`.md-body`, `.md-compact`, `.md-body-flush`), the code surface
+ (`.code-*`), Shiki's dark palette and the KaTeX fixes live in the shared UI package, beside the
+ components that draw them: packages/ui/src/components/content/prose/prose.css. */
/* ---------- Channel message bubble (features/company/channel-view.tsx) ---------- */
@@ -761,47 +501,3 @@ html.dark .shiki span {
.channel-bubble :is(th, td) {
@apply border-gray-300 dark:border-gray-700;
}
-
-/* ---------- 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/deslop.test.ts b/packages/web/test/deslop.test.ts
index 28e1ebd4..c052f73f 100644
--- a/packages/web/test/deslop.test.ts
+++ b/packages/web/test/deslop.test.ts
@@ -80,7 +80,6 @@ const ALLOWLIST: DeslopAllowlist = {
"features/chat/agent-topology-view.tsx": { 12: [1, "W6"], 13: [3, "W6"] },
"features/chat/chat-input.tsx": { 7: [1, "W6"], 12: [7, "W6"], 13: [5, "W6"] },
"features/chat/chat-page.tsx": { 12: [2, "W6"], 13: [3, "W6"], 15: [1, "W4"] },
- "features/chat/code-block.tsx": { 13: [1, "W5"] },
"features/chat/context-gauge.tsx": { 12: [5, "W8"] },
"features/chat/conversation-outline.tsx": { 12: [1, "W6"] },
"features/chat/disclosure-row.tsx": { 13: [1, "W4"], 14: [2, "W4"] },
diff --git a/packages/web/test/disclosure-body.test.ts b/packages/web/test/disclosure-body.test.ts
index 59738bba..a0441975 100644
--- a/packages/web/test/disclosure-body.test.ts
+++ b/packages/web/test/disclosure-body.test.ts
@@ -1,13 +1,13 @@
/**
* The expanded Markdown body the thinking block and the compaction sections share
* (features/chat/disclosure-row.tsx). vitest is node-only here (`environment: "node"`, no
- * jsdom), so this pins the contract against the source text and styles.css — the
+ * jsdom), so this pins the contract against the source text and the stylesheets — the
* title-reveal.test.ts convention.
*
* The fragile part is not the class list, it is **where the end-margin reset lives**. The
- * `.md-body` rules in styles.css sit outside any cascade layer while Tailwind's utilities are
- * emitted inside `@layer utilities`, and an unlayered declaration beats a layered one at any
- * specificity — so a `[&>*:first-child]:mt-0` utility on the body is silently inert against
+ * `.md-body` rules (the shared UI package's prose.css) sit outside any cascade layer while
+ * Tailwind's utilities are emitted inside `@layer utilities`, and an unlayered declaration beats a
+ * layered one at any specificity — so a `[&>*:first-child]:mt-0` utility on the body is inert against
* `.md-body`'s own `margin: 0.5rem 0`, and the body carries double the inset it claims.
* Nothing about the class list looks wrong when that happens, which is why it is asserted here.
*
@@ -49,8 +49,9 @@ const unlayeredRules = (sheet: string) => {
};
/**
- * The unlayered rules of every stylesheet under the scanned roots — styles.css today, the shared
- * package's component CSS once the Markdown body moves there — each file stripped on its own.
+ * The unlayered rules of every stylesheet under the scanned roots — the app's styles.css and the
+ * shared package's component CSS, where the Markdown body's rules live — each file stripped on its
+ * own.
*/
const unlayered = SCAN.files
.filter((file) => file.name.endsWith(".css"))
diff --git a/packages/web/test/highlighter-worker.test.ts b/packages/web/test/highlighter-worker.test.ts
index b840efcd..0bd4c088 100644
--- a/packages/web/test/highlighter-worker.test.ts
+++ b/packages/web/test/highlighter-worker.test.ts
@@ -2,11 +2,14 @@
* Highlighting must stay off the main thread, and the engine must stay out of the main bundle.
*
* Tokenizing is linear in the size of the input and runs to completion once it starts, so the
- * viewer's responsiveness depends on it happening in a worker. Two edits would quietly undo that
- * without failing a build or looking wrong in review: calling the engine directly from a
- * component, and turning the client's fallback `await import(…)` into a static import — which
- * bundles a second ~147KB copy of Shiki into the entry chunk for every reader whose worker works,
- * the very cost the split exists to avoid.
+ * viewer's responsiveness depends on it happening in a worker. The engine lives in the shared UI
+ * package on its own subpath (`@prismshadow/penguin-ui/highlighter`, which the package's code
+ * surfaces never import — they ask the highlighter the app hands them), and the app decides where
+ * it runs. Three edits would quietly undo that without failing a build or looking wrong in
+ * review: calling the engine directly from a component, turning the client's fallback
+ * `await import(…)` into a static import — which bundles a second ~147KB copy of Shiki into the
+ * entry chunk for every reader whose worker works, the very cost the split exists to avoid — and
+ * handing the code surfaces something other than the worker client.
*
* vitest runs node-only here (`environment: "node"`, no jsdom), so this asserts against the
* source text rather than a running worker.
@@ -43,13 +46,22 @@ describe("the highlighting worker", () => {
it("owns the only static import of the engine", () => {
const importers = sources(SRC)
- .filter(([, src]) => /^import\s(?!type\s)[^;]*from "[^"]*highlighter-core"/m.test(src))
+ .filter(([, src]) =>
+ /^import\s(?!type\s)[^;]*from "@prismshadow\/penguin-ui\/highlighter"/m.test(src),
+ )
.map(([path]) => path);
expect(importers).toEqual(["features/chat/highlighter.worker.ts"]);
});
it("leaves the client's own use of the engine dynamic, as its fallback", () => {
const client = readFileSync(join(CHAT, "highlighter.ts"), "utf8");
- expect(client).toMatch(/await import\("\.\/highlighter-core"\)/);
+ expect(client).toMatch(/await import\("@prismshadow\/penguin-ui\/highlighter"\)/);
+ });
+
+ it("is what the app hands the package's code surfaces, loaded on the first block", () => {
+ const hook = readFileSync(join(CHAT, "code-highlight.ts"), "utf8");
+ expect(hook).toMatch(/import\("\.\/highlighter"\)[\s\S]*highlightToHtml/);
+ const app = readFileSync(join(SRC, "app.tsx"), "utf8");
+ expect(app).toContain("<CodeHighlighterProvider highlight={highlightCode}>");
});
});
diff --git a/packages/web/test/inner-html-stability.test.ts b/packages/web/test/inner-html-stability.test.ts
index e4cdb419..effbd8c0 100644
--- a/packages/web/test/inner-html-stability.test.ts
+++ b/packages/web/test/inner-html-stability.test.ts
@@ -43,15 +43,17 @@ describe("dangerouslySetInnerHTML", () => {
expect(inline).toEqual([]);
});
- it("is used in exactly the two places that own untrusted markup", () => {
- // A third site is not forbidden, but it is worth noticing: each one is a place sanitisation
- // has to be argued, and each one carries the identity rule above.
+ it("is used in exactly the three places that own untrusted markup", () => {
+ // A fourth site is not forbidden, but it is worth noticing: each one is a place sanitisation
+ // has to be argued, and each one carries the identity rule above. The code surface and the
+ // diff viewer both inject the highlighter's markup, in which the code itself arrives escaped.
const users = sources()
.filter(([, src]) => src.includes("dangerouslySetInnerHTML"))
.map(([path]) => path)
.sort();
expect(users).toEqual([
- "packages/web/src/features/chat/code-block.tsx",
+ "packages/ui/src/components/content/code-block/code-block.tsx",
+ "packages/ui/src/components/content/diff-viewer/diff-viewer.tsx",
"packages/web/src/features/skills/skill-icon-view.tsx",
]);
});
diff --git a/packages/web/test/markdown-math.test.ts b/packages/web/test/markdown-math.test.ts
index 04962078..b5db6cda 100644
--- a/packages/web/test/markdown-math.test.ts
+++ b/packages/web/test/markdown-math.test.ts
@@ -1,369 +1,70 @@
/**
- * 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.
+ * The app's side of the shared Markdown pipeline: every renderer in the Web App and the shared UI
+ * package takes the same plugin lists, and KaTeX's fonts ship with the build. How the pipeline
+ * renders math is the package's own suite (packages/ui/test/prose-math.test.ts).
*/
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";
+import { expectEveryRootScanned, scanSources } from "./helpers/roots";
-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);
- });
-});
+const SCAN = scanSources();
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.
+ * source scan: every `<ReactMarkdown` in either root has to carry both stages.
*/
- const RENDERERS = [
- "../src/features/chat/md.tsx",
- "../src/features/chat/workspace-browser.tsx",
- "../src/components/ui/file-browser.tsx",
- "../src/features/traces/trace-event-row.tsx",
- ];
+ const renderers = SCAN.files.filter(
+ (file) => file.name.endsWith(".tsx") && file.text.includes("<ReactMarkdown"),
+ );
/**
- * 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
+ * Matched by the constant each prop names rather than by an exact string, because `Md` 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", () => {
+ /** Where each root takes the lists from: the package's own module, or the package. */
+ const HOME: Record<string, string> = {
+ ui: 'from "./markdown-plugins"',
+ web: 'from "@prismshadow/penguin-ui"',
+ };
+
+ it("are looked for in every source root", () => {
+ expectEveryRootScanned(SCAN);
+ });
+
+ it("are the known renderers: Md, the shared file browser, a Trace event and a plugin's page", () => {
+ expect(renderers.map((file) => file.id).sort()).toEqual([
+ "packages/ui/src/components/content/prose/prose.tsx",
+ "packages/web/src/components/ui/file-browser.tsx",
+ "packages/web/src/features/plugins/plugin-detail-page.tsx",
+ "packages/web/src/features/traces/trace-event-row.tsx",
+ ]);
+ });
+
+ it("every ReactMarkdown 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);
+ for (const file of renderers) {
+ const uses = file.text.split("<ReactMarkdown").length - 1;
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);
+ const values = [...file.text.matchAll(new RegExp(`${prop}=\\{([^}]*)\\}`, "g"))];
+ expect(values.length, `${file.id} ${prop}`).toBe(uses);
+ for (const [, value] of values) expect(value, `${file.id} ${prop}`).toContain(constant);
}
- expect(source, relative).toContain('from "../../lib/markdown-plugins"');
+ expect(file.text, file.id).toContain(HOME[file.root]);
}
- expect(total).toBe(5); // md.tsx, workspace, the shared file browser, and two in trace-event-row
+ expect(total).toBe(5); // Md, the shared file browser, a plugin's page, 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);
+ for (const file of renderers) {
// 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}"`);
+ expect(file.text, `${file.id} imports ${plugin} directly`).not.toContain(`"${plugin}"`);
}
}
});
diff --git a/packages/web/test/md.test.ts b/packages/web/test/md.test.ts
index 97646f73..4cf02b04 100644
--- a/packages/web/test/md.test.ts
+++ b/packages/web/test/md.test.ts
@@ -1,8 +1,10 @@
/**
- * Md (chat markdown) rendering contract, via react-dom/server static markup (node env, no DOM):
+ * Md (the shared UI package's Markdown) as the app wires it, via react-dom/server static markup
+ * (node env, no DOM):
* - outside a conversation every link — explicit [text](url), bare autolinked URL (remark-gfm),
* relative or #anchor — opens in a new tab: target="_blank" + rel="noreferrer";
- * - inside one (WorkspaceLinksProvider, as MessageStream renders it) only an external link does:
+ * - inside one (WorkspaceLinksProvider, features/chat/workspace-links.tsx, as MessageStream
+ * renders it) only an external link does:
* a link to a Workspace file, an #anchor and a relative href with nowhere to go render without
* a target, because a relative href resolves against the SPA's own route. What their clicks do
* is covered in reply-link.test.ts — static markup carries no handlers;
@@ -13,7 +15,8 @@ import { describe, expect, it, vi } from "vitest";
import { createElement } from "react";
import type { MouseEvent } from "react";
import { renderToStaticMarkup } from "react-dom/server";
-import { Md, WorkspaceLinksProvider } from "../src/features/chat/md";
+import { Md } from "@prismshadow/penguin-ui";
+import { WorkspaceLinksProvider } from "../src/features/chat/workspace-links";
import { replyLinkBehavior, resolveReplyLink } from "../src/lib/reply-link";
const render = (text: string, streaming = false) =>
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 5d4b309e..735e763b 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -499,6 +499,30 @@ importers:
'@fontsource/ibm-plex-sans-condensed':
specifier: ^5.3.0
version: 5.3.0
+ '@shikijs/langs':
+ specifier: ^4.3.1
+ version: 4.3.1
+ '@shikijs/themes':
+ specifier: ^4.3.1
+ version: 4.3.1
+ katex:
+ specifier: ^0.16.47
+ version: 0.16.47
+ react-markdown:
+ specifier: ^10.1.0
+ rehype-katex:
+ specifier: ^7.0.1
+ version: 7.0.1
+ remark-gfm:
+ specifier: ^4.0.0
+ version: 4.0.1([email protected])
+ remark-math:
+ specifier: ^6.0.0
+ version: 6.0.0([email protected])
+ shiki:
+ specifier: ^4.3.1
+ version: 4.3.1
zustand:
specifier: ^5.0.15
version: 5.0.15(@types/[email protected])([email protected])
@@ -582,12 +606,6 @@ importers:
'@prismshadow/penguin-ui':
specifier: workspace:*
version: link:../ui
- '@shikijs/langs':
- specifier: ^4.3.1
- version: 4.3.1
- '@shikijs/themes':
- specifier: ^4.3.1
- version: 4.3.1
'@xterm/addon-clipboard':
specifier: ^0.1.0
version: 0.1.0(@xterm/[email protected])
@@ -603,9 +621,6 @@ importers:
copy-to-clipboard:
specifier: ^4.0.2
version: 4.0.2
- katex:
- specifier: ^0.16.47
- version: 0.16.47
react:
specifier: ^19.1.0
version: 19.2.7
@@ -618,18 +633,6 @@ importers:
react-router:
specifier: ^8.3.0
- rehype-katex:
- specifier: ^7.0.1
- version: 7.0.1
- remark-gfm:
- specifier: ^4.0.0
- version: 4.0.1([email protected])
- remark-math:
- specifier: ^6.0.0
- version: 6.0.0([email protected])
- shiki:
- specifier: ^4.3.1
- version: 4.3.1
uqr:
specifier: ^0.1.3
version: 0.1.3
diff --git a/scripts/ui-migrate.json b/scripts/ui-migrate.json
index 1532c5c6..8f6f9a5c 100644
--- a/scripts/ui-migrate.json
+++ b/scripts/ui-migrate.json
@@ -587,6 +587,53 @@
"names": ["NoticeStrip", "NOTICE_TONE", "NoticeTone"]
}
]
+ },
+ "W5": {
+ "packages/web/src/features/chat/md": [
+ {
+ "owner": "W5-A",
+ "target": "@prismshadow/penguin-ui",
+ "dest": "packages/ui/src/components/content/prose/prose.tsx",
+ "names": ["Md", "SETTLED_MD_COMPONENTS"]
+ },
+ {
+ "owner": "W5-A",
+ "target": "packages/web/src/features/chat/workspace-links",
+ "dest": "packages/web/src/features/chat/workspace-links.tsx",
+ "names": ["WorkspaceLinksProvider"]
+ }
+ ],
+ "packages/web/src/lib/markdown-plugins": [
+ {
+ "owner": "W5-A",
+ "target": "@prismshadow/penguin-ui",
+ "dest": "packages/ui/src/components/content/prose/markdown-plugins.ts",
+ "names": ["REMARK_PLUGINS", "REHYPE_PLUGINS", "NO_REHYPE_PLUGINS"]
+ }
+ ],
+ "packages/web/src/features/chat/code-block": [
+ {
+ "owner": "W5-B",
+ "target": "@prismshadow/penguin-ui",
+ "dest": "packages/ui/src/components/content/code-block/code-block.tsx",
+ "names": ["CodeBlock", "CodeSurface"]
+ }
+ ],
+ "packages/web/src/features/chat/code-languages": [
+ {
+ "owner": "W5-B",
+ "target": "@prismshadow/penguin-ui",
+ "dest": "packages/ui/src/components/content/code-block/code-languages.ts",
+ "names": [
+ "languageForExtension",
+ "resolveLanguage",
+ "isPlainTextLanguage",
+ "PLAIN_TEXT_LANGUAGE",
+ "LANGUAGE_LOADERS",
+ "LANGUAGE_ALIASES"
+ ]
+ }
+ ]
}
}
}