Repository navigation
fix(mermaid): 沙箱 iframe 隔离图表布局测量,修复大 Markdown 预览卡死 - #1040
Conversation
|
补充:首次来自 fork 的 CI 运行显示 |
3db02b5 to
39368d3
Compare
|
补充一份本地按仓库 CI 步骤跑出来的结果(GitHub Actions 这边仍是 环境:Ubuntu (WSL2) · node v22.23.4 · pnpm 11.8.0 ·
说明: |
2ec737e to
2cc2594
Compare
|
已 rebase 到最新 rebase 后按仓库 CI 步骤在本地 Linux 复跑(Ubuntu WSL2 · node v22.23.4 · pnpm 11.8.0 · fresh clone +
GitHub Actions 这边仍是 |
2cc2594 to
598714b
Compare
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.
|
维护者 review 结论:needs-changes,这一批先不合。两个阻断(其余是观察):
非阻断观察:隐藏页面时队列与 80ms mutation 合并缺少 |
598714b to
54f82fa
Compare
…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.
|
@Menghuan1918 两个阻断项已修复,已 rebase 到最新
本地 Linux(Ubuntu WSL2 · node v22.23.4 · pnpm 11.8.0,fresh clone + |
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.
54f82fa to
d19a2db
Compare
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.
审阅指引(TL;DR)
src/client/mermaid-frame.ts(~180 行,沙箱 iframe 渲染器 + postMessage 协议)、src/client/mermaid.tsx(渲染队列 / 占位骨架 / 可见性门控)、MarkdownHtml.tsx+use-markdown-surface.ts(仅把 mutation 触发的全量 pass 合并成 80 ms 一次)。src/client/mermaid-frame-asset.generated.ts是构建产物(gitignored,由prepare/build调用scripts/build-mermaid-frame-asset.mjs生成);仓库里的 diff 只有生成脚本本身。问题
在大 Markdown(约 90 KB、31 个 mermaid 围栏的
SYSTEM_ARCHITECTURE.md)上打开预览会卡死渲染器:重载后侧栏恢复上次标签页 → 再次卡死,形成崩溃循环。同尺寸、把 mermaid 围栏换成普通代码围栏的文档打开完全正常,问题锁定在 Mermaid 预览链路。
根因(真实宿主测量)
Mermaid 用
SVGElement.getBBox()量每个标签的文字尺寸,测量节点挂在document.body上,每次测量都会刷新整个宿主文档的布局:getBBox单张图因此要 1.5–7.3 秒;旧实现把文档里所有图在挂载时同时渲染,31 张图让主线程连续无响应 >20 秒,触发桌面壳看门狗。
尝试过但无效/不可行的方案:
#root { contain: layout style }/contain: strict(59/62 ms,无改善);content-visibility: hidden(1 ms,但会隐藏界面)。方案
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)。效果(同机、同文档)
测试
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 编码/
tarCRLF 等,集中在 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 queueIntersectionObserver可见性 handle,队列只调度可见预览的任务;隐藏页签保留占位、切回时wake();预览卸载清掉其排队任务。.mermaidWrap增加content-visibility: auto+contain-intrinsic-size+contain: layout paint style,视口外的图表不再参与布局与绘制。fix(mermaid): show the mermaid error itself when a diagram fails验证:
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 到
dev43db17f2:MermaidDiagramError(只回退该图,不重试/不置熔断);装载/超时/通道故障才是MermaidFrameError(重试一次后熔断)。新增tests/mermaid-frame.spec.ts覆盖三类路径。event.source === frame.contentWindow+ 不透明 origin 白名单 + id/svg/message schema;frame 侧绑定window.parent+ id/code/theme/长度校验。本地 Linux CI:
typecheck/lint/test(233 files · 2848 passed · 17 skipped)/build/check:consumer-types全绿。