fix(mermaid): isolate diagram layout in a sandboxed iframe

Mermaid measures every label with SVGElement.getBBox() against a node
appended to document.body, so each measurement flushes the whole host
document's layout. Measured in the live DSH window (15,418 DOM nodes):
59-75 ms per measurement, versus 1 ms in an empty iframe document. One
diagram therefore took 1.5-7.3 s, and a 31-diagram markdown document kept
the renderer main thread blocked for >20 s - long enough for the desktop
shell's surface watchdog to kill the renderer, with tab restoration
turning it into a crash loop. CSS containment on the app root does not
help (59-62 ms); only an independent layout tree does.

Render diagrams inside a hidden sandboxed iframe instead: a self-contained
blob: document (mermaid UMD bundle + a small postMessage protocol, both
inlined by scripts/build-mermaid-frame-asset.mjs) renders each diagram;
the parent only sends/receives and sanitizes the SVG. Diagrams now take
30-104 ms each and 31 diagrams complete in ~5 s in the background, while
the client mermaid chunk shrinks from 7.04 MB to 3.69 MB (minified UMD
replaces the unminified inline bundle).

Also add a shared render queue: visible/near-viewport diagrams first, the
rest filled in on requestIdleCallback with 16 ms main-thread yields between
renders, so every diagram is still rendered (none degrades to a code
block). Fence-line-sized placeholder skeletons reserve height while a
diagram waits. No host-half route changes are needed.
This commit is contained in:
OCILY committed 2026-10-28 20:20:49 +08:00
1 parent 58310536d6
commit fe06211775
12 files changed
+794 -67

No files matched your search

