Skip to content

fix(mermaid): 沙箱 iframe 隔离图表布局测量,修复大 Markdown 预览卡死 - #1040

Merged
Menghuan1918 merged 5 commits into
omdsh-dev:devfrom
OCILY:fix/mermaid-preview-iframe
Oct 29, 2026
Merged

Menghuan1918 merged 5 commits into
omdsh-dev:devfrom
OCILY:fix/mermaid-preview-iframe

Conversation

@OCILY

@OCILY OCILY commented Oct 23, 2026 •

Copy link
Copy Markdown

审阅指引(TL;DR)

  • 核心逻辑 3 处:src/client/mermaid-frame.ts(~180 行,沙箱 iframe 渲染器 + postMessage 协议)、src/client/mermaid.tsx(渲染队列 / 占位骨架 / 可见性门控)、MarkdownHtml.tsx + use-markdown-surface.ts(仅把 mutation 触发的全量 pass 合并成 80 ms 一次)。
  • 生成物不在 diff 里:src/client/mermaid-frame-asset.generated.ts 是构建产物(gitignored,由 prepare/build 调用 scripts/build-mermaid-frame-asset.mjs 生成);仓库里的 diff 只有生成脚本本身。
  • 边界:无 host 半改动、无新增路由、无依赖增减(mermaid 本来就是 runtime 依赖);客户端 mermaid chunk 7.04 MB → 3.69 MB。
  • 证据:真机测量与对照实验在设计文档;本地 Linux CI 五步全绿(见下方评论)。GitHub Actions 首次 fork run 需要维护者 approve 一次。

问题

在大 Markdown(约 90 KB、31 个 mermaid 围栏的 SYSTEM_ARCHITECTURE.md)上打开预览会卡死渲染器:

renderer surface watchdog: page did not respond
terminating unresponsive renderer
unresponsive renderer replaced (reason: crashed, exitCode: 2)

重载后侧栏恢复上次标签页 → 再次卡死,形成崩溃循环。同尺寸、把 mermaid 围栏换成普通代码围栏的文档打开完全正常,问题锁定在 Mermaid 预览链路。

根因(真实宿主测量)

Mermaid 用 SVGElement.getBBox() 量每个标签的文字尺寸,测量节点挂在 document.body 上,每次测量都会刷新整个宿主文档的布局:

测量环境 一次 getBBox
真实 DSH 窗口(15,418 个 DOM 节点) 59–75 ms
空 iframe 文档 1 ms

单张图因此要 1.5–7.3 秒;旧实现把文档里所有图在挂载时同时渲染,31 张图让主线程连续无响应 >20 秒,触发桌面壳看门狗。

尝试过但无效/不可行的方案:#root { contain: layout style } / contain: strict(59/62 ms,无改善);content-visibility: hidden(1 ms,但会隐藏界面)。

方案

  • 渲染器隔离在沙箱 iframe(新增 src/client/mermaid-frame.ts):懒创建隐藏 iframe(sandbox="allow-scripts",opaque origin,无法访问 GUI 文档),加载自包含的 blob: 文档(内联 mermaid UMD + 小 postMessage 协议),父侧只做收发与 SVG 清洗。失败自动重建一次,仍失败则该图显示「错误 + 源码」,不退回主线程慢渲染。
  • 自包含资产(新增 scripts/build-mermaid-frame-asset.mjs):构建期把插件自己的 mermaid/dist/mermaid.min.js 与协议内联为 HTML(生成文件 gitignored),由 prepare/build/bundle/watch 在 tsc/vitest/tsdown 前生成。无需改动 host 半 / 新增路由。
  • 渲染调度(src/client/mermaid.tsx):模块级共享队列,可见/近视口图优先,其余 requestIdleCallback 逐张补齐,两次渲染之间让出 16 ms 主线程;卸载/主题切换用 generation 取消旧任务。所有图最终都会渲染成图,不再退化为代码块;占位骨架按围栏行数预留高度,图到达时不跳动。
  • 样式:sidebar.module.css 新增占位骨架(仅主题 token,尊重 prefers-reduced-motion)。

效果(同机、同文档)

指标 修复前 修复后
单图渲染 1,500–7,300 ms 30–104 ms
31 图总耗时 主线程阻塞 >20 s,渲染器被杀 约 5 s 内后台逐张完成
watchdog 崩溃 必现 0 次新增
客户端 mermaid chunk 7.04 MB 3.69 MB
图表显示 卡死 全部成图

