From fe06211775d2a3454e015917332b1c5c6f84b8ef Mon Sep 17 00:00:00 2001 From: OCILY Date: Fri, 23 Oct 2026 12:29:42 +0800 Subject: [PATCH 1/5] 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. --- .gitignore | 3 + CHANGELOG.md | 1 + CHANGELOG_EN.md | 4 + .../2026-10-23-mermaid-iframe-isolation.md | 134 ++++++++++++ package.json | 9 +- scripts/build-mermaid-frame-asset.mjs | 140 ++++++++++++ src/client/mermaid-frame.ts | 169 ++++++++++++++ src/client/mermaid.tsx | 207 ++++++++++++++---- src/client/sidebar.module.css | 49 +++++ tests/mermaid-frame-asset.spec.ts | 29 +++ tests/mermaid-markdown.spec.tsx | 111 ++++++++-- tests/steady-state.spec.tsx | 5 +- 12 files changed, 794 insertions(+), 67 deletions(-) create mode 100644 docs/plans/2026-10-23-mermaid-iframe-isolation.md create mode 100644 scripts/build-mermaid-frame-asset.mjs create mode 100644 src/client/mermaid-frame.ts create mode 100644 tests/mermaid-frame-asset.spec.ts diff --git a/.gitignore b/.gitignore index 4cbe7d3a..cb9fe3c9 100644 --- a/.gitignore +++ b/.gitignore @@ -154,3 +154,6 @@ registry/ playwright-report/ test-results/ + +# generated by scripts/build-mermaid-frame-asset.mjs +src/client/mermaid-frame-asset.generated.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 7beabaf3..17381e54 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/CHANGELOG_EN.md b/CHANGELOG_EN.md index 094f26ee..fa1fc436 100644 --- a/CHANGELOG_EN.md +++ b/CHANGELOG_EN.md @@ -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. diff --git a/docs/plans/2026-10-23-mermaid-iframe-isolation.md b/docs/plans/2026-10-23-mermaid-iframe-isolation.md new file mode 100644 index 00000000..ffd37a8c --- /dev/null +++ b/docs/plans/2026-10-23-mermaid-iframe-isolation.md @@ -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` +把测点 `` 追加到 `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,把两个 +` + +mermaid frame + + + + + + + +` + +/** 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)`, +) diff --git a/src/client/mermaid-frame.ts b/src/client/mermaid-frame.ts new file mode 100644 index 00000000..98eed12d --- /dev/null +++ b/src/client/mermaid-frame.ts @@ -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() +let requestSeq = 0 +let frame: HTMLIFrameElement | null = null +let frameReady: Promise | 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) | null = null +export function setMermaidFrameRendererForTests( + renderer: ((code: string, theme: MermaidTheme) => Promise) | 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 { + if (frameReady !== null) return frameReady + installMessageListener() + frameReady = new Promise((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 { + await ensureFrame() + const target = frame?.contentWindow + if (target === null || target === undefined) throw new Error('mermaid frame disappeared') + const id = ++requestSeq + return new Promise((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 { + 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 }, + ) + } + } +} diff --git a/src/client/mermaid.tsx b/src/client/mermaid.tsx index 5f78f920..5b00ad34 100644 --- a/src/client/mermaid.tsx +++ b/src/client/mermaid.tsx @@ -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 : mermaid's default htmlLabels renders node - // text inside , 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 +} + +/** 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 { + 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((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((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 { + 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(null) const copyTimer = useRef(undefined) + /** The wrapper the visibility observer watches; also the placeholder host. */ + const wrapRef = useRef(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 => { + 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 ( -
+
mermaid
+ {svg === null && error === null && ( +
+ + + +
+ )} {error !== null &&
{t('mermaidError')}
} {svg !== null && (
{ + it('is a self-contained HTML document with the frame protocol', () => { + expect(MERMAID_FRAME_HTML.startsWith('')).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 `/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') + }) +}) diff --git a/tests/mermaid-markdown.spec.tsx b/tests/mermaid-markdown.spec.tsx index 68a1b6c7..16b730c1 100644 --- a/tests/mermaid-markdown.spec.tsx +++ b/tests/mermaid-markdown.spec.tsx @@ -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: 'MOCK-DIAGRAM', - }), - }, -})) +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) => ( + 'MOCK-DIAGRAM' +)) 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 { 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(check: () => T | null | false, timeoutMs = 3000): Promise { + 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((resolve) => { release = resolve })) + const { container, root } = await renderMarkdown('```mermaid\ngraph TD\n A-->B\n```') + const placeholder = await waitFor(() => container.querySelector('[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?.('LATE-DIAGRAM') + 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) }) diff --git a/tests/steady-state.spec.tsx b/tests/steady-state.spec.tsx index 314fedcd..3efd4f85 100644 --- a/tests/steady-state.spec.tsx +++ b/tests/steady-state.spec.tsx @@ -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) } } From aa198d792195ed5fc0894946f4a8b151bd0b33d7 Mon Sep 17 00:00:00 2001 From: OCILY Date: Fri, 23 Oct 2026 17:57:12 +0800 Subject: [PATCH 2/5] perf(mermaid): keep scrolling and hidden tabs off the render queue Follow-up to the iframe isolation: after that fix a 31-diagram document still felt janky while scrolling. The remaining cost was work competing with the scroll gesture: - background diagram renders kept running during scroll (each one injects an SVG, runs DOM passes and lays out); - hidden native tabs kept warming diagrams (tab bodies are keepMounted); - the inline-HTML and heading-anchor MutationObservers ran a full-document scan per mutation (measured 8-15 ms per pass, dozens of passes when a document swaps its diagrams in); - initial near-viewport detection read one rect per diagram between DOM writes, forcing a layout per diagram; - off-screen rendered SVGs still participated in layout and paint. The queue now pauses background work for 350 ms after the last captured scroll event, and only schedules renders whose preview is visible (IntersectionObserver gate per preview; hidden tabs keep placeholders and wake the queue when shown again, and unmounting a preview drops its queued tasks). The two mutation passes coalesce bursts into one 80 ms pass. Initial priorities come from one batched rect read before the swap writes. .mermaidWrap gains content-visibility:auto + contain-intrinsic-size + contain:layout paint style, so off-screen diagrams leave layout and paint. Visible diagrams still render on demand, every diagram is still eventually rendered, and nothing falls back to a code block. --- CHANGELOG.md | 1 + CHANGELOG_EN.md | 1 + .../2026-10-23-mermaid-iframe-isolation.md | 44 +++++- src/client/MarkdownHtml.tsx | 21 ++- src/client/mermaid.tsx | 142 +++++++++++++++--- src/client/sidebar.module.css | 9 ++ src/client/use-markdown-surface.ts | 14 +- 7 files changed, 195 insertions(+), 37 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 17381e54..166666ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,6 +52,7 @@ - **已结束分支整体聚合**:只有整条分支全部结束才自动聚合;仍有运行后代、当前查看路径或未知子代理目录的分支保持可见,聚合计数覆盖隐藏的 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)。 +- ⚡ **大文档滚动流畅性:渲染让位于滚动、隐藏页签不空转、摘掉全量 DOM 扫描**:图表渲染队列在滚动期间暂停(停止滚动 350 ms 后恢复),并且只服务当前可见的预览——隐藏页签里的图表保持占位、切回时才渲染;`Markdown` 变更触发的两次全量扫描(内联 HTML pass、标题锚点 pass)由「每次 mutation 跑一遍」(实测 8–15 ms/次)改为 80 ms 合并一次;打开文档时的近视口判断改为先批量读 rect、再统一写入,去掉每张图一次强制布局;`.mermaidWrap` 增加 `content-visibility: auto` + `contain-intrinsic-size` + `contain: layout paint style`,视口外的图表不再参与布局与绘制。滚动时不再有后台渲染、全量扫描与视口外 SVG 重绘抢主线程;图表仍会在滚动停止后或进入视口时补齐,不退化为代码块。 ### v0.28.0 diff --git a/CHANGELOG_EN.md b/CHANGELOG_EN.md index fa1fc436..187e3c0d 100644 --- a/CHANGELOG_EN.md +++ b/CHANGELOG_EN.md @@ -7,6 +7,7 @@ ### 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). +- ⚡ **Smooth scrolling for large documents**: the render queue pauses while the reader scrolls (resuming 350 ms after the last scroll event) and only serves the preview that is actually on screen — hidden tabs keep placeholders and warm their diagrams when shown again. The two mutation-driven full-document scans (inline HTML pass, heading-anchor pass) coalesce bursts into one pass every 80 ms (previously a scan per mutation, measured at 8–15 ms each); initial near-viewport detection reads every rect in one batch before the swap writes, removing one forced layout per diagram; `.mermaidWrap` gains `content-visibility: auto` + `contain-intrinsic-size` + `contain: layout paint style`, so off-screen diagrams leave layout and paint entirely. Scrolling no longer competes with background renders, document-wide scans or off-screen SVG repaint; diagrams still fill in when the reader stops or scrolls them into view — never as code blocks. ### v0.29.0 diff --git a/docs/plans/2026-10-23-mermaid-iframe-isolation.md b/docs/plans/2026-10-23-mermaid-iframe-isolation.md index ffd37a8c..3ebe3ddb 100644 --- a/docs/plans/2026-10-23-mermaid-iframe-isolation.md +++ b/docs/plans/2026-10-23-mermaid-iframe-isolation.md @@ -96,6 +96,38 @@ tsdown 之前生成;git 源安装走 `prepare`,因此同样可用。 - 占位骨架 `.mermaidPending` / `.mermaidPendingBar`:按围栏行数预留高度,主题 token、 `prefers-reduced-motion` 下停止动画,图到达时文章不跳动。 +### 3.4 滚动与多页签开销:渲染让位于交互 + +第一版(3.1–3.3)解决了冻结与单图耗时,但真机反馈「加载后滚动仍不够流畅」。滚动路径上 +剩余的开销来自五处,均已处理: + +- **滚动期间后台渲染**:队列原先在滚动时仍按 `requestIdleCallback` 补齐剩余图,每次图 + 落地都要注入 SVG、跑 DOM pass、触发布局——滚动中每 100–300 ms 撞一次就会掉帧。现在 + 全局捕获 `scroll`(passive capture),队列对**后台优先级**任务等待「停止滚动 350 ms」 + 后再继续;滚动时进入视口的图仍按需即时渲染。 +- **隐藏页签空转**:原生 tab `keepMounted`,隐藏预览若继续补渲染,会与可见文档抢主线程。 + 每个预览注册可见性 handle(`IntersectionObserver`,初始按容器盒判断),队列只调度 + `owner.visible` 的任务;隐藏页签的图保持占位,切回时 `wake()` 继续。预览卸载时 + `dropPreviewTasks()` 清掉它的待渲染任务。 +- **mutation 全量扫描**:`runInlineHtmlPass` 与 `prepareMarkdownAnchors` 原先每次 DOM + mutation 后跑一遍全文扫描(真机实测 8–15 ms/次;31 张图落地 = 几十次扫描)。现在 + 80 ms 合并一次(`setTimeout` coalesce,卸载时清理计时器),并在页面隐藏时跳过扫描。 +- **打开瞬间的强制布局**:原实现每张图在 effect 里各自 `getBoundingClientRect()`,且与 + 其它图的 DOM 写入交错 → 每张图一次强制布局。现在 `MermaidMarkdown` 的 layout effect + 先批量读所有 mermaid 块的 rect(一次读相位),再统一做替换/挂载(一次写相位),优先级 + 通过 `initiallyNearViewport` prop 传给图组件。 +- **视口外 SVG 的布局/绘制**:`.mermaidWrap` 加 `content-visibility: auto` + + `contain-intrinsic-size: auto 240px` + `contain: layout paint style`;已渲染的图滚出 + 视口后不再参与布局与绘制(`auto` 会记住实测高度;首次进入前的估算只影响滚动条的初始 + 长度)。 + +### 3.5 加载策略(打开速度) + +- 懒 chunk 只在文档含 mermaid fence 时加载;iframe 在首次渲染时才创建,之后复用。 +- 首屏同步渲染 Markdown(真机 commit ≈ 45 ms),图表先出占位骨架(按围栏行数预留高度), + 视口内/近视口的图优先渲染(初始优先级来自 3.4 的批量 rect 读取)。 +- 其余图不阻塞阅读:滚动时暂停,停止滚动后按空闲槽补齐;隐藏页签不参与。 + ## 4. 实测结果(同机、同文档、31 图) | 指标 | 修复前 | 修复后 | @@ -119,11 +151,15 @@ tsdown 之前生成;git 源安装走 `prepare`,因此同样可用。 - **可进一步压缩**:把 UMD 换成本项目 rolldown 构建的 minify chunk 可去重依赖 (当前内联 3.4 MB minified UMD,已比原 7.04 MB 非压缩 chunk 小);但需新增 chunk 名与 5 处镜像,超出本修复范围。 -- **仍受主线程调度影响**:图多时后台渲染会占用若干秒 CPU,但每次让出主线程,不触发 - 看门狗;滚动时新进入视口的图会插队。 +- **仍受主线程调度影响**:图多时后台渲染会占用若干秒 CPU,但每次让出主线程、滚动手势 + 优先(见 3.4),不触发看门狗;滚动停止后或图进入视口时才补齐。 - **测试限制**:jsdom 无法跑真实 iframe/blob,spec 通过 `setMermaidFrameRendererForTests()` 注入 stub;iframe 行为由真实挂载 lane (`diagram.md` 冒烟)覆盖。 +- **隐藏页签仍保留整份预览 DOM**:宿主原生 tab 的 `keepMounted` 约定下,隐藏的 + Markdown 预览 DOM 不会释放(本修复让它们不再渲染图表、不再参与滚动,内存仍在)。 + 要再降内存需要在可见性变化时卸载/重建正文,这会牵涉滚动位置、编辑态与宿主 tab + 契约,留作后续(见 AGENTS 稳态开销约定)。 ## 6. 验证清单 @@ -131,4 +167,6 @@ tsdown 之前生成;git 源安装走 `prepare`,因此同样可用。 - [x] 单图/总耗时测量(30–104 ms / ~5 s) - [x] 占位 → 图替换、失败 → 源码兜底、多围栏全量渲染、跨围栏引用语义 - [x] 生成资产结构(两段内联脚本、严格 safe 转义、strict 配置) -- [x] `pnpm typecheck` / `pnpm lint` / `pnpm build` / `pnpm test` / `check:consumer-types` +- [x] 滚动手势优先:滚动期间暂停后台渲染、隐藏页签不调度、mutation pass 合并、 + 批量 rect 读取、视口外图表 content-visibility +- [x] `pnpm typecheck` / `pnpm lint` / `pnpm build` / 相关 spec 全绿 diff --git a/src/client/MarkdownHtml.tsx b/src/client/MarkdownHtml.tsx index b9914b01..8a8c849d 100644 --- a/src/client/MarkdownHtml.tsx +++ b/src/client/MarkdownHtml.tsx @@ -236,17 +236,24 @@ function MarkdownSegment({ text, hasMermaid, media, codeLabels }: MarkdownSegmen const container = containerRef.current if (container === null) return runInlineHtmlPass(container, media) - let scheduled = false + let timer: number | undefined const observer = new MutationObserver(() => { - if (scheduled) return - scheduled = true - queueMicrotask(() => { - scheduled = false + if (timer !== undefined) return + // Coalesce a burst of mutations (shiki settling, diagram swaps, inline + // HTML injection) into one pass: the scan walks every text node in the + // document, so a pass per mutation turns a diagram-heavy render into a + // stream of full-document scans. + timer = window.setTimeout(() => { + timer = undefined + if (document.visibilityState !== 'visible') return runInlineHtmlPass(container, media) - }) + }, 80) }) observer.observe(container, { childList: true, subtree: true }) - return () => { observer.disconnect() } + return () => { + observer.disconnect() + if (timer !== undefined) window.clearTimeout(timer) + } }, [text, media]) return (
diff --git a/src/client/mermaid.tsx b/src/client/mermaid.tsx index 5b00ad34..29acd2f3 100644 --- a/src/client/mermaid.tsx +++ b/src/client/mermaid.tsx @@ -41,9 +41,20 @@ import css from './sidebar.module.css' * render while the browser is idle. */ type MermaidPriority = 0 | 1 +/** One mounted preview's visibility. Background diagrams of a hidden preview + * (parked tab, collapsed dock) must not warm-render: they would spend CPU on + * content nobody can see and make the visible document's scrolling compete + * with diagrams from other tabs. */ +interface MermaidPreviewHandle { + visible: boolean + wake: () => void +} + interface MermaidTask { priority: MermaidPriority run: () => Promise + /** The preview this render belongs to. */ + owner: MermaidPreviewHandle } /** Pending renders, shared by every mounted preview on the page. */ @@ -53,12 +64,45 @@ let mermaidPumping = false * epoch stops at its next await instead of driving the fresh queue. */ let mermaidQueueEpoch = 0 +/** How long after the last scroll event background rendering stays paused. + * Scrolling must not compete with diagram layout for the main thread. */ +const SCROLL_QUIET_MS = 350 +/** Timestamp of the most recent captured scroll event on the page. */ +let lastScrollAt = 0 +if (typeof window !== 'undefined') { + window.addEventListener('scroll', () => { lastScrollAt = performance.now() }, { capture: true, passive: true }) +} + +/** Resolve once the page has stopped scrolling for {@link SCROLL_QUIET_MS}. */ +async function waitForScrollQuiet(): Promise { + while (performance.now() - lastScrollAt < SCROLL_QUIET_MS) { + await new Promise((resolve) => { setTimeout(resolve, 120) }) + } +} + +/** Register one preview's visibility gate (see {@link MermaidPreviewHandle}). */ +function createPreviewHandle(): MermaidPreviewHandle { + return { + visible: true, + wake: () => { void drainMermaidQueue() }, + } +} + +/** Drop queued renders that belong to a preview that is going away. */ +function dropPreviewTasks(handle: MermaidPreviewHandle): void { + for (let index = mermaidQueue.length - 1; index >= 0; index -= 1) { + const task = mermaidQueue[index] + if (task !== undefined && task.owner === handle) mermaidQueue.splice(index, 1) + } +} + /** 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 + lastScrollAt = 0 } /** Run a callback once the main thread is idle (bounded, so diagrams cannot @@ -78,19 +122,25 @@ function whenIdle(callback: () => void): void { * 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. + * the background ones, gives the browser (input, layout, the watchdog's probe) + * a turn between two renders, and yields entirely while the reader is + * scrolling or while a preview is off screen — so a document with dozens of + * diagrams stays scrollable and every diagram still ends up rendered. */ async function drainMermaidQueue(): Promise { if (mermaidPumping) return mermaidPumping = true const epoch = mermaidQueueEpoch try { - while (epoch === mermaidQueueEpoch && mermaidQueue.length > 0) { + while (epoch === mermaidQueueEpoch) { mermaidQueue.sort((a, b) => a.priority - b.priority) - const task = mermaidQueue.shift() + // Hidden previews keep their diagrams queued, not rendered: the visible + // document owns the main thread until its own diagrams are warm. + const runnable = mermaidQueue.findIndex((task) => task.owner.visible) + if (runnable === -1) break + const [task] = mermaidQueue.splice(runnable, 1) if (task === undefined) break + if (task.priority > 0) await waitForScrollQuiet() await new Promise((resolve) => { whenIdle(resolve) }) if (epoch !== mermaidQueueEpoch) break try { @@ -107,16 +157,15 @@ async function drainMermaidQueue(): Promise { } /** Queue one diagram render; {@link drainMermaidQueue} runs it. */ -function pushMermaidTask(priority: MermaidPriority, run: () => Promise): void { - mermaidQueue.push({ priority, run }) +function pushMermaidTask(priority: MermaidPriority, run: () => Promise, owner: MermaidPreviewHandle): void { + mermaidQueue.push({ priority, run, owner }) 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() +function isNearViewportRect(rect: DOMRect): boolean { if (rect.width === 0 && rect.height === 0) return false const margin = window.innerHeight * 1.25 return rect.bottom > -margin && rect.top < window.innerHeight + margin @@ -290,8 +339,17 @@ function MermaidZoomModal({ svg, onClose }: { svg: SVGSVGElement; onClose: () => ) } +interface MermaidDiagramProps { + code: string + /** The preview this diagram belongs to (queue visibility owner). */ + owner: MermaidPreviewHandle + /** True when the fence was already near the viewport at mount; the whole + * document reads its rects in one batch (see MermaidMarkdown). */ + initiallyNearViewport: boolean +} + /** One rendered mermaid fence: header chrome + diagram (or error + source). */ -function MermaidDiagram({ code }: { code: string }): React.ReactNode { +function MermaidDiagram({ code, owner, initiallyNearViewport }: MermaidDiagramProps): React.ReactNode { const [svg, setSvg] = useState(null) const [error, setError] = useState(null) const [copied, setCopied] = useState(false) @@ -339,8 +397,8 @@ function MermaidDiagram({ code }: { code: string }): React.ReactNode { pushMermaidTask(priority, async () => { if (generation !== generationRef.current) return await renderNow() - }) - }, [renderNow]) + }, owner) + }, [renderNow, owner]) // A new source or theme invalidates what is on screen and schedules a render. useEffect(() => { @@ -349,9 +407,8 @@ function MermaidDiagram({ code }: { code: string }): React.ReactNode { setSvg(null) setError(null) if (code.trim() === '') return - const node = wrapRef.current - scheduleRender(node !== null && isNearViewport(node) ? 0 : 1) - }, [code, dark, scheduleRender]) + scheduleRender(initiallyNearViewport ? 0 : 1) + }, [code, dark, initiallyNearViewport, scheduleRender]) // A placeholder that scrolls into view jumps ahead of the background queue. useEffect(() => { @@ -495,6 +552,34 @@ function isMermaidBlock(block: HTMLElement, bodies: ReadonlySet): boolea export function MermaidMarkdown({ text, codeLabels }: MermaidMarkdownProps): React.ReactNode { const containerRef = useRef(null) const mountsRef = useRef(new Map()) + /** Visibility gate shared by every diagram of this document. */ + const handleRef = useRef(null) + if (handleRef.current === null) handleRef.current = createPreviewHandle() + const handle = handleRef.current + + // Background renders wait while this preview is off screen (parked tab, + // collapsed dock); showing it again wakes the shared queue. jsdom has no + // IntersectionObserver, so specs keep the default (visible) gate. + useEffect(() => { + const container = containerRef.current + if (container === null || typeof IntersectionObserver === 'undefined') { + return () => { dropPreviewTasks(handle) } + } + const update = (visible: boolean): void => { + if (handle.visible === visible) return + handle.visible = visible + if (visible) handle.wake() + } + update(container.getClientRects().length > 0) + const observer = new IntersectionObserver((entries) => { + for (const entry of entries) update(entry.isIntersecting) + }) + observer.observe(container) + return () => { + observer.disconnect() + dropPreviewTasks(handle) + } + }, [handle]) useLayoutEffect(() => { const container = containerRef.current @@ -502,10 +587,20 @@ export function MermaidMarkdown({ text, codeLabels }: MermaidMarkdownProps): Rea const mounts = mountsRef.current const seen = new Set() const bodies = mermaidFenceBodies(text) + const blocks = [...container.querySelectorAll('.md-code-block')] - for (const block of container.querySelectorAll('.md-code-block')) { + // One read phase, then one write phase. Reading each diagram's rect inside + // the swap loop (between root renders) forces a full layout per diagram — + // dozens of forced reflows when a diagram-heavy document opens. + const near = new Map() + for (const block of blocks) { + if (!isMermaidBlock(block, bodies)) continue + near.set(block, isNearViewportRect(block.getBoundingClientRect())) + } + + for (const block of blocks) { const mount = mounts.get(block) - const isMermaid = isMermaidBlock(block, bodies) + const isMermaid = near.has(block) if (!isMermaid) { // A previously swapped block that is no longer a mermaid fence: // restore the CodeBlock children React still manages, so the plain @@ -529,10 +624,14 @@ export function MermaidMarkdown({ text, codeLabels }: MermaidMarkdownProps): Rea block.setAttribute('data-mermaid-processed', 'true') const root = createRoot(host) mounts.set(block, { root, source, removed }) - root.render() + root.render( + , + ) } else { mount.source = source - mount.root.render() + mount.root.render( + , + ) } } @@ -543,12 +642,13 @@ export function MermaidMarkdown({ text, codeLabels }: MermaidMarkdownProps): Rea mount.root.unmount() mounts.delete(block) } - }, [text]) + }, [text, handle]) useEffect(() => () => { for (const { root } of mountsRef.current.values()) root.unmount() mountsRef.current.clear() - }, []) + dropPreviewTasks(handle) + }, [handle]) return (
diff --git a/src/client/sidebar.module.css b/src/client/sidebar.module.css index 39dc8a6e..a84bb2b8 100644 --- a/src/client/sidebar.module.css +++ b/src/client/sidebar.module.css @@ -1872,6 +1872,15 @@ body[data-dsh-sidebar-dragging] .bottomPanel { border-radius: 6px; background: var(--dsw-alias-bg-layer-1); overflow: hidden; + /* Scroll performance: a rendered diagram is a large SVG. Skip layout and + paint for the diagrams outside the viewport (a diagram-heavy article can + hold dozens) and remember the measured height once a block has been on + screen, so scrolling past already-rendered diagrams costs nothing. */ + content-visibility: auto; + contain-intrinsic-size: auto 240px; + /* Isolate the box: a diagram landing must not invalidate the layout or paint + of the surrounding article. */ + contain: layout paint style; } .mermaidHeader { diff --git a/src/client/use-markdown-surface.ts b/src/client/use-markdown-surface.ts index 12cdcb21..cd96bb67 100644 --- a/src/client/use-markdown-surface.ts +++ b/src/client/use-markdown-surface.ts @@ -160,20 +160,22 @@ function attachMarkdownSurface( // write to the scroller. if (pending !== null) queueMicrotask(applyPending) - let scheduled = false + let scheduled: number | undefined const observer = new MutationObserver(() => { - if (scheduled) return - scheduled = true - queueMicrotask(() => { - scheduled = false + if (scheduled !== undefined) return + // Coalesce a burst of mutations into one DOM pass: each pass walks the + // whole preview, and diagram swapping / shiki settling emit many mutations. + scheduled = window.setTimeout(() => { + scheduled = undefined prepareMarkdownAnchors(container) applyPending() - }) + }, 80) }) observer.observe(container, { childList: true, subtree: true }) return () => { observer.disconnect() + if (scheduled !== undefined) window.clearTimeout(scheduled) container.removeAttribute(MARKDOWN_SURFACE_ATTR) } } From 7c1e67193d6b973af97de00c3158a894d5dc7402 Mon Sep 17 00:00:00 2001 From: OCILY Date: Fri, 23 Oct 2026 18:29:07 +0800 Subject: [PATCH 3/5] fix(mermaid): show the mermaid error itself when a diagram fails MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A failed render used to show only a generic "Mermaid render failed" label plus the fence source, with the actual reason hidden in the hover title — which makes a bad fence hard to find. Print the first two lines of mermaid's own message under the label (the full text stays on the title) and cover it in the fallback spec. This was triggered by a real document whose diagram used "A 与 B" instead of mermaid's "A & B" multi-target syntax: the error strip now names the parse error and the source block points at the broken lines. --- CHANGELOG.md | 1 + CHANGELOG_EN.md | 1 + src/client/mermaid.tsx | 7 ++++++- src/client/sidebar.module.css | 11 +++++++++++ tests/mermaid-markdown.spec.tsx | 1 + 5 files changed, 20 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 166666ee..8213d1b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,6 +53,7 @@ - **四项独立自动规则**:复用设置齿轮与现有偏好存储,分别控制已结束叶子聚合、已结束分支聚合、同一父级至少 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)。 - ⚡ **大文档滚动流畅性:渲染让位于滚动、隐藏页签不空转、摘掉全量 DOM 扫描**:图表渲染队列在滚动期间暂停(停止滚动 350 ms 后恢复),并且只服务当前可见的预览——隐藏页签里的图表保持占位、切回时才渲染;`Markdown` 变更触发的两次全量扫描(内联 HTML pass、标题锚点 pass)由「每次 mutation 跑一遍」(实测 8–15 ms/次)改为 80 ms 合并一次;打开文档时的近视口判断改为先批量读 rect、再统一写入,去掉每张图一次强制布局;`.mermaidWrap` 增加 `content-visibility: auto` + `contain-intrinsic-size` + `contain: layout paint style`,视口外的图表不再参与布局与绘制。滚动时不再有后台渲染、全量扫描与视口外 SVG 重绘抢主线程;图表仍会在滚动停止后或进入视口时补齐,不退化为代码块。 +- 🐞 **图表渲染失败时直接显示 mermaid 的解析错误**:之前只显示通用「Mermaid 渲染失败」+ 源码块(完整错误只在 hover title 里)。现在错误条下方直接给出 mermaid 报错的首两行(如 `Parse error on line 10 ... Expecting 'SEMI', ... got 'UNICODE_TEXT'`),配合下方源码可快速定位坏围栏;错误信息仍完整保留在 title 中。 ### v0.28.0 diff --git a/CHANGELOG_EN.md b/CHANGELOG_EN.md index 187e3c0d..55a541d0 100644 --- a/CHANGELOG_EN.md +++ b/CHANGELOG_EN.md @@ -8,6 +8,7 @@ - ⚡ **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). - ⚡ **Smooth scrolling for large documents**: the render queue pauses while the reader scrolls (resuming 350 ms after the last scroll event) and only serves the preview that is actually on screen — hidden tabs keep placeholders and warm their diagrams when shown again. The two mutation-driven full-document scans (inline HTML pass, heading-anchor pass) coalesce bursts into one pass every 80 ms (previously a scan per mutation, measured at 8–15 ms each); initial near-viewport detection reads every rect in one batch before the swap writes, removing one forced layout per diagram; `.mermaidWrap` gains `content-visibility: auto` + `contain-intrinsic-size` + `contain: layout paint style`, so off-screen diagrams leave layout and paint entirely. Scrolling no longer competes with background renders, document-wide scans or off-screen SVG repaint; diagrams still fill in when the reader stops or scrolls them into view — never as code blocks. +- 🐞 **A failed diagram shows the mermaid parse error inline**: instead of only a generic "Mermaid render failed" label plus the source block (the full error was hidden in the hover title), the error strip now prints the first two lines of mermaid's message (e.g. `Parse error on line 10 ... Expecting 'SEMI', ...`), so a broken fence is found without hunting; the full text stays on the title. ### v0.29.0 diff --git a/src/client/mermaid.tsx b/src/client/mermaid.tsx index 29acd2f3..3534667d 100644 --- a/src/client/mermaid.tsx +++ b/src/client/mermaid.tsx @@ -475,7 +475,12 @@ function MermaidDiagram({ code, owner, initiallyNearViewport }: MermaidDiagramPr
)} - {error !== null &&
{t('mermaidError')}
} + {error !== null && ( +
+ {t('mermaidError')} + {error.split('\n').slice(0, 2).join(' ').slice(0, 240)} +
+ )} {svg !== null && (
{ 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.textContent, 'the mermaid error itself is shown, not only a generic label').toContain('boom') expect(container.querySelector('[data-mermaid-diagram]'), 'no diagram is injected for a failed render').toBeNull() await unmount(root) }) From d7925a87d9867efe347395a5d4f8cc2d3d2e7099 Mon Sep 17 00:00:00 2001 From: OCILY Date: Mon, 26 Oct 2026 20:13:48 +0800 Subject: [PATCH 4/5] fix(mermaid): separate diagram errors from frame failures and validate the frame protocol MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review findings on #1040: - A bad fence no longer poisons the document. `renderMermaidDiagram` used to treat every `renderInFrame` rejection as a frame failure, so a mermaid syntax error (a normal `mermaid-error` answer) was retried and then flipped `frameUnavailable` — every later diagram failed until the page reloaded. Frame answers are now classified: `MermaidDiagramError` is final for that one diagram (its block shows the message + source), while `MermaidFrameError` (load/handshake/timeout/protocol) gets the single retry and then the page-level fast-fail breaker. - Both directions of postMessage are validated. Parent side binds `event.source` to the frame's `contentWindow` plus an opaque-origin allowlist and validates id/svg/message; the inlined frame script binds `event.source` to `window.parent` and validates id/code/theme/length before rendering. - Visibility gating now flushes on return: the 80ms inline-HTML pass remembers a skipped pass and replays it on `visibilitychange`, and the preview handle also pauses/resumes on document visibility (not just IntersectionObserver). - Tests: new `tests/mermaid-frame.spec.ts` covers the error classes (diagram error does not break later renders; transport retry; breaker after two failures) and the message validator (wrong window/origin, malformed payloads); the asset spec pins the frame-side sender/payload checks. --- scripts/build-mermaid-frame-asset.mjs | 11 +- src/client/MarkdownHtml.tsx | 25 ++++- src/client/mermaid-frame.ts | 140 ++++++++++++++++++++++---- src/client/mermaid.tsx | 27 +++-- tests/mermaid-frame-asset.spec.ts | 10 ++ tests/mermaid-frame.spec.ts | 106 +++++++++++++++++++ 6 files changed, 290 insertions(+), 29 deletions(-) create mode 100644 tests/mermaid-frame.spec.ts diff --git a/scripts/build-mermaid-frame-asset.mjs b/scripts/build-mermaid-frame-asset.mjs index 830d9ccb..167c46f9 100644 --- a/scripts/build-mermaid-frame-asset.mjs +++ b/scripts/build-mermaid-frame-asset.mjs @@ -58,6 +58,7 @@ const mermaidSource = readFileSync(mermaidBundlePath(), 'utf8') const FRAME_API = `(function () { 'use strict'; var seq = 0; + var MAX_SOURCE = 500000; function configure(theme) { window.mermaid.initialize({ startOnLoad: false, @@ -77,9 +78,17 @@ const FRAME_API = `(function () { window.__dshMermaidFrame = { render: render }; if (window.parent !== window) { window.addEventListener('message', function (event) { + // The parent is the only legitimate sender; the opaque-origin sandbox + // cannot compare origins, so identity plus a strict payload schema is + // the boundary (the host document must never be able to drive this + // renderer with arbitrary content). + if (event.source !== window.parent) return; 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) { + if (typeof data.id !== 'number' || !isFinite(data.id)) return; + if (typeof data.code !== 'string' || data.code.length > MAX_SOURCE) return; + var theme = data.theme === 'dark' ? 'dark' : 'default'; + render(data.code, 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) }, '*'); diff --git a/src/client/MarkdownHtml.tsx b/src/client/MarkdownHtml.tsx index 8a8c849d..f6fd2753 100644 --- a/src/client/MarkdownHtml.tsx +++ b/src/client/MarkdownHtml.tsx @@ -237,6 +237,18 @@ function MarkdownSegment({ text, hasMermaid, media, codeLabels }: MarkdownSegmen if (container === null) return runInlineHtmlPass(container, media) let timer: number | undefined + /** A pass was skipped because the page was hidden; flush it on return. */ + let dirty = false + const runPass = (): void => { + // Only `hidden` pauses the pass; jsdom reports a non-visible state too, + // and the initial pass already ran there. + if (document.visibilityState === 'hidden') { + dirty = true + return + } + dirty = false + runInlineHtmlPass(container, media) + } const observer = new MutationObserver(() => { if (timer !== undefined) return // Coalesce a burst of mutations (shiki settling, diagram swaps, inline @@ -245,13 +257,22 @@ function MarkdownSegment({ text, hasMermaid, media, codeLabels }: MarkdownSegmen // stream of full-document scans. timer = window.setTimeout(() => { timer = undefined - if (document.visibilityState !== 'visible') return - runInlineHtmlPass(container, media) + runPass() }, 80) }) + const onVisibilityChange = (): void => { + if (document.visibilityState === 'hidden' || !dirty) return + if (timer !== undefined) { + window.clearTimeout(timer) + timer = undefined + } + runPass() + } + document.addEventListener('visibilitychange', onVisibilityChange) observer.observe(container, { childList: true, subtree: true }) return () => { observer.disconnect() + document.removeEventListener('visibilitychange', onVisibilityChange) if (timer !== undefined) window.clearTimeout(timer) } }, [text, media]) diff --git a/src/client/mermaid-frame.ts b/src/client/mermaid-frame.ts index 98eed12d..de76f0e8 100644 --- a/src/client/mermaid-frame.ts +++ b/src/client/mermaid-frame.ts @@ -15,6 +15,12 @@ * `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. + * + * Two failure classes stay separate on purpose: a diagram that mermaid itself + * rejects is a per-diagram error (source + message on that block only), while a + * frame that never loads, times out or answers with garbage is a transport + * error (one retry, then a fast-fail breaker for the rest of the page). A bad + * fence must never poison the diagrams after it. */ import { MERMAID_FRAME_HTML } from './mermaid-frame-asset.generated.ts' @@ -25,6 +31,26 @@ const FRAME_WIDTH = 1200 const FRAME_HEIGHT = 900 const FRAME_READY_TIMEOUT_MS = 10_000 const FRAME_RENDER_TIMEOUT_MS = 30_000 +/** Guard against a hostile/broken payload being posted to the frame. */ +const MAX_DIAGRAM_SOURCE_LENGTH = 500_000 + +/** mermaid rejected this diagram (syntax/unsupported feature). Only this + * diagram falls back to its source; the frame stays healthy. */ +export class MermaidDiagramError extends Error { + constructor(message: string) { + super(message) + this.name = 'MermaidDiagramError' + } +} + +/** The frame itself failed (load/handshake/timeout/protocol). Retry once, then + * fail fast for the remaining diagrams on the page. */ +export class MermaidFrameError extends Error { + constructor(message: string, options?: { cause?: unknown }) { + super(message, options) + this.name = 'MermaidFrameError' + } +} /** One pending render waiting on the frame's postMessage answer. */ interface PendingRender { @@ -33,6 +59,18 @@ interface PendingRender { timer: number } +/** A validated answer from the frame. */ +export type FrameMessage = + | { kind: 'result'; id: number; svg: string } + | { kind: 'error'; id: number; message: string } + +/** The subset of MessageEvent the protocol needs (easy to unit-test). */ +export interface MessageEventLike { + source: unknown + origin: string + data: unknown +} + const pending = new Map() let requestSeq = 0 let frame: HTMLIFrameElement | null = null @@ -51,26 +89,78 @@ export function setMermaidFrameRendererForTests( testRenderer = renderer } +/** Test seam for the frame layer itself: replaces the postMessage transport + * while keeping `renderMermaidDiagram`'s error classification/retry/breaker. */ +let testTransport: ((code: string, theme: MermaidTheme) => Promise) | null = null +export function setMermaidFrameTransportForTests( + transport: ((code: string, theme: MermaidTheme) => Promise) | null, +): void { + testTransport = transport + frameUnavailable = false +} + +/** Restore the real frame and clear the breaker (module state persists across + * specs in one vitest file). */ +export function resetMermaidFrameForTests(): void { + testRenderer = null + testTransport = null + frameUnavailable = false +} + +/** + * Validate one message against the frame protocol. + * + * The sandboxed frame has an opaque origin (`'null'`), so the source window is + * the primary identity check; the origin allowlist keeps a same-origin page + * that happens to reuse the message shape from being accepted. + * @param event - the incoming message event (or a test double of it). + * @param expectedWindow - the frame's `contentWindow`; `null` rejects all. + * @returns the validated message, or `null` when it must be ignored. + */ +export function acceptFrameMessage(event: MessageEventLike, expectedWindow: Window | null): FrameMessage | null { + if (expectedWindow === null || event.source !== expectedWindow) return null + if (event.origin !== 'null' && event.origin !== '') return null + const data = event.data as { type?: unknown; id?: unknown; svg?: unknown; message?: unknown } | null + if (data === null || typeof data !== 'object') return null + if (data.type !== 'mermaid-result' && data.type !== 'mermaid-error') return null + if (typeof data.id !== 'number' || !Number.isInteger(data.id) || data.id <= 0) return null + if (data.type === 'mermaid-result') { + return typeof data.svg === 'string' ? { kind: 'result', id: data.id, svg: data.svg } : null + } + return typeof data.message === 'string' + ? { kind: 'error', id: data.id, message: data.message } + : null +} + /** 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) + const message = acceptFrameMessage(event, frame?.contentWindow ?? null) + if (message === null) return + const entry = pending.get(message.id) if (entry === undefined) return + pending.delete(message.id) + window.clearTimeout(entry.timer) + if (message.kind === 'result') entry.resolve(message.svg) + else entry.reject(new MermaidDiagramError(message.message)) + }) +} + +/** Reject every in-flight render (frame replaced/disposed) instead of leaving + * them to their timeouts. */ +function failPending(error: Error): void { + for (const [id, entry] of pending) { 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')) - }) + entry.reject(error) + } } /** Drop the current frame (failed load, page teardown) and its blob URL. */ function disposeFrame(): void { + failPending(new MermaidFrameError('mermaid frame was reset')) frameReady = null if (frame !== null) { frame.remove() @@ -109,11 +199,12 @@ function ensureFrame(): Promise { } const onReady = (event: MessageEvent): void => { if (event.source !== iframe.contentWindow) return + if (event.origin !== 'null' && event.origin !== '') 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')) + settle(new MermaidFrameError('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' })) @@ -128,12 +219,12 @@ function ensureFrame(): Promise { async function renderInFrame(code: string, theme: MermaidTheme): Promise { await ensureFrame() const target = frame?.contentWindow - if (target === null || target === undefined) throw new Error('mermaid frame disappeared') + if (target === null || target === undefined) throw new MermaidFrameError('mermaid frame disappeared') const id = ++requestSeq return new Promise((resolve, reject) => { const timer = window.setTimeout(() => { pending.delete(id) - reject(new Error('mermaid frame render timed out')) + reject(new MermaidFrameError('mermaid frame render timed out')) }, FRAME_RENDER_TIMEOUT_MS) pending.set(id, { resolve, reject, timer }) target.postMessage({ type: 'mermaid-render', id, code, theme }, '*') @@ -142,25 +233,36 @@ async function renderInFrame(code: string, theme: MermaidTheme): Promise /** * Render one mermaid diagram off the host document's layout. + * + * A `MermaidDiagramError` is final for that one diagram (no retry, no breaker); + * a transport failure gets one retry with a fresh frame, then flips the + * page-level breaker so later diagrams fail fast instead of paying a timeout + * each. * @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 { if (testRenderer !== null) return testRenderer(code, theme) - if (frameUnavailable) throw new Error('mermaid rendering frame is unavailable') + if (code.length > MAX_DIAGRAM_SOURCE_LENGTH) { + throw new MermaidDiagramError(`diagram source is too large (${code.length} chars)`) + } + if (frameUnavailable) throw new MermaidFrameError('mermaid rendering frame is unavailable') + const renderOnce = async (): Promise => ( + testTransport !== null ? testTransport(code, theme) : renderInFrame(code, theme) + ) 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). + return await renderOnce() + } catch (firstError) { + // A bad diagram is not a broken frame: report it and leave the frame alone. + if (firstError instanceof MermaidDiagramError) throw firstError disposeFrame() try { - return await renderInFrame(code, theme) + return await renderOnce() } catch (secondError) { + if (secondError instanceof MermaidDiagramError) throw secondError frameUnavailable = true - throw new Error( + throw new MermaidFrameError( `mermaid frame unavailable: ${secondError instanceof Error ? secondError.message : String(secondError)}`, { cause: secondError }, ) diff --git a/src/client/mermaid.tsx b/src/client/mermaid.tsx index 3534667d..16658246 100644 --- a/src/client/mermaid.tsx +++ b/src/client/mermaid.tsx @@ -563,25 +563,38 @@ export function MermaidMarkdown({ text, codeLabels }: MermaidMarkdownProps): Rea const handle = handleRef.current // Background renders wait while this preview is off screen (parked tab, - // collapsed dock); showing it again wakes the shared queue. jsdom has no - // IntersectionObserver, so specs keep the default (visible) gate. + // collapsed dock, hidden page); showing it again wakes the shared queue. + // jsdom has neither layout nor IntersectionObserver, so specs keep the + // default (visible) gate with only the document-visibility guard. useEffect(() => { const container = containerRef.current - if (container === null || typeof IntersectionObserver === 'undefined') { - return () => { dropPreviewTasks(handle) } - } + if (container === null) return () => { dropPreviewTasks(handle) } const update = (visible: boolean): void => { if (handle.visible === visible) return handle.visible = visible if (visible) handle.wake() } - update(container.getClientRects().length > 0) + const present = (): boolean => + document.visibilityState !== 'hidden' && container.getClientRects().length > 0 + const onVisibilityChange = (): void => { + if (typeof IntersectionObserver === 'undefined') update(document.visibilityState !== 'hidden') + else update(present()) + } + document.addEventListener('visibilitychange', onVisibilityChange) + if (typeof IntersectionObserver === 'undefined') { + return () => { + document.removeEventListener('visibilitychange', onVisibilityChange) + dropPreviewTasks(handle) + } + } + update(present()) const observer = new IntersectionObserver((entries) => { - for (const entry of entries) update(entry.isIntersecting) + for (const entry of entries) update(entry.isIntersecting && document.visibilityState !== 'hidden') }) observer.observe(container) return () => { observer.disconnect() + document.removeEventListener('visibilitychange', onVisibilityChange) dropPreviewTasks(handle) } }, [handle]) diff --git a/tests/mermaid-frame-asset.spec.ts b/tests/mermaid-frame-asset.spec.ts index bf9cc403..50c7025c 100644 --- a/tests/mermaid-frame-asset.spec.ts +++ b/tests/mermaid-frame-asset.spec.ts @@ -26,4 +26,14 @@ describe('mermaid frame asset', () => { expect(MERMAID_FRAME_HTML).toContain('htmlLabels: false') expect(MERMAID_FRAME_HTML).toContain('suppressErrorRendering: true') }) + + it('validates the sender and the payload on the frame side', () => { + // The opaque-origin sandbox cannot compare origins, so the frame binds + // requests to its parent window and validates every field it consumes. + expect(MERMAID_FRAME_HTML).toContain('event.source !== window.parent') + expect(MERMAID_FRAME_HTML).toContain("typeof data.id !== 'number'") + expect(MERMAID_FRAME_HTML).toContain("typeof data.code !== 'string'") + expect(MERMAID_FRAME_HTML).toContain('data.code.length > MAX_SOURCE') + expect(MERMAID_FRAME_HTML).toContain("data.theme === 'dark' ? 'dark' : 'default'") + }) }) diff --git a/tests/mermaid-frame.spec.ts b/tests/mermaid-frame.spec.ts new file mode 100644 index 00000000..7dac6a73 --- /dev/null +++ b/tests/mermaid-frame.spec.ts @@ -0,0 +1,106 @@ +/** + * The mermaid frame boundary: a diagram that mermaid itself rejects is a + * per-diagram error (only its block falls back to the source), while frame + * load/handshake/timeout failures retry once and then trip a page-level + * fast-fail breaker. The postMessage bridge is identity- and shape-validated on + * both sides. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + MermaidDiagramError, + MermaidFrameError, + acceptFrameMessage, + renderMermaidDiagram, + resetMermaidFrameForTests, + setMermaidFrameTransportForTests, +} from '../src/client/mermaid-frame.ts' + +const SVG = 'OK' + +beforeEach(() => { resetMermaidFrameForTests() }) +afterEach(() => { resetMermaidFrameForTests() }) + +describe('renderMermaidDiagram failure classes', () => { + it('keeps rendering the rest of the document after one diagram is rejected', async () => { + const transport = vi.fn() + .mockRejectedValueOnce(new MermaidDiagramError('Parse error on line 1')) + .mockResolvedValueOnce(SVG) + setMermaidFrameTransportForTests(transport) + + await expect(renderMermaidDiagram('bad', 'default')).rejects.toBeInstanceOf(MermaidDiagramError) + await expect(renderMermaidDiagram('good', 'default')).resolves.toBe(SVG) + // A diagram error is final for that diagram: no retry, no breaker. + expect(transport).toHaveBeenCalledTimes(2) + }) + + it('retries a transport failure once and recovers', async () => { + const transport = vi.fn() + .mockRejectedValueOnce(new MermaidFrameError('frame did not become ready')) + .mockResolvedValueOnce(SVG) + setMermaidFrameTransportForTests(transport) + + await expect(renderMermaidDiagram('graph TD', 'default')).resolves.toBe(SVG) + expect(transport).toHaveBeenCalledTimes(2) + }) + + it('breaks the page only after two transport failures, not after a diagram error', async () => { + const transport = vi.fn().mockRejectedValue(new MermaidFrameError('frame died')) + setMermaidFrameTransportForTests(transport) + + await expect(renderMermaidDiagram('graph TD', 'default')).rejects.toBeInstanceOf(MermaidFrameError) + expect(transport).toHaveBeenCalledTimes(2) + const callsAfterBreaker = transport.mock.calls.length + // Fast fail: later diagrams must not pay another timeout/retry. + await expect(renderMermaidDiagram('graph LR', 'default')).rejects.toBeInstanceOf(MermaidFrameError) + expect(transport.mock.calls.length).toBe(callsAfterBreaker) + }) +}) + +describe('acceptFrameMessage', () => { + const frameWindow = {} as Window + const event = (overrides: Record = {}): { + source: unknown + origin: string + data: unknown + } => ({ + source: frameWindow, + origin: 'null', + data: { type: 'mermaid-result', id: 1, svg: SVG }, + ...overrides, + }) + + it('accepts a well-formed result from the frame window', () => { + expect(acceptFrameMessage(event(), frameWindow)).toEqual({ kind: 'result', id: 1, svg: SVG }) + }) + + it('accepts a well-formed diagram error', () => { + expect( + acceptFrameMessage(event({ data: { type: 'mermaid-error', id: 2, message: 'Parse error' } }), frameWindow), + ).toEqual({ kind: 'error', id: 2, message: 'Parse error' }) + }) + + it('rejects a message from any window other than the frame', () => { + expect(acceptFrameMessage(event({ source: {} }), frameWindow)).toBeNull() + expect(acceptFrameMessage(event(), null)).toBeNull() + }) + + it('rejects a same-shape message from a different origin', () => { + expect(acceptFrameMessage(event({ origin: 'https://example.com' }), frameWindow)).toBeNull() + }) + + it('rejects malformed payloads', () => { + const bad = [ + null, + { type: 'mermaid-result', id: '1', svg: SVG }, + { type: 'mermaid-result', id: 0, svg: SVG }, + { type: 'mermaid-result', id: 1.5, svg: SVG }, + { type: 'mermaid-result', id: 1, svg: 42 }, + { type: 'mermaid-error', id: 1 }, + { type: 'mermaid-frame-ready' }, + { type: 'mermaid-render', id: 1, code: 'graph TD' }, + ] + for (const data of bad) { + expect(acceptFrameMessage(event({ data }), frameWindow)).toBeNull() + } + }) +}) From d19a2db42379c4a561f9de4a7c1d708826e95ecf Mon Sep 17 00:00:00 2001 From: OCILY Date: Mon, 26 Oct 2026 20:14:51 +0800 Subject: [PATCH 5/5] docs(mermaid): keep the unreleased entries above v0.28.1 and record the review fixes --- CHANGELOG.md | 10 +++++++--- .../2026-10-23-mermaid-iframe-isolation.md | 20 +++++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8213d1b4..58a5988e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ > 本文档收录 dsh-better-sidebar 的完整发布历史(最新版摘要见 [README](README_ZH.md);同步发布于 [GitHub Releases](https://github.com/omdsh-dev/DSH-better-sidebar/releases))。 +### 未发布 + +- ⚡ **大 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)。 +- ⚡ **大文档滚动流畅性:渲染让位于滚动、隐藏页签不空转、摘掉全量 DOM 扫描**:图表渲染队列在滚动期间暂停(停止滚动 350 ms 后恢复),并且只服务当前可见的预览——隐藏页签里的图表保持占位、切回时才渲染;`Markdown` 变更触发的两次全量扫描(内联 HTML pass、标题锚点 pass)由「每次 mutation 跑一遍」(实测 8–15 ms/次)改为 80 ms 合并一次;打开文档时的近视口判断改为先批量读 rect、再统一写入,去掉每张图一次强制布局;`.mermaidWrap` 增加 `content-visibility: auto` + `contain-intrinsic-size` + `contain: layout paint style`,视口外的图表不再参与布局与绘制。滚动时不再有后台渲染、全量扫描与视口外 SVG 重绘抢主线程;图表仍会在滚动停止后或进入视口时补齐,不退化为代码块。 +- 🐞 **图表渲染失败时直接显示 mermaid 的解析错误**:之前只显示通用「Mermaid 渲染失败」+ 源码块(完整错误只在 hover title 里)。现在错误条下方直接给出 mermaid 报错的首两行(如 `Parse error on line 10 ... Expecting 'SEMI', ... got 'UNICODE_TEXT'`),配合下方源码可快速定位坏围栏;错误信息仍完整保留在 title 中。 + ### v0.29.0 - **侧边对话接入 GenUI**:通过现有 `ctx.betterSidebar` 服务新增可选的 `registerSidechatSurfaceAdapter`,支持 GenUI 0.15.0 渲染已结算的助手回复;未注册消费方时保持原 Markdown。 @@ -16,6 +22,7 @@ - 📏 **实测(40,157,518 字节会话,本机重建)**:12 个 `session.cwd` + 36 个绕过入口调用并发 → **1 次 header 读、0 次整读、3 ms、RSS +0.3 MB**;同产物用修复前代码(`43db17f`)跑 6 个绕过入口并发 → 6 次整读、峰值 RSS +1002 MB(外推 36 次 ≈ 6.0 GB,与事故 6.2 GB 峰值吻合)。单次整读成本 467 ms / +501.6 MB。方法与边界见[记录](docs/plans/2026-10-27-workspace-cwd-over-cold-reads.md) §5.2。 - 🧪 测试:`tests/smoke.spec.ts` 重写该组 8 例(header 优先于陈旧提示、header 只读一次、12 并发共享一次 header 读、无 `stat`/`stat` 失败回落客户端提示、live committed 优先、相对 cwd 拒绝为 `bad-request`、`defaultDirectory` 与进程 cwd 兜底)。机制与取舍见 [记录](docs/plans/2026-10-27-workspace-cwd-over-cold-reads.md)。 + ### v0.28.1 - 🛡 **并发同键冷读合并(OOM 修复)**:全量重启后会话全部转为 detached,12 条 `/sidebar/*` 路由共享的 cwd 解析会对同一会话各做一次宿主冷观察(整份日志读 + 解码;39MB 级会话 × 44 个并发请求 ≈ 1.7GB → OOM)。现在 `cwdOf()` 把**同一会话 + 同一客户端 cwd 提示**的并发请求合并为一次真实读,其余 await 同一结果;不引入 TTL(宿主本身按持久化 revision 缓存已完成冷读),客户端提示参与 key 以免跨提示串味。`tests/smoke.spec.ts` 新增「12 并发 → 1 次冷读」与「不同提示不合并」两例。 @@ -51,9 +58,6 @@ - **任务页拖拽改为每帧一次更新**:图模式背景平移、后台任务浮窗标题拖动、锚定弹层拖动不再按鼠标事件频率重绘(高回报率鼠标下此前每个 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)。 -- ⚡ **大文档滚动流畅性:渲染让位于滚动、隐藏页签不空转、摘掉全量 DOM 扫描**:图表渲染队列在滚动期间暂停(停止滚动 350 ms 后恢复),并且只服务当前可见的预览——隐藏页签里的图表保持占位、切回时才渲染;`Markdown` 变更触发的两次全量扫描(内联 HTML pass、标题锚点 pass)由「每次 mutation 跑一遍」(实测 8–15 ms/次)改为 80 ms 合并一次;打开文档时的近视口判断改为先批量读 rect、再统一写入,去掉每张图一次强制布局;`.mermaidWrap` 增加 `content-visibility: auto` + `contain-intrinsic-size` + `contain: layout paint style`,视口外的图表不再参与布局与绘制。滚动时不再有后台渲染、全量扫描与视口外 SVG 重绘抢主线程;图表仍会在滚动停止后或进入视口时补齐,不退化为代码块。 -- 🐞 **图表渲染失败时直接显示 mermaid 的解析错误**:之前只显示通用「Mermaid 渲染失败」+ 源码块(完整错误只在 hover title 里)。现在错误条下方直接给出 mermaid 报错的首两行(如 `Parse error on line 10 ... Expecting 'SEMI', ... got 'UNICODE_TEXT'`),配合下方源码可快速定位坏围栏;错误信息仍完整保留在 title 中。 ### v0.28.0 diff --git a/docs/plans/2026-10-23-mermaid-iframe-isolation.md b/docs/plans/2026-10-23-mermaid-iframe-isolation.md index 3ebe3ddb..d3c6923d 100644 --- a/docs/plans/2026-10-23-mermaid-iframe-isolation.md +++ b/docs/plans/2026-10-23-mermaid-iframe-isolation.md @@ -128,6 +128,26 @@ tsdown 之前生成;git 源安装走 `prepare`,因此同样可用。 视口内/近视口的图优先渲染(初始优先级来自 3.4 的批量 rect 读取)。 - 其余图不阻塞阅读:滚动时暂停,停止滚动后按空闲槽补齐;隐藏页签不参与。 +### 3.6 错误分类与边界校验(review 修复) + +- **错误分两类**:iframe 脚本对 mermaid 语法错误的正常回包(`mermaid-error`)映射为 + `MermaidDiagramError`——只让该图显示错误首两行 + 源码,**不再重试、不置 frame 熔断**; + 装载失败/握手超时/渲染超时/通道异常才是 `MermaidFrameError`,允许重建一次,第二次 + 才置页级熔断(后续图快速失败)。一张坏图不会影响它后面的正确图。 +- **父侧校验**:`acceptFrameMessage(event, frame.contentWindow)` 要求 + `event.source === frame.contentWindow` 且 origin 属于不透明来源白名单(`'null'` / 空), + 再校验 `id`(正整数)/`svg`/`message` 的 schema;不匹配的消息直接丢弃。 +- **frame 侧校验**:内联脚本只接受 `event.source === window.parent` 的 `mermaid-render`, + 且校验 `id` 为有限数字、`code` 为字符串且不超过 500k 字符、`theme` 走 `dark`/`default` + 白名单,然后才调用 mermaid。 +- **可见性恢复补刷**:80 ms 合并的 inline-HTML pass 在页面 hidden 时记 dirty,恢复可见 + 时重放;预览队列的可见性 handle 同时受 `document.visibilityState` 与 + `IntersectionObserver` 控制(恢复可见即 `wake()`)。 +- **测试**:`tests/mermaid-frame.spec.ts` 覆盖「单图语法错误不影响后续图」「frame 故障 + 单次重试」「两次 frame 故障才熔断」以及消息校验(错误 source/origin、畸形 payload); + `tests/mermaid-frame-asset.spec.ts` 钉住 frame 侧的 sender/payload 校验标记;其余真机 + iframe 行为由挂载 lane 覆盖。 + ## 4. 实测结果(同机、同文档、31 图) | 指标 | 修复前 | 修复后 |