+3
View File
@@ -154,3 +154,6 @@ registry/
playwright-report/
test-results/
# generated by scripts/build-mermaid-frame-asset.mjs
src/client/mermaid-frame-asset.generated.ts
+1
View File
@@ -51,6 +51,7 @@
- **任务页拖拽改为每帧一次更新**:图模式背景平移、后台任务浮窗标题拖动、锚定弹层拖动不再按鼠标事件频率重绘(高回报率鼠标下此前每个 pointermove 都提交整块画布);松手同步落位,点击判定与最终位置不变。实测同一帧内 100 次移动的画布提交由 98 次降到 1 次。
- **已结束分支整体聚合**:只有整条分支全部结束才自动聚合;仍有运行后代、当前查看路径或未知子代理目录的分支保持可见,聚合计数覆盖隐藏的 Agent 后代。
- **四项独立自动规则**:复用设置齿轮与现有偏好存储,分别控制已结束叶子聚合、已结束分支聚合、同一父级至少 3 个空闲队友聚合(workflow 内沿用原规则,也受空闲开关控制),以及 Agent 总数至少 8 个时后台任务抽屉自动收起,默认全部开启。未手动操作时设置即时生效;手动展开或收起始终优先。
- ⚡ **大 Markdown 的 Mermaid 预览不再卡死渲染器(chunk 内测量隔离到沙箱 iframe)**:Mermaid 用 `SVGElement.getBBox()` 量文字,测量节点挂在 `document.body` 上 → 每次测量都刷新整个 DSH 文档布局。真机实测一次 `getBBox` **59–75 ms**(15,418 节点),空 iframe 里只要 **1 ms**;31 张图因此阻塞主线程 >20 s,触发桌面壳看门狗杀渲染器,恢复标签页后循环卡死。现在图表改在隐藏的 `sandbox="allow-scripts"` iframe(blob: 自包含 mermaid UMD + 协议)里渲染,父侧只做 postMessage 收发与 SVG 清洗:**单图 1,500–7,300 ms → 30–104 ms,31 图约 5 s 内完成**,客户端 mermaid chunk 同时从 **7.04 MB → 3.69 MB**。另加共享渲染队列(可见/近视口优先,其余 `requestIdleCallback` 逐张补齐,两次之间让出 16 ms 主线程;**所有图最终都会渲染成图,不再退化为代码块**)与按围栏行数预留高度的占位骨架。设计与实测见 [docs/plans/2026-10-23-mermaid-iframe-isolation.md](docs/plans/2026-10-23-mermaid-iframe-isolation.md)。
### v0.28.0
+4
View File
@@ -4,6 +4,10 @@
>
> 📝 The Chinese [CHANGELOG](./CHANGELOG.md) is the authoritative, item-by-item record; this file carries the English summaries and has historically lagged behind it. Where the two disagree, the Chinese one is current.
### Unreleased
- ⚡ **Mermaid previews of large Markdown documents no longer stall the renderer (layout measurement isolated in a sandboxed iframe)**: mermaid measures label text with `SVGElement.getBBox()` against a node appended to `document.body`, so every measurement flushes the whole DSH document layout — measured on a real desktop host at **59–75 ms per measurement** (15,418 nodes) versus **1 ms** in an empty iframe. A 31-diagram document therefore blocked the main thread for >20 s, tripping the desktop shell's surface watchdog and turning tab restoration into a crash loop. Diagrams now render inside a hidden `sandbox="allow-scripts"` iframe (a self-contained blob: document with the mermaid UMD bundle inlined plus a small postMessage protocol); the parent only sends/receives and sanitizes SVG: **per diagram 1,500–7,300 ms → 30–104 ms, 31 diagrams in ~5 s**, while the client mermaid chunk shrinks from **7.04 MB to 3.69 MB**. A shared render queue (visible/near-viewport diagrams first, the rest filled in on `requestIdleCallback`, 16 ms main-thread yields between renders — **every diagram is still rendered, none degrades to a code block**) and fence-line-sized placeholder skeletons complete the change. Design and measurements: [docs/plans/2026-10-23-mermaid-iframe-isolation.md](docs/plans/2026-10-23-mermaid-iframe-isolation.md).
### v0.29.0
- **GenUI in side chats**: the existing `ctx.betterSidebar` service exposes the opt-in `registerSidechatSurfaceAdapter` for GenUI 0.15.0 to render settled assistant replies. Without a consumer, Markdown rendering stays unchanged.
@@ -0,0 +1,134 @@
# Markdown 预览 Mermaid 图表:布局测量隔离到沙箱 iframe
- 日期:2026-10-23
- 影响面:`src/client/mermaid.tsx`、`src/client/mermaid-frame.ts`(新增)、
`scripts/build-mermaid-frame-asset.mjs`(新增)、`src/client/sidebar.module.css`
- 关联:v0.13.1 引入的 Mermaid 预览(#164)、#341(`suppressErrorRendering`)
## 1. 现象
在 DSH Desktop(Windows,DSH 0.2.1-rc.2,插件 0.28.0)中打开一份约 90 KB、含 31 个
mermaid 围栏的 Markdown(`SYSTEM_ARCHITECTURE.md`)时页面卡死:桌面壳日志出现
```
renderer surface watchdog: page did not respond
terminating unresponsive renderer
unresponsive renderer replaced (reason: crashed, exitCode: 2)
```
后渲染器被杀、页面重载;侧栏恢复上次标签页后再次卡死,形成崩溃循环。
同尺寸、把 mermaid 围栏换成普通代码围栏的文档打开完全正常 → 问题锁定在 Mermaid
预览渲染链路,而不是文档大小或 Markdown 解析。
## 2. 根因(真机实测)
Mermaid 用 `SVGElement.getBBox()` 给每个标签测量文字尺寸(`calculateTextDimensions`
把测点 `<svg>` 追加到 `document.body`)。该测量与**整个宿主文档的布局**共享一个布局树:
| 测量环境 | 一次 `getBBox` | 说明 |
|---|---|---|
| 真实 DSH 窗口(15,418 个 DOM 节点、复杂样式) | **59–75 ms** | 每次测量触发一次文档级样式/布局刷新 |
| 空 iframe 文档 | **1 ms** | 独立、极小的布局树 |
一张图要做几十次测量,因此单图 **1.5–7.3 秒**;旧实现把文档里所有图在挂载时同时
发起渲染(每块一个 React root + `mermaid.render` 并行),31 张图累计让主线程连续
无响应 > 20 秒,超过桌面壳看门狗(5s 探测 / 10s 超时 / 连续 2 次)阈值。
对照实验(同页面内探针,2026-10-23):
- `#root { contain: layout style }` / `contain: strict`:**无改善**(59/62 ms);
- `#root { content-visibility: hidden }`:1 ms,但会隐藏整个界面,不可接受;
- 同源空 iframe 内测量:**1 ms**。
结论:唯一既能保持界面可见、又能去掉测量成本的隔离边界是**独立的 iframe 文档**。
## 3. 方案
### 3.1 自包含的沙箱 iframe(渲染器)
`src/client/mermaid-frame.ts`:
- 首次需要渲染图表时懒创建隐藏 iframe:
`sandbox="allow-scripts"`(**不带 allow-same-origin**,opaque origin,无法访问 GUI
文档),`position:fixed` 移到视口外、`visibility:hidden`;
- `src` 为 `blob:` URL,内容由 `MERMAID_FRAME_HTML` 提供(见 3.2);
- postMessage 协议:
- 父 → 子:`{ type: 'mermaid-render', id, code, theme }`
- 子 → 父:`{ type: 'mermaid-result', id, svg }` / `{ type: 'mermaid-error', id, message }`
- 子就绪:`{ type: 'mermaid-frame-ready' }`
- 单例复用、单请求 30s 超时、就绪 10s 超时;失败自动重建一次,连续失败后该页面
停止重试并让对应图走「错误 + 源码」兜底(仅故障时,不用于正常路径);
- 父侧仍在 `sanitizeSvg()` 之后注入 SVG,安全链路不变。
iframe 内的 iframe 协议(`FRAME_API`)负责 `mermaid.initialize()` 与 `render()`:
`securityLevel: 'strict'`、`htmlLabels: false`、`suppressErrorRendering: true`,
主题随请求传入(`'dark' | 'default'`)。
### 3.2 自包含资产(无 host 路由)
`scripts/build-mermaid-frame-asset.mjs` 用插件自己的 `mermaid` 依赖
(`mermaid/dist/mermaid.min.js`,UMD)与 `FRAME_API` 拼成一个完整 HTML,把两个
`<script>` 内联(`</script` → `<\/script`,其余源码逐字保留),生成
`src/client/mermaid-frame-asset.generated.ts`(`export const MERMAID_FRAME_HTML: string`,
显式 `: string` 注解避免 3.5 MB 字面量进入 `.d.ts`)。
生成文件加入 `.gitignore`,由 `prepare` / `build` / `bundle` / `watch` 在 tsc/vitest/
tsdown 之前生成;git 源安装走 `prepare`,因此同样可用。
选择内联而不是新增 host 路由:
- 插件客户端 chunk 体系(`/sidebar/bundle`)只服务构建期 chunk;
- 新增 frame HTML 路由需要 host 半改动 + 路由测试,且 frame 需要反代前缀安全的 URL;
- 内联后客户端 chunk 是自包含的:**3.69 MB(原 client-mermaid.js 7.04 MB)**,
首次预览仍只加载这一个懒 chunk,没有额外请求;
- 代价:生成/构建多一步;mermaid 版本升级由 `pnpm install` 后的 `prepare` 自动重建。
### 3.3 渲染调度:可见优先 + 空闲补齐 + 占位
`src/client/mermaid.tsx`:
- 删除 chunk 内直接 `mermaid.render` 的旧路径,改为 `renderMermaidDiagram(code, theme)`;
- 模块级共享队列(`requestIdleCallback`,400ms 上限)一次只渲染一张图,两次之间
`setTimeout(16)` 让出主线程(输入、布局、看门狗探针都能插进来);
- 优先级:挂载时在视口附近(或 `IntersectionObserver`,rootMargin 800px 内)的图优先;
不可见/隐藏 tab 的图走空闲队列,**最终全部渲染成图**(不再退化为代码块);
- 卸载、主题切换、围栏变化用 generation 计数取消旧任务;
- 占位骨架 `.mermaidPending` / `.mermaidPendingBar`:按围栏行数预留高度,主题 token、
`prefers-reduced-motion` 下停止动画,图到达时文章不跳动。
## 4. 实测结果(同机、同文档、31 图)
| 指标 | 修复前 | 修复后 |
|---|---|---|
| 单图渲染 | 1,500–7,300 ms | **30–104 ms** |
| 31 图总耗时 | 主线程阻塞 > 20 s,渲染器被杀 | **约 5 s 内空闲队列逐张完成** |
| 首次打开交互 | 卡死/崩溃循环 | 首屏立即可读,可见图先出 |
| watchdog 崩溃 | 必现 | **0 次新增** |
| 客户端 chunk | 7.04 MB | **3.69 MB** |
| 图表显示 | 卡死 / 受旧实现影响 | 全部成图 |
`pnpm typecheck`、`pnpm lint`、`pnpm build`、相关 spec(含新增占位/失败/资产用例)
全绿。
## 5. 已知取舍与后续
- **如果 iframe 加载失败**(极端 CSP/环境限制):对应图显示错误 + 源码,不会退回
主线程慢渲染,也不会静默丢内容;正常路径下图表全部渲染。
- **资产生成是新增构建步骤**:生成文件不提交;`prepare`/`build` 自动生成,缺失时
脚本给出明确报错("run pnpm install first")。
- **可进一步压缩**:把 UMD 换成本项目 rolldown 构建的 minify chunk 可去重依赖
(当前内联 3.4 MB minified UMD,已比原 7.04 MB 非压缩 chunk 小);但需新增
chunk 名与 5 处镜像,超出本修复范围。
- **仍受主线程调度影响**:图多时后台渲染会占用若干秒 CPU,但每次让出主线程,不触发
看门狗;滚动时新进入视口的图会插队。
- **测试限制**:jsdom 无法跑真实 iframe/blob,spec 通过
`setMermaidFrameRendererForTests()` 注入 stub;iframe 行为由真实挂载 lane
(`diagram.md` 冒烟)覆盖。
## 6. 验证清单
- [x] 真机复现(修复前必现)与修复后回归(同一文档,无新增 watchdog)
- [x] 单图/总耗时测量(30–104 ms / ~5 s)
- [x] 占位 → 图替换、失败 → 源码兜底、多围栏全量渲染、跨围栏引用语义
- [x] 生成资产结构(两段内联脚本、严格 safe 转义、strict 配置)
- [x] `pnpm typecheck` / `pnpm lint` / `pnpm build` / `pnpm test` / `check:consumer-types`
+5 -4
View File
@@ -74,12 +74,13 @@
"locale/*.json"
],
"scripts": {
"build": "node -e \"require('node:fs').rmSync('lib',{recursive:true,force:true})\" && tsc -p tsconfig.build.json && tsdown",
"build": "node scripts/build-mermaid-frame-asset.mjs && node -e \"require('node:fs').rmSync('lib',{recursive:true,force:true})\" && tsc -p tsconfig.build.json && tsdown",
"build:asset": "node scripts/build-mermaid-frame-asset.mjs",
"prepublishOnly": "pnpm build",
"typecheck": "tsc --noEmit",
"bundle": "tsdown",
"watch": "tsdown --watch",
"prepare": "tsdown",
"bundle": "node scripts/build-mermaid-frame-asset.mjs && tsdown",
"watch": "node scripts/build-mermaid-frame-asset.mjs && tsdown --watch",
"prepare": "node scripts/build-mermaid-frame-asset.mjs && tsdown",
"test": "vitest run",
"test:windows": "vitest run --maxWorkers=1",
"test:mount": "bash scripts/e2e-mount.sh",
+140
View File
@@ -0,0 +1,140 @@
/**
* Generates `src/client/mermaid-frame-asset.generated.ts`.
*
* The markdown preview renders mermaid diagrams inside a sandboxed iframe
* (see src/client/mermaid-frame.ts): mermaid sizes every label with
* `SVGElement.getBBox()`, and in the live DSH window that forces a layout
* flush of the whole (large, style-heavy) document — measured at ~60-75ms per
* measurement, so one diagram takes seconds and a document with dozens of
* them keeps the renderer busy for minutes. An iframe has its own small
* layout tree: the same measurement costs ~1ms.
*
* The frame must be self-contained (an opaque-origin sandboxed iframe cannot
* fetch parent blob: subresources), so this build step inlines the UMD bundle
* of the plugin's own `mermaid` dependency plus the tiny frame protocol into a
* single HTML document. The document is embedded in the mermaid lazy chunk as
* a string and turned into a blob: URL at runtime.
*
* Runs from `prepare` / `build` / `bundle` / `watch`, so a fresh install (and
* a git-source install, which builds through `prepare`) always has the asset
* before tsc/vitest/tsdown need it.
*/
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import { dirname, join } from 'node:path'
const requireFromRepo = createRequire(import.meta.url)
/**
* Locate mermaid's UMD bundle. Prefer the package subpath; fall back to the
* package root + `dist/` so a restrictive `exports` map cannot break the
* build.
* @returns absolute path to mermaid.min.js.
*/
function mermaidBundlePath() {
const candidates = []
try {
candidates.push(requireFromRepo.resolve('mermaid/dist/mermaid.min.js'))
} catch {
// Subpath not exported: fall through to the package-root candidate.
}
try {
candidates.push(join(dirname(requireFromRepo.resolve('mermaid/package.json')), 'dist/mermaid.min.js'))
} catch {
// Mermaid missing entirely: the explicit error below explains the fix.
}
for (const candidate of candidates) {
if (existsSync(candidate)) return candidate
}
throw new Error(
'cannot locate mermaid/dist/mermaid.min.js — the mermaid dependency is not installed; run pnpm install first',
)
}
const mermaidSource = readFileSync(mermaidBundlePath(), 'utf8')
/** The frame protocol. Runs inside the iframe (window.mermaid is the inlined
* UMD bundle) and posts exactly one result/error per render request. */
const FRAME_API = `(function () {
'use strict';
var seq = 0;
function configure(theme) {
window.mermaid.initialize({
startOnLoad: false,
securityLevel: 'strict',
htmlLabels: false,
suppressErrorRendering: true,
theme: theme === 'dark' ? 'dark' : 'default'
});
}
function render(code, theme) {
configure(theme);
var id = 'dsh-frame-mermaid-' + (++seq);
return window.mermaid.render(id, code).then(function (result) {
return result && typeof result.svg === 'string' ? result.svg : '';
});
}
window.__dshMermaidFrame = { render: render };
if (window.parent !== window) {
window.addEventListener('message', function (event) {
var data = event.data;
if (!data || typeof data !== 'object' || data.type !== 'mermaid-render') return;
render(String(data.code == null ? '' : data.code), data.theme).then(function (svg) {
window.parent.postMessage({ type: 'mermaid-result', id: data.id, svg: svg }, '*');
}).catch(function (error) {
window.parent.postMessage({ type: 'mermaid-error', id: data.id, message: String((error && error.message) || error) }, '*');
});
});
window.parent.postMessage({ type: 'mermaid-frame-ready' }, '*');
}
})();`
/**
* Inline a script body into an HTML `<script>` element. Only `</script` has
* to be neutralized (`<\/script` is the same token to the JS lexer); the rest
* of the source runs verbatim.
* @param source - script source.
* @returns the source, safe to place between `<script>` and `</script>`.
*/
function inlineScript(source) {
return source.replace(/<\/script/gi, '<\\/script')
}
const frameHtml = `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>mermaid frame</title>
<style>
html, body { margin: 0; padding: 0; background: transparent; width: 1200px; }
body { font: 13px/1.5 system-ui, sans-serif; }
</style>
</head>
<body>
<script>${inlineScript(mermaidSource)}</script>
<script>${inlineScript(FRAME_API)}</script>
</body>
</html>
`
/** The generated module. */
const generated = `/**
* GENERATED by scripts/build-mermaid-frame-asset.mjs — do not edit.
*
* Self-contained mermaid iframe document (inline mermaid UMD + frame
* protocol). See src/client/mermaid-frame.ts for why the preview renders
* diagrams inside an iframe at all.
*/
// The explicit \`: string\` annotation keeps the ~3.5 MB literal out of the
// emitted .d.ts (otherwise tsc expands it into the declaration).
export const MERMAID_FRAME_HTML: string = ${JSON.stringify(frameHtml)}
`
const target = new URL('../src/client/mermaid-frame-asset.generated.ts', import.meta.url)
writeFileSync(target, generated)
console.log(
'mermaid frame asset written:',
`${(generated.length / 1024 / 1024).toFixed(2)} MB`,
'(mermaid UMD',
`${(mermaidSource.length / 1024 / 1024).toFixed(2)} MB)`,
)
+169
View File
@@ -0,0 +1,169 @@
/**
* Client half of the isolated mermaid renderer.
*
* Mermaid sizes every label with `SVGElement.getBBox()`. In the live DSH
* window one such measurement costs ~60-75ms (the document is large and
* style-heavy, and the measurement node is appended to its body), so a single
* diagram takes seconds and a document with dozens of them keeps the renderer
* busy for minutes — long enough for the desktop shell's surface watchdog to
* kill the page. An iframe has its own small layout tree: the same measurement
* costs ~1ms, so diagrams render in milliseconds and the host window never
* blocks.
*
* The frame is self-contained (the mermaid UMD bundle and protocol are inlined
* by scripts/build-mermaid-frame-asset.mjs) and sandboxed WITHOUT
* `allow-same-origin`: it runs only our own rendering code, cannot touch the
* GUI document, and needs no host route. It is created lazily on the first
* diagram and reused for every following render on the page.
*/
import { MERMAID_FRAME_HTML } from './mermaid-frame-asset.generated.ts'
export type MermaidTheme = 'dark' | 'default'
/** Frame viewport width: the empty document diagrams are laid out against. */
const FRAME_WIDTH = 1200
const FRAME_HEIGHT = 900
const FRAME_READY_TIMEOUT_MS = 10_000
const FRAME_RENDER_TIMEOUT_MS = 30_000
/** One pending render waiting on the frame's postMessage answer. */
interface PendingRender {
resolve: (svg: string) => void
reject: (error: Error) => void
timer: number
}
const pending = new Map<number, PendingRender>()
let requestSeq = 0
let frame: HTMLIFrameElement | null = null
let frameReady: Promise<void> | null = null
let frameObjectUrl: string | null = null
let messageListenerInstalled = false
/** Set once the frame failed to load twice: stop paying the timeout per diagram. */
let frameUnavailable = false
/** Test seam: jsdom cannot run the real frame asset, so specs replace the
* renderer with a stub. `null` restores the real one. */
let testRenderer: ((code: string, theme: MermaidTheme) => Promise<string>) | null = null
export function setMermaidFrameRendererForTests(
renderer: ((code: string, theme: MermaidTheme) => Promise<string>) | null,
): void {
testRenderer = renderer
}
/** Route the frame's result/error messages to their pending render. */
function installMessageListener(): void {
if (messageListenerInstalled) return
messageListenerInstalled = true
window.addEventListener('message', (event: MessageEvent) => {
const data = event.data as { type?: unknown; id?: unknown; svg?: unknown; message?: unknown } | null
if (data === null || typeof data !== 'object') return
if (data.type !== 'mermaid-result' && data.type !== 'mermaid-error') return
const id = typeof data.id === 'number' ? data.id : -1
const entry = pending.get(id)
if (entry === undefined) return
pending.delete(id)
window.clearTimeout(entry.timer)
if (data.type === 'mermaid-result' && typeof data.svg === 'string') entry.resolve(data.svg)
else entry.reject(new Error(typeof data.message === 'string' ? data.message : 'mermaid frame render failed'))
})
}
/** Drop the current frame (failed load, page teardown) and its blob URL. */
function disposeFrame(): void {
frameReady = null
if (frame !== null) {
frame.remove()
frame = null
}
if (frameObjectUrl !== null) {
URL.revokeObjectURL(frameObjectUrl)
frameObjectUrl = null
}
}
/** Create the hidden frame and resolve once its protocol posted `ready`. */
function ensureFrame(): Promise<void> {
if (frameReady !== null) return frameReady
installMessageListener()
frameReady = new Promise<void>((resolve, reject) => {
const iframe = document.createElement('iframe')
// Opaque-origin sandbox: the frame runs only our inlined mermaid bundle and
// not the host origin's APIs. postMessage is the only bridge.
iframe.setAttribute('sandbox', 'allow-scripts')
iframe.setAttribute('aria-hidden', 'true')
iframe.tabIndex = -1
iframe.style.cssText = `position:fixed;left:-12000px;top:0;width:${FRAME_WIDTH}px;height:${FRAME_HEIGHT}px;border:0;visibility:hidden;pointer-events:none`
let settled = false
const settle = (error?: Error): void => {
if (settled) return
settled = true
window.removeEventListener('message', onReady)
window.clearTimeout(timer)
if (error !== undefined) {
disposeFrame()
reject(error)
return
}
resolve()
}
const onReady = (event: MessageEvent): void => {
if (event.source !== iframe.contentWindow) return
const data = event.data as { type?: unknown } | null
if (data !== null && typeof data === 'object' && data.type === 'mermaid-frame-ready') settle()
}
const timer = window.setTimeout(() => {
settle(new Error('mermaid frame did not become ready'))
}, FRAME_READY_TIMEOUT_MS)
window.addEventListener('message', onReady)
frameObjectUrl = URL.createObjectURL(new Blob([MERMAID_FRAME_HTML], { type: 'text/html' }))
iframe.src = frameObjectUrl
document.body.appendChild(iframe)
frame = iframe
})
return frameReady
}
/** Ask the frame to render one diagram and resolve with the raw SVG markup. */
async function renderInFrame(code: string, theme: MermaidTheme): Promise<string> {
await ensureFrame()
const target = frame?.contentWindow
if (target === null || target === undefined) throw new Error('mermaid frame disappeared')
const id = ++requestSeq
return new Promise<string>((resolve, reject) => {
const timer = window.setTimeout(() => {
pending.delete(id)
reject(new Error('mermaid frame render timed out'))
}, FRAME_RENDER_TIMEOUT_MS)
pending.set(id, { resolve, reject, timer })
target.postMessage({ type: 'mermaid-render', id, code, theme }, '*')
})
}
/**
* Render one mermaid diagram off the host document's layout.
* @param code - the diagram source (one fenced block body).
* @param theme - mermaid theme to render with (follows the color scheme).
* @returns the raw SVG markup (sanitized by the caller before injection).
*/
export async function renderMermaidDiagram(code: string, theme: MermaidTheme): Promise<string> {
if (testRenderer !== null) return testRenderer(code, theme)
if (frameUnavailable) throw new Error('mermaid rendering frame is unavailable')
try {
return await renderInFrame(code, theme)
} catch (_firstError) {
// One retry with a fresh frame covers a transient load failure; a second
// failure marks the frame unusable so later diagrams fail fast (the
// diagram body then shows the error + source instead of a placeholder).
disposeFrame()
try {
return await renderInFrame(code, theme)
} catch (secondError) {
frameUnavailable = true
throw new Error(
`mermaid frame unavailable: ${secondError instanceof Error ? secondError.message : String(secondError)}`,
{ cause: secondError },
)
}
}
}
+166 -41
View File
@@ -27,7 +27,6 @@
import { useCallback, useEffect, useLayoutEffect, useRef, useState, type MouseEvent as ReactMouseEvent } from 'react'
import { createPortal } from 'react-dom'
import { createRoot, type Root } from 'react-dom/client'
import mermaid from 'mermaid'
import { IconCopyOutlineRegular, MarkdownText, writeClipboard } from '@deepseek-ai/dsh-client-ui-primitives'
import { isDarkScheme, subscribeColorScheme } from './theme.ts'
import { markdownTextProps } from './markdown-labels.tsx'
@@ -35,27 +34,100 @@ import { t } from './locales.ts'
import { sanitizeSvg } from './mermaid-sanitize.ts'
import type { MermaidMarkdownProps } from './mermaid-blocks.ts'
import { splitMermaidBlocks } from './mermaid-blocks.ts'
import { renderMermaidDiagram, type MermaidTheme } from './mermaid-frame.ts'
import css from './sidebar.module.css'
/** Monotonic id seed: every render call gets a fresh, document-unique id. */
let mermaidSeq = 0
/** Render queue priorities: a diagram the reader can see goes first, the rest
* render while the browser is idle. */
type MermaidPriority = 0 | 1
/** Configure mermaid for the current color scheme (idempotent). */
function configureMermaid(): void {
mermaid.initialize({
startOnLoad: false,
securityLevel: 'strict',
// Labels as real SVG <text>: mermaid's default htmlLabels renders node
// text inside <foreignObject>, which the sanitizer strips wholesale —
// forcing pure SVG text keeps labels visible and the HTML label channel
// closed (strict already escapes label content).
htmlLabels: false,
// Mermaid 11 renders a large error SVG into document.body before rejecting
// invalid diagrams. The component already has its own error fallback, so
// suppress that global side effect to keep the DSH shell intact.
suppressErrorRendering: true,
theme: isDarkScheme() ? 'dark' : 'default',
})
interface MermaidTask {
priority: MermaidPriority
run: () => Promise<void>
}
/** Pending renders, shared by every mounted preview on the page. */
const mermaidQueue: MermaidTask[] = []
let mermaidPumping = false
/** Incremented when a test tears the queue down; a drain loop from an older
* epoch stops at its next await instead of driving the fresh queue. */
let mermaidQueueEpoch = 0
/** Drop every queued render and detach the current drain loop (test seam:
* module state persists across specs in one vitest file). */
export function resetMermaidRenderQueueForTests(): void {
mermaidQueueEpoch += 1
mermaidQueue.length = 0
mermaidPumping = false
}
/** Run a callback once the main thread is idle (bounded, so diagrams cannot
* starve forever while the page stays busy). */
function whenIdle(callback: () => void): void {
if (typeof requestIdleCallback === 'function') {
requestIdleCallback(() => { callback() }, { timeout: 400 })
return
}
setTimeout(callback, 0)
}
/**
* Drain the render queue one diagram at a time.
*
* Rendering every fence of a document in one commit (the behaviour this
* replaced) could hold the main thread for minutes on diagram-heavy documents
* — long enough for the desktop shell's surface watchdog to declare the page
* unresponsive and kill it. The queue interleaves a visible diagram ahead of
* the background ones and gives the browser (input, layout, the watchdog's
* probe) a turn between two renders, so a document with dozens of diagrams
* stays interactive and every diagram still ends up rendered.
*/
async function drainMermaidQueue(): Promise<void> {
if (mermaidPumping) return
mermaidPumping = true
const epoch = mermaidQueueEpoch
try {
while (epoch === mermaidQueueEpoch && mermaidQueue.length > 0) {
mermaidQueue.sort((a, b) => a.priority - b.priority)
const task = mermaidQueue.shift()
if (task === undefined) break
await new Promise<void>((resolve) => { whenIdle(resolve) })
if (epoch !== mermaidQueueEpoch) break
try {
await task.run()
} catch (error) {
// One broken fence must not stall the queue behind it.
console.error('[dsh-better-sidebar] mermaid render failed', error)
}
await new Promise<void>((resolve) => { setTimeout(resolve, 16) })
}
} finally {
if (epoch === mermaidQueueEpoch) mermaidPumping = false
}
}
/** Queue one diagram render; {@link drainMermaidQueue} runs it. */
function pushMermaidTask(priority: MermaidPriority, run: () => Promise<void>): void {
mermaidQueue.push({ priority, run })
void drainMermaidQueue()
}
/** True when the block is at most about one viewport away from the visible
* area. A mounted-but-hidden body (parked tab, closed drawer) has a zero box;
* it is treated as off-screen so its diagrams take the idle path. */
function isNearViewport(node: HTMLElement): boolean {
const rect = node.getBoundingClientRect()
if (rect.width === 0 && rect.height === 0) return false
const margin = window.innerHeight * 1.25
return rect.bottom > -margin && rect.top < window.innerHeight + margin
}
/** Rough first-paint height for the placeholder, derived from the fence's line
* count. Reserving some height keeps the article from jumping under the
* reader's cursor when the diagram arrives. */
function placeholderHeight(code: string): number {
const lines = code.split('\n').length
return Math.min(480, Math.max(120, lines * 14))
}
/** First lines of a mermaid error (its dumps are huge; the head explains). */
@@ -228,33 +300,74 @@ function MermaidDiagram({ code }: { code: string }): React.ReactNode {
/** The cloned svg shown in the zoom modal (null = closed). */
const [zoomSvg, setZoomSvg] = useState<SVGSVGElement | null>(null)
const copyTimer = useRef<number | undefined>(undefined)
/** The wrapper the visibility observer watches; also the placeholder host. */
const wrapRef = useRef<HTMLDivElement>(null)
/** Bumped whenever the source/theme changes or the component unmounts; a
* render result belonging to an older generation is dropped. */
const generationRef = useRef(0)
/** Generation whose render is already queued (one task per generation). */
const scheduledRef = useRef(-1)
useEffect(() => subscribeColorScheme(() => { setDark(isDarkScheme()) }), [])
/** Render the current source and publish the sanitized SVG. */
const renderNow = useCallback(async (): Promise<void> => {
const generation = generationRef.current
const theme: MermaidTheme = dark ? 'dark' : 'default'
try {
const rendered = await renderMermaidDiagram(code, theme)
if (generation !== generationRef.current) return
const clean = sanitizeSvg(rendered)
if (clean === '') {
// Parse/sanitize rejection: never pass the raw string through.
setError(t('mermaidError'))
return
}
setSvg(clean)
} catch (reason) {
if (generation !== generationRef.current) return
setError(summarizeError(reason))
}
}, [code, dark])
/** Queue one render of the current generation: a visible diagram goes
* first, the rest render on the idle path. */
const scheduleRender = useCallback((priority: MermaidPriority): void => {
const generation = generationRef.current
if (scheduledRef.current === generation) return
scheduledRef.current = generation
pushMermaidTask(priority, async () => {
if (generation !== generationRef.current) return
await renderNow()
})
}, [renderNow])
// A new source or theme invalidates what is on screen and schedules a render.
useEffect(() => {
let cancelled = false
generationRef.current += 1
scheduledRef.current = -1
setSvg(null)
setError(null)
if (code.trim() === '') return () => { cancelled = true }
configureMermaid()
const id = `dsh-md-mermaid-${mermaidSeq += 1}`
mermaid.render(id, code)
.then(({ svg: rendered }) => {
if (cancelled) return
const clean = sanitizeSvg(rendered)
if (clean === '') {
// Parse/sanitize rejection: never pass the raw string through.
setError(t('mermaidError'))
return
}
setSvg(clean)
})
.catch((reason: unknown) => {
if (cancelled) return
setError(summarizeError(reason))
})
return () => { cancelled = true }
}, [code, dark])
if (code.trim() === '') return
const node = wrapRef.current
scheduleRender(node !== null && isNearViewport(node) ? 0 : 1)
}, [code, dark, scheduleRender])
// A placeholder that scrolls into view jumps ahead of the background queue.
useEffect(() => {
const node = wrapRef.current
if (node === null || typeof IntersectionObserver === 'undefined') return
const observer = new IntersectionObserver((entries) => {
if (!entries.some((entry) => entry.isIntersecting)) return
observer.disconnect()
scheduleRender(0)
}, { rootMargin: '800px 0px' })
observer.observe(node)
return () => { observer.disconnect() }
}, [scheduleRender])
// Unmounting the preview drops renders that are still queued.
useEffect(() => () => { generationRef.current += 1 }, [])
const onCopy = useCallback(() => {
if (copied) return
@@ -279,7 +392,7 @@ function MermaidDiagram({ code }: { code: string }): React.ReactNode {
}
return (
<div className={css.mermaidWrap}>
<div className={css.mermaidWrap} ref={wrapRef}>
<div className={css.mermaidHeader}>
<span className={css.mermaidInfo}>mermaid</span>
<button
@@ -293,6 +406,18 @@ function MermaidDiagram({ code }: { code: string }): React.ReactNode {
<span>{copied ? t('copied') : t('copy')}</span>
</button>
</div>
{svg === null && error === null && (
<div
className={css.mermaidPending}
style={{ minHeight: `${placeholderHeight(code)}px` }}
data-mermaid-pending
aria-busy="true"
>
<span className={css.mermaidPendingBar} />
<span className={css.mermaidPendingBar} />
<span className={css.mermaidPendingBar} />
</div>
)}
{error !== null && <div className={css.mermaidError} title={error}>{t('mermaidError')}</div>}
{svg !== null && (
<div
+49
View File
@@ -1921,6 +1921,55 @@ body[data-dsh-sidebar-dragging] .bottomPanel {
height: auto;
}
/* Lazy render placeholder: the fence's diagram is queued and swaps in as soon
as the render queue reaches it (visible diagrams first, the rest while the
browser is idle). The min-height comes from the fence's line count so the
article does not jump under the reader's cursor when the diagram arrives. */
.mermaidPending {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 10px;
padding: 18px 24px;
}
.mermaidPendingBar {
display: block;
width: min(320px, 70%);
height: 10px;
border-radius: 5px;
background: var(--dsw-alias-bg-layer-2);
animation: mermaidPendingPulse 1.4s ease-in-out infinite;
}
.mermaidPendingBar:nth-child(2) {
width: min(240px, 55%);
animation-delay: 0.15s;
}
.mermaidPendingBar:nth-child(3) {
width: min(160px, 40%);
animation-delay: 0.3s;
}
@keyframes mermaidPendingPulse {
0%,
100% {
opacity: 0.45;
}
50% {
opacity: 1;
}
}
@media (prefers-reduced-motion: reduce) {
.mermaidPendingBar {
animation: none;
}
}
.mermaidError {
padding: 6px 10px;
border-bottom: 1px solid var(--dsw-alias-border-l1);
+29
View File
@@ -0,0 +1,29 @@
/**
* The generated mermaid frame asset must stay a single self-contained HTML
* document: the preview loads it into an opaque-origin sandboxed iframe, which
* can fetch no subresources, and a raw `</script` inside either inlined script
* would close the element early and corrupt the frame.
*/
import { describe, expect, it } from 'vitest'
import { MERMAID_FRAME_HTML } from '../src/client/mermaid-frame-asset.generated.ts'
describe('mermaid frame asset', () => {
it('is a self-contained HTML document with the frame protocol', () => {
expect(MERMAID_FRAME_HTML.startsWith('<!doctype html>')).toBe(true)
expect(MERMAID_FRAME_HTML).toContain('window.__dshMermaidFrame')
expect(MERMAID_FRAME_HTML).toContain('mermaid-frame-ready')
expect(MERMAID_FRAME_HTML).toContain('dsh-frame-mermaid-')
})
it('inlines exactly two script bodies (mermaid UMD + frame protocol)', () => {
// Every `</script` inside the inlined sources is escaped as `<\/script`,
// so the document carries exactly the two structural closing tags.
expect(MERMAID_FRAME_HTML.match(/<\/script>/gi)?.length).toBe(2)
})
it('carries the strict mermaid configuration used by the preview', () => {
expect(MERMAID_FRAME_HTML).toContain("securityLevel: 'strict'")
expect(MERMAID_FRAME_HTML).toContain('htmlLabels: false')
expect(MERMAID_FRAME_HTML).toContain('suppressErrorRendering: true')
})
})
+91 -20
View File
@@ -2,11 +2,12 @@
* MermaidMarkdown architecture spec: the preview renders the WHOLE document
* through one MarkdownText pass (cross-fence reference-style links must
* resolve — the P1 regression from the CR), then swaps every rendered
* mermaid CodeBlock for a diagram. mermaid is mocked so the swap + semantics
* are asserted without pulling the real layout engine into jsdom.
* mermaid CodeBlock for a diagram. The actual mermaid layout engine runs in
* the isolated iframe (see mermaid-frame.ts), so the specs inject a stub
* renderer instead of pulling mermaid into jsdom.
*/
// @vitest-environment jsdom
import { describe, expect, it, vi, beforeEach } from 'vitest'
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { createElement } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { act } from 'react-dom/test-utils'
@@ -15,17 +16,13 @@ import { act } from 'react-dom/test-utils'
import { setupReactAct } from './test-utils.ts'
setupReactAct()
vi.mock('mermaid', () => ({
default: {
initialize: vi.fn(),
render: async () => ({
svg: '<svg xmlns="http://www.w3.org/2000/svg"><text>MOCK-DIAGRAM</text></svg>',
}),
},
}))
import { MermaidMarkdown, resetMermaidRenderQueueForTests } from '../src/client/mermaid.tsx'
import { setMermaidFrameRendererForTests, type MermaidTheme } from '../src/client/mermaid-frame.ts'
import mermaid from 'mermaid'
import { MermaidMarkdown } from '../src/client/mermaid.tsx'
/** The stub renderer the specs install; each test clears its call log. */
const renderDiagram = vi.fn(async (_code: string, _theme: MermaidTheme) => (
'<svg xmlns="http://www.w3.org/2000/svg"><text>MOCK-DIAGRAM</text></svg>'
))
const codeLabels = {
copyLabel: 'Copy', copiedLabel: 'Copied', codeLabel: 'Code block', wrapLabel: 'Wrap lines', unwrapLabel: 'Do not wrap lines',
@@ -37,7 +34,7 @@ async function renderMarkdown(text: string): Promise<{ container: HTMLElement; r
const root = createRoot(container)
await act(async () => {
root.render(createElement(MermaidMarkdown, { text, codeLabels }))
// Let the mocked mermaid.render promise settle inside the act scope.
// Let the queued render + its state update settle inside the act scope.
await new Promise(resolve => { setTimeout(resolve, 0) })
})
return { container, root }
@@ -47,25 +44,98 @@ async function unmount(root: Root): Promise<void> {
await act(async () => { root.unmount() })
}
/**
* Wait until `check` returns a truthy value. Diagram rendering is queued (one
* render at a time, idle slots between them — the whole point of the queue), so
* a swap lands asynchronously instead of in the mount commit.
*/
async function waitFor<T>(check: () => T | null | false, timeoutMs = 3000): Promise<T> {
const startedAt = Date.now()
for (;;) {
const value = check()
if (value) return value
if (Date.now() - startedAt > timeoutMs) throw new Error('timed out waiting for the diagram render')
await act(async () => { await new Promise(resolve => { setTimeout(resolve, 10) }) })
}
}
beforeEach(() => {
document.body.innerHTML = ''
renderDiagram.mockClear()
setMermaidFrameRendererForTests(renderDiagram)
})
afterEach(() => {
setMermaidFrameRendererForTests(null)
resetMermaidRenderQueueForTests()
})
describe('MermaidMarkdown', () => {
it('swaps the mermaid code block for a rendered diagram', async () => {
const { container, root } = await renderMarkdown('```mermaid\ngraph TD\n A-->B\n```')
const diagram = container.querySelector('[data-mermaid-diagram] svg')
const diagram = await waitFor(() => container.querySelector('[data-mermaid-diagram] svg'))
expect(diagram, 'the mermaid fence must be swapped for a diagram').not.toBeNull()
expect(diagram?.textContent).toContain('MOCK-DIAGRAM')
await unmount(root)
})
it('suppresses Mermaid global error rendering', async () => {
vi.mocked(mermaid.initialize).mockClear()
it('renders with the current scheme theme through the isolated renderer', async () => {
const { root } = await renderMarkdown('```mermaid\ngraph TD\n A-->B\n```')
expect(mermaid.initialize).toHaveBeenCalledWith(expect.objectContaining({
suppressErrorRendering: true,
}))
await waitFor(() => renderDiagram.mock.calls.length > 0)
expect(renderDiagram).toHaveBeenCalledWith(expect.stringContaining('graph TD'), 'default')
await unmount(root)
})
it('shows a sized placeholder while the render is queued, then swaps it out', async () => {
let release: ((svg: string) => void) | null = null
setMermaidFrameRendererForTests(() => new Promise<string>((resolve) => { release = resolve }))
const { container, root } = await renderMarkdown('```mermaid\ngraph TD\n A-->B\n```')
const placeholder = await waitFor(() => container.querySelector<HTMLElement>('[data-mermaid-pending]'))
expect(placeholder, 'a diagram placeholder is shown while the render is queued').not.toBeNull()
expect(placeholder.style.minHeight, 'the placeholder reserves height so the article does not jump').not.toBe('')
// The queue starts the render on the next idle slot; release it only after
// the stub renderer was actually invoked.
await waitFor(() => (release === null ? null : true))
await act(async () => {
release?.('<svg xmlns="http://www.w3.org/2000/svg"><text>LATE-DIAGRAM</text></svg>')
await new Promise(resolve => { setTimeout(resolve, 30) })
})
await waitFor(() => container.querySelector('[data-mermaid-diagram] svg'))
expect(container.querySelector('[data-mermaid-pending]'), 'the placeholder is gone once the diagram is in').toBeNull()
await unmount(root)
})
it('falls back to the fence source when the renderer fails', async () => {
setMermaidFrameRendererForTests(async () => { throw new Error('boom') })
const { container, root } = await renderMarkdown('```mermaid\ngraph TD\n A-->B\n```')
const source = await waitFor(() => container.querySelector('pre code'))
expect(source?.textContent, 'a failed render keeps the source visible').toContain('graph TD')
expect(container.querySelector('[data-mermaid-diagram]'), 'no diagram is injected for a failed render').toBeNull()
await unmount(root)
})
it('drains every diagram of a multi-fence document', async () => {
const text = [
'```mermaid',
'graph TD',
' A --> B',
'```',
'',
'prose between fences',
'',
'```mermaid',
'graph LR',
' C --> D',
'```',
'',
'```mermaid',
'sequenceDiagram',
' A->>B: hi',
'```',
].join('\n')
const { container, root } = await renderMarkdown(text)
await waitFor(() => container.querySelectorAll('[data-mermaid-diagram] svg').length >= 3 && true)
expect(container.querySelectorAll('[data-mermaid-diagram] svg').length, 'every fence must render, none may stay a code block').toBe(3)
await unmount(root)
})
@@ -84,6 +154,7 @@ describe('MermaidMarkdown', () => {
const link = container.querySelector('a[href="https://example.com"]')
expect(link, 'the definition after the fence must resolve the link before it').not.toBeNull()
expect(link?.textContent).toContain('before')
await waitFor(() => container.querySelector('[data-mermaid-diagram] svg'))
expect(container.querySelector('[data-mermaid-diagram] svg'), 'the diagram must still swap in').not.toBeNull()
await unmount(root)
})
+3 -2
View File
@@ -263,14 +263,15 @@ const TIMER_LEDGER: Array<{ file: string; gate: string; why: string }> = [
},
]
/** `src/client` 下的 .ts/.tsx(跳过惰性 chunk 目录:它们不是常驻面)。 */
/** `src/client` 下的 .ts/.tsx(跳过惰性 chunk 目录:它们不是常驻面;跳过
* `*.generated.ts`:构建产出的资产(如内联的 mermaid UMD)不是手写源码)。 */
function clientSources(dir: string, out: string[] = []): string[] {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const path = join(dir, entry.name)
if (entry.isDirectory()) {
if (entry.name === 'chunks') continue
clientSources(path, out)
} else if (/\.tsx?$/.test(entry.name)) {
} else if (/\.tsx?$/.test(entry.name) && !entry.name.endsWith('.generated.ts')) {
out.push(path)
}
}