测试

  • tests/mermaid-markdown.spec.tsx:占位→图替换、失败→源码兜底、多围栏全量渲染、主题透传、跨围栏引用语义(原有)。
  • 新增 tests/mermaid-frame-asset.spec.ts:自包含文档、恰好两段内联脚本(</script 安全转义)、strict 配置。
  • tests/steady-state.spec.tsx:周期定时器扫描跳过 *.generated.ts 资产(不是手写源码)。
  • 本地已通过:pnpm typecheck、pnpm lint、pnpm build,以及上述相关 spec(15 用例)全绿。

说明:本地 Windows 全量单测存在既有的环境性失败(git 二进制/符号链接权限/GBK 编码/tar CRLF 等,集中在 git-、smoke、fs-、text-encoding、plugin-meta),与本次改动无关;check:consumer-types 与 mount 冒烟受本机符号链接/Playwright 环境限制未能本地执行,以 CI 为准。

设计记录

docs/plans/2026-10-23-mermaid-iframe-isolation.md

讨论点

内联 UMD 到客户端 chunk 是为了不动 host 半、保持自包含;代价是 chunk 内多一个 3.5 MB 字符串(但仍比原先的 7.04 MB 小)。如果更偏好新增 runtime chunk + /sidebar/bundle 路由的方式,我可以按现有 chunk 注册表(含 5 处镜像)改一版。

追加迭代(同一 PR 的 2 个后续 commit)

iframe 隔离解决冻结后,真机反馈「加载后滚动仍不够流畅」,因此同 PR 继续补了两批改动(设计记录 §3.4–3.5、CHANGELOG 已同步):

  • perf(mermaid): keep scrolling and hidden tabs off the render queue
    • 滚动手势优先:全局 passive 捕获 scroll,滚动期间暂停后台渲染,停止滚动 350 ms 后恢复;滚动中进入视口的图仍即时渲染。
    • 隐藏页签不空转:每个预览一个 IntersectionObserver 可见性 handle,队列只调度可见预览的任务;隐藏页签保留占位、切回时 wake();预览卸载清掉其排队任务。
    • mutation 全量扫描合并:内联 HTML pass / 标题锚点 pass 从「每次 mutation 跑一遍」(实测 8–15 ms/次)改为 80 ms 合并一次,页面隐藏时跳过。
    • 打开时去掉逐图强制布局:先批量读取所有 mermaid 块的 rect(一次读相位),再统一替换/挂载(一次写相位)。
    • .mermaidWrap 增加 content-visibility: auto + contain-intrinsic-size + contain: layout paint style,视口外的图表不再参与布局与绘制。
  • fix(mermaid): show the mermaid error itself when a diagram fails
    • 渲染失败时错误条直接显示 mermaid 报错首两行(此前只在 hover title 里),配合下方源码可快速定位坏围栏;完整错误与源码仍保留。

验证:typecheck / lint / build 通过;相关 spec(mermaid-markdown / mermaid-frame-asset / markdown-html-render / markdown-surface / steady-state / lazy-chunk)64+ 用例全绿。当前 CI 仍是 action_required(fork 首次 PR 需维护者批准一次 workflow),方便的话 approve 一下即可开跑。

Review 修复(2026-10-26,head 54f82fa9)

按维护者 review 的两个阻断项修复后已 rebase 到 dev 43db17f2:

  1. 坏图不再全局熔断:iframe 对语法错误的正常回包映射为 MermaidDiagramError(只回退该图,不重试/不置熔断);装载/超时/通道故障才是 MermaidFrameError(重试一次后熔断)。新增 tests/mermaid-frame.spec.ts 覆盖三类路径。
  2. postMessage 双向校验:父侧绑定 event.source === frame.contentWindow + 不透明 origin 白名单 + id/svg/message schema;frame 侧绑定 window.parent + id/code/theme/长度校验。
  3. 非阻断项:visibilitychange 恢复补刷已加;超时/真实 iframe 仍由挂载 lane 覆盖。

本地 Linux CI:typecheck / lint / test(233 files · 2848 passed · 17 skipped)/ build / check:consumer-types 全绿。

@OCILY

OCILY commented Oct 23, 2026

Copy link
Copy Markdown
Author

补充:首次来自 fork 的 CI 运行显示 action_required(需要维护者批准一次 workflow),麻烦有空 approve 一下;本地已跑过 typecheck / lint / build 与相关 spec(mermaid-markdown / mermaid-frame-asset / steady-state 共 15 用例全绿)。

@OCILY

OCILY commented Oct 23, 2026

Copy link
Copy Markdown
Author

补充一份本地按仓库 CI 步骤跑出来的结果(GitHub Actions 这边仍是 action_required,fork 首次贡献需要维护者批准一次 workflow,作者无法自行批准;fork 仓库的 Actions 又被 GitHub 默认禁用,所以先在本地用同版本工具链验证):

环境:Ubuntu (WSL2) · node v22.23.4 · pnpm 11.8.0 · pnpm install --frozen-lockfile(与 .github/workflows/ci.yml 的 ci job 一致,分支 HEAD 2ec737e0)

步骤 结果
pnpm typecheck ✅
pnpm lint ✅
pnpm test ✅ 222 files / 2692 passed, 17 skipped, 0 failed
pnpm build ✅
pnpm check:consumer-types ✅

说明:ci.yml 里的 test:mount(真实 DSH + Playwright Chromium)是 ubuntu-only 的独立 lane,本地无法完整复现,其余步骤与官方 ci job 相同。如果方便 approve 一下 workflow,就能拿到官方 check 结果;这份结果可以先作为参考。

@OCILY
OCILY force-pushed the fix/mermaid-preview-iframe branch from 2ec737e to 2cc2594 Compare October 23, 2026 17:11
@OCILY

OCILY commented Oct 23, 2026

Copy link
Copy Markdown
Author

已 rebase 到最新 dev(740d73a0,等待期间上游合入 #1041 / #1044 等),冲突只在 CHANGELOG.md 的新增条目区,已手工合并双方条目,PR 目前 mergeable。新的 head:2cc25948(仍是 3 个 commit,仅 rebase)。

rebase 后按仓库 CI 步骤在本地 Linux 复跑(Ubuntu WSL2 · node v22.23.4 · pnpm 11.8.0 · fresh clone + pnpm install --frozen-lockfile):

步骤 结果
pnpm typecheck ✅
pnpm lint ✅
pnpm test ✅ 222 files / 2692 passed, 17 skipped, 0 failed
pnpm build ✅
pnpm check:consumer-types ✅

GitHub Actions 这边仍是 action_required(fork 首次贡献需要维护者批准一次 workflow,作者无法自行批准);方便时 approve 就能拿到官方 check。

@OCILY
OCILY force-pushed the fix/mermaid-preview-iframe branch from 2cc2594 to 598714b Compare October 24, 2026 12:05
davidLi17 added a commit to davidLi17/DSH-better-sidebar that referenced this pull request Oct 25, 2026
Selectively backport open upstream PRs omdsh-dev#1040 (598714b), omdsh-dev#1055 (828452a), and omdsh-dev#1053 (f2ad4b1). Isolate Mermaid layout with authenticated sandbox messaging, recover from malformed diagrams, cancel/promote queued renders, preserve Windows Markdown separators and keep the bottom workbench toggle reachable.

Preserve LHG draft/image sidechat behavior and selective omdsh-dev#1050 performance fixes. Ship prebuilt lib without lifecycle hooks. Validation: 230 files, 2790 tests passed, 17 skipped; typecheck, lint, build, consumer types, pack and fresh official DSH rc1 install/start passed. Real browser UI and native Windows unverified; see maintenance record.
@Menghuan1918

Copy link
Copy Markdown
Collaborator

维护者 review 结论:needs-changes,这一批先不合。两个阻断(其余是观察):

  1. 坏图会全局熔断:src/client/mermaid-frame.ts:154-162 把所有 renderInFrame 的 reject 都当成 frame 故障;frame 脚本在语法错误时会正常回一条 mermaid-error(scripts/build-mermaid-frame-asset.mjs:84-85 附近),它被并进同一条路径 → 重试后 frameUnavailable = true,之后任意正确图直到整页刷新都失败。应区分「图表本身错误」(只让该图回退)与「frame 初始化/超时/消息通道故障」(才允许重试并最终熔断)。
  2. 双向消息未校验来源:src/client/mermaid-frame.ts:58-68(父侧收结果)与构建脚本 :79-85(frame 侧收请求)只校验 type/id。父侧应绑定 event.source === frame.contentWindow(sandboxed iframe 的 origin 是不透明 "null",以 source 为主 + origin 白名单),frame 侧应绑定 event.source === parent,并补齐 id/code/theme 的 schema 校验。

非阻断观察:隐藏页面时队列与 80ms mutation 合并缺少 visibilitychange 门控(恢复可见无新 mutation 则不补刷);stub 测试绕过了真实协议/超时/错误恢复。资产内联不需要新增 chunk 镜像,CSS 只用 token,这部分没问题。按上面两点更新后可重开 review。

Menghuan1918 added a commit that referenced this pull request Oct 26, 2026
- CHANGELOG: add the #992 dock-fallback entry
- docs/plans: scan inventory, per-batch merge/close evidence, deferred PR
  verdicts (#1040 #1019 #1048), gates and known local flakes
- issue-triage: #983/#992/#1059 are dev-fixed pending release
@OCILY
OCILY force-pushed the fix/mermaid-preview-iframe branch from 598714b to 54f82fa Compare October 26, 2026 12:17
OCILY pushed a commit to OCILY/DSH-better-sidebar that referenced this pull request Oct 26, 2026
…e the frame protocol

Review findings on omdsh-dev#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.
@OCILY

OCILY commented Oct 26, 2026

Copy link
Copy Markdown
Author

@Menghuan1918 两个阻断项已修复,已 rebase 到最新 dev(43db17f2)并推送(head 54f82fa9,5 commits):

  1. 错误分类(src/client/mermaid-frame.ts)
    • iframe 对语法/不支持特性的正常回包 → MermaidDiagramError:只让当前图回退到「错误 + 源码」,不重试、不置 frameUnavailable;
    • 装载/握手/渲染超时/通道异常 → MermaidFrameError:重建 frame 重试一次,第二次才熔断(后续图直接快速失败,不再逐个等超时);
    • 新增 tests/mermaid-frame.spec.ts:坏图之后的正确图仍能渲染(transport 只调用 1 次);frame 故障重试一次后恢复;两次 frame 故障才熔断且后续图不再调用 transport。
  2. 双向消息校验
    • 父侧 acceptFrameMessage:event.source === frame.contentWindow + 不透明 origin 白名单('null' / 空)+ id/svg/message schema,不匹配直接丢弃;
    • frame 侧(build 脚本内联):只接受 event.source === window.parent,并校验 id 为有限数字、code 为字符串且 ≤500k 字符、theme ∈ {dark, default} 后才渲染;
    • 测试覆盖错误 source/origin、畸形 payload;mermaid-frame-asset.spec.ts 钉住 frame 侧的 sender/payload 校验标记。
  3. 非阻断观察
    • 80 ms inline pass 在页面 hidden 时记 dirty,visibilitychange 恢复后补刷;预览队列的可见性 handle 同时受 document.visibilityState 与 IntersectionObserver 控制(恢复可见即 wake());
    • 超时/真实 iframe 行为仍无法在 jsdom 复刻(由挂载 lane 覆盖);错误分类/重试/熔断/协议校验已有单测。

本地 Linux(Ubuntu WSL2 · node v22.23.4 · pnpm 11.8.0,fresh clone + pnpm install --frozen-lockfile)复跑:typecheck ✅ / lint ✅ / test ✅ 233 files · 2848 passed · 17 skipped / build ✅ / check:consumer-types ✅。GitHub Actions 的首次 fork run 仍需维护者 approve 一次;方便时重开 review。

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.
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.
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.
…e the frame protocol

Review findings on omdsh-dev#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.
@OCILY
OCILY force-pushed the fix/mermaid-preview-iframe branch from 54f82fa to d19a2db Compare October 28, 2026 12:23
@Menghuan1918
Menghuan1918 merged commit 66337ff into omdsh-dev:dev Oct 29, 2026
Menghuan1918 pushed a commit that referenced this pull request Nov 4, 2026
The #1040 merge (04c6cb8) resolved CHANGELOG.md and CHANGELOG_EN.md from a
tree that had already lost everything below the top sections: both parents
were 656/658 (ZH) and 496/497 (EN) lines, the merge result was 41/27. The
file ended mid-v0.28.1, so v0.28.0 and every earlier release disappeared.

Restore the tail from 66337ff (the dev-side parent; its history is identical
to the other parent's from v0.28.1/v0.28.2 down) and keep the current top
sections, which already carry the batch's new entries. PR #1077 (dev to main)
would otherwise delete 628 lines of main's release history.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants