Skip to content

fix(ui): prevent Mermaid height changes on cached remounts - #5962

Merged
Colafornia merged 2 commits into
apache:mainfrom
Colafornia:fix/5942-mermaid-chat-flicker
Oct 9, 2026
Merged

Colafornia merged 2 commits into
apache:mainfrom
Colafornia:fix/5942-mermaid-chat-flicker

Conversation

@Colafornia

@Colafornia Colafornia commented Oct 4, 2026 •

Copy link
Copy Markdown
Member
English

Summary

Leaving a Mermaid conversation idle can repeatedly move the transcript or scrollbar. Keep cached diagrams at their final fitted height from the first commit when virtualized rows remount.

The template cache avoids Mermaid rendering work, but previously did not prevent loading and JS measurement layouts on remount. Those row-height changes trigger scroll compensation and can restart virtua's direction-dependent mount/unmount cycle.

  • Restore cached templates synchronously during state initialization, preserving independent SVG IDs and cache recency.
  • Compute fitted dimensions in CSS from the SVG ratio, container width, viewport height limit, and zoom. Remove JS layout state, the measurement scheduler, and the window resize listener.
  • Keep one MermaidDiagram component. Its rendered result's cacheKey identifies the source/theme; the remaining ResizeObserver updates panning affordances only.

Fixes #5942

Verification

  • UI build and typecheck passed; 106 related Mermaid, Markdown, use-chat-scroll, and transcript-scroll-authority tests passed.
  • The submitted cached-remount regression checks every React commit and fails on the original loading path.
  • Touched-file Biome lint and git diff --check passed. CI passed, including lint, formatting, build, typecheck, Knip, affected workspace tests, Desktop E2E, browser smoke, Storybook smoke, and existing transcript geometry invariants. The existing geometry scenes do not specifically protect Mermaid first-commit height.
  • Compared baseline 7c90bac2d with the final source in Electron 43.4.1 using production ChatView, MermaidDiagram, scroll authority, and desktop CSS. Each isolated pane had a 1240×700 viewport and received no input during its 10-second recording. These were isolated UI replays, not full installed-app recordings.

Side-by-side recording

tail.webm
reading.webm
Idle position Before After
Tail, 578 geometry samples scrollHeight 4072/4349; timeline Y -27.97/338.03 scrollTop 3649, scrollHeight 4349, timeline Y -27.97 throughout
Reading, 577 geometry samples scrollTop 2719/2996; scrollHeight 4072/4349 scrollTop 2996, scrollHeight 4349, timeline Y 625.03 throughout

Warm-remount ablation measured first-commit → final diagram heights: simplified fix 462→462px; no synchronous restore 145→462px; synchronous restore with old JS sizing 551→462px. CSS alone also stopped the observed idle loop, but retained loading. Both changes preserve warm-remount first-commit geometry; neither is claimed individually necessary for every idle loop.

Local geometry checks covered pie, wide flowchart, and tall sequence diagrams at 320/720/1240px, fullscreen, and zoom. The simplified candidate preserved panning affordances after resizing a zoomed diagram from 1240 to 720px. Rendering 25 distinct standalone diagrams evicted old templates; the cold remount then settled.

Remaining verification and scope

The Node regression protects synchronous restoration, not CSS geometry. CSS evidence remains local browser measurement and recording; no new geometry CI gate is included. Idle stability alone would miss the observed 551→462px first-commit transition.

After review, changing an already-mounted diagram to a cached source/theme restores the template directly without committing a loading placeholder. The effect still resets zoom and refreshes cache recency. The first-commit fitted-height guarantee applies to remounts; input changes can initially show the previous rendered template. Cold misses remain asynchronous. virtua, scroll authority, and cache capacity are unchanged.

Review follow-up verification: the existing theme-switch test now checks every React commit when returning from dark to cached light. It failed on the reviewed head and passes with the fix. UI build/typecheck, 106 focused Mermaid, Markdown and scroll tests, touched-file lint, and git diff --check passed locally. The earlier CI and browser measurements above apply to the original reviewed head; this follow-up does not add CSS geometry coverage.

  • In the full Desktop window (npm run dev is sufficient), replay the original conversation and idle 10 seconds at the tail and near the timeline.
  • Check light/dark theme switching (confirmed by the user).
  • Inspect the completed CI run.

AI use

  • No generative tool made a substantive contribution
  • Generative tooling made a substantive contribution

Tool(s) and scope: OpenAI Codex diagnosed the remount loop, implemented the fix, ran regression and ablation checks, and prepared this PR under user direction. The commit includes a Generated-by: Codex trailer.

Checklist

  • Tests cover the change and fail without it
  • Lint, format, typecheck and the affected suites pass

The cache restoration regression fails without the fix; CSS geometry has local evidence rather than a submitted automated regression. Package checks and touched-file lint passed locally; repository lint/format, typecheck, and affected suites passed in CI. The UI surface is excluded from the repository formatter by existing policy.

Does this PR entail a change in behavior?

  • Yes — described under Summary above
  • No
中文

概述

含 Mermaid 图表的会话停止滚动后,正文或滚动条可能持续跳动。本次修复让虚拟列表中的图表在缓存命中后重新挂载时,从第一次提交起就保持最终适配高度。

模板缓存避免了重复调用 Mermaid 渲染,但此前重新挂载仍会经过加载占位和 JS 测量布局。行高变化触发滚动补偿,并可能重新启动 virtua 根据滚动方向挂载、卸载行的循环。

  • 在 state 初始化时同步恢复缓存模板,保留独立 SVG ID 和缓存使用顺序更新。
  • 根据 SVG 比例、容器宽度、视口高度上限和缩放比例,在 CSS 中计算适配尺寸。删除 JS 布局状态、测量调度和窗口尺寸监听。
  • 保持单个 MermaidDiagram 组件。渲染结果的 cacheKey 标识源码与主题;剩余 ResizeObserver 仅更新平移方向和交互提示。

修复 #5942

验证

  • UI 构建和类型检查通过;Mermaid、Markdown、use-chat-scroll、transcript-scroll-authority 相关测试共 106 项通过。
  • 提交的缓存重挂载回归测试检查每次 React 提交,在原始加载路径上会失败。
  • 修改文件的 Biome lint 和 git diff --check 通过。CI 已通过,包括 lint、格式检查、构建、类型检查、Knip、受影响工作区测试、Desktop E2E、浏览器冒烟、Storybook 冒烟及现有正文几何约束检查。现有几何场景不专门保护 Mermaid 首次提交高度。
  • 在 Electron 43.4.1 中,使用生产 ChatView、MermaidDiagram、滚动权威和桌面 CSS,对比基线 7c90bac2d 与最终源码。每侧独立视口为 1240×700,录制 10 秒期间没有输入。这是隔离 UI 回放,不是完整安装版应用录屏。

同屏录屏

同屏录屏统一放在英文区,请展开英文区查看。

空闲位置 修复前 修复后
正文底部,578 次几何采样 scrollHeight 4072/4349;时间线 Y -27.97/338.03 全程 scrollTop 3649、scrollHeight 4349、时间线 Y -27.97
阅读位置,577 次几何采样 scrollTop 2719/2996;scrollHeight 4072/4349 全程 scrollTop 2996、scrollHeight 4349、时间线 Y 625.03

暖缓存重挂载消融测得首次提交 → 最终图表高度:简化方案 462→462px;去掉同步恢复 145→462px;保留同步恢复但使用旧 JS 测量 551→462px。仅修改 CSS 也能停止实验中的空闲循环,但仍经过加载占位。两项改动共同保证暖缓存重挂载的首帧几何;没有声称它们分别对所有空闲循环都必不可少。

本地几何检查覆盖 320/720/1240px 下的饼图、宽流程图、高时序图,以及全屏和缩放。简化版本在缩放后将窗口从 1240 缩到 720px,仍能正确更新平移方向。渲染 25 个独立图表淘汰旧模板后,冷缓存重挂载能够收敛。

待验证项与范围

Node 回归测试保护同步恢复,不验证 CSS 几何。CSS 证据仍来自本地浏览器测量和录屏,没有新增几何 CI 闸门。仅检查空闲稳定性,也无法检出已观察到的 551→462px 首帧高度变化。

根据审查意见,已挂载图表切换到缓存中的源码或主题时,直接恢复模板,不再提交加载占位。状态更新仍重置缩放并刷新缓存使用顺序。首次提交适配高度的保证适用于重挂载;输入变化时,最初仍可能显示上一个已渲染模板。冷缓存未命中仍异步渲染。virtua、滚动权威和缓存容量保持不变。

审查修复验证:扩展现有主题切换测试,检查从深色切回已缓存浅色时的每次 React 提交。该断言在审查时的版本上失败,修复后通过。UI 构建、类型检查、106 项 Mermaid、Markdown 和滚动相关测试、修改文件 lint 及 git diff --check 均在本地通过。上文既有 CI 和浏览器测量对应原审查版本;本轮未新增 CSS 几何覆盖。

  • [X ] 在完整 Desktop 窗口中回放原会话,分别在正文底部和时间线附近空闲 10 秒(npm run dev 即可)。
  • 检查浅色/深色主题切换(用户已确认)。
  • 检查完整 CI 结果。

AI 使用

  • 生成式工具没有实质性贡献
  • 生成式工具有实质性贡献

工具与范围:OpenAI Codex 在用户指导下诊断重挂载循环、实现修复、执行回归与消融检查,并编写本 PR。提交包含 Generated-by: Codex 标记。

检查清单

  • 测试覆盖改动,移除修复后会失败
  • lint、格式检查、类型检查和受影响测试通过

缓存恢复回归测试在没有修复时失败;CSS 几何仅有本地证据,没有提交自动回归测试。包级检查和修改文件的 lint 在本地通过;仓库 lint/格式、类型检查和受影响测试在 CI 通过。既有仓库策略将 UI 文件排除在格式化器之外。

此 PR 是否改变行为?

  • 是——已在概述中说明
  • 否

Restore warm templates synchronously and compute fitted diagram dimensions in CSS, removing the asynchronous measurement state.

Generated-by: Codex
@github-actions github-actions Bot added the effort/M Under 500 readable lines label Oct 4, 2026
@Colafornia
Colafornia marked this pull request as ready for review October 4, 2026 11:11

@jackwener jackwener left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[kabi-sol]

Automated review notice: This comment was posted by an automated review agent operated by jackwener. It is not an independent human review and does not replace one.

Reviewed b80bbbce1859ecf561ffe7bca597ba37d8056967. No P0–P2 findings in the checked scope.

The design addresses the cause locally: cached templates are ready at the first commit, while CSS owns fitted geometry. Removing the post-render measurement avoids competing size updates without changing virtualizer or scroll policy.

I rebuilt core/UI and ran 106 focused Mermaid, Markdown and scroll tests successfully. In real Chromium with the production component, actual Mermaid rendering and full Desktop stylesheet, 24 warm-remount combinations (four diagram types, three widths, light/dark) retained the same first-commit and settled height. A base-code control reproduced pie 145→551→517px and tall flowchart 345→1354→517px; this head mounts directly at 517px for both. Inline/fullscreen zoom, fit/reset, Escape and fullscreen resize checks also passed.

The checked-in regression guards cached rendered state, not CSS geometry. My browser check mounts the diagram directly; I did not rerun the full long-conversation virtualizer loop, packaged Electron, Windows or the entire repository suite. Head remains unchanged and CI test is green.

@Astro-Han Astro-Han left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review notice: This comment was posted by an automated review agent. It is not an independent human review and does not replace one.

Review of exact head b80bbbce (single commit on merge-base e57b0295). CI test passes; GitHub reports MERGEABLE (merge state BLOCKED pending review).

No P0-P2 findings. The fix is sound.

What I checked:

  • Cached first commit: the lazy useState initializer reads mermaidRenderCache and starts in rendered. The render effect returns early when state.cacheKey === cacheKey, so a warm remount never commits a loading placeholder. The new Profiler assertion pins this for every commit.
  • CSS sizing matches the removed JS: collapsed --maka-mermaid-fit-width = min(natural, 100cqi - 2*space-3, (clamp(112, 480, 55vh) - 2*space-3) * ratio). That is naturalWidth * min(1, widthScale, heightScale), the old calculateMermaidFitScale. 100cqi resolves against .maka-mermaid-diagram, which is already container-type: inline-size (styles.css:667), so it is the viewport's content width. The viewport height formula reproduces the old max(112, min(maxH, h*scale + pad)). Expanded mode makes the viewport a size container, and min(100cqw, 100cqh*ratio) is the old uncapped min(widthScale, heightScale).
  • Ratio is safe: mermaidViewBoxSize only returns positive finite dimensions (it falls back to 1200x675), so --maka-mermaid-ratio can't become Infinity/NaN. React does not add px to numeric custom properties.
  • Pannable effect without rAF: inline and expanded viewports never mount together (showContent = !expanded). The Dialog renders children synchronously in a native <dialog>, and its showModal() effect runs before this parent effect. The ResizeObserver initial callback covers any late layout anyway.
  • Removed exports/attributes: nothing else in the repo uses calculateMermaidFitScale or data-maka-mermaid-layout.

One P3 inline (warm theme switch still goes through loading).

Residual risk: CSS sizing can't run in jsdom, so this PR leaves fit sizing with no automated coverage. A Storybook/visual check of one wide and one tall diagram, collapsed and expanded, would close that gap.

Comment thread packages/ui/src/mermaid-diagram.tsx Resolved

@Astro-Han Astro-Han left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review notice: This comment was posted by an automated review agent. It is not an independent human review and does not replace one.

Incremental review of b80bbbce..bdc93cc9 (one new commit, no rebase; merge-base 7c90bac2 unchanged). CI test passes; MERGEABLE (BLOCKED pending review); git merge-tree against current main is clean.

Prior P3 (cached theme switch committed loading): fixed. The render effect now checks mermaidRenderCache before setting loading, touches the LRU entry, resets zoom, and restores via renderedMermaidState, so each instance still gets fresh SVG ids. The cached branch returns with no cleanup, and that is correct: no request is in flight, and the previous effect's cleanup already cancelled any stale one. The commit between the theme change and the effect's setState still shows the old-theme SVG, never a placeholder. Manual render of a deferred diagram whose template is already cached now also skips loading, which is a small bonus.

No P0-P2 findings. One P3 inline on test strength.

Residual risk is unchanged: CSS fit geometry still has no automated coverage.

Restore cached templates directly in the render effect and preserve cache recency. Extend the theme-switch regression to check every React commit.

Generated-by: Codex
@Colafornia
Colafornia force-pushed the fix/5942-mermaid-chat-flicker branch from bdc93cc to 3eb3330 Compare October 9, 2026 01:43

@Astro-Han Astro-Han left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review notice: This comment was posted by an automated review agent. It is not an independent human review and does not replace one.

Incremental review: bdc93cc9 (our last reviewed head) to 3eb33301. The branch was re-amended: 3eb33301 is again a single commit on b80bbbce, and the merge-base with main is unchanged (7c90bac2). Compared with bdc93cc9, the only net change is in packages/ui/src/__tests__/mermaid-render-cache.test.tsx (+11/-1). mermaid-diagram.tsx is byte-identical to the head we already reviewed.

The delta is test-only, with no findings. The fake renderer now stamps the theme it rendered with into the SVG (data-theme). The test now asserts that the dark SVG is mounted after switching to dark, and that the default-theme SVG is restored after switching back from cache. Before, the test only checked render counts and that no loading state was committed. Now it also proves that the cached result for the right theme is the one shown.

Prior findings: the P3 (cached theme switch committed loading) remains fixed. No P0-P3 open.

Status: CI test passes on 3eb33301. GitHub reports MERGEABLE, with merge state BLOCKED (review required). No protocol files, so there is no epoch impact.

@Astro-Han Astro-Han left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved at @Astro-Han's explicit request. Automated review passes on this PR (including an independent pass by jackwener on an earlier head) found no P0–P2. The only P3 was fixed, the latest head adds test assertions only, and CI is green.

@Colafornia
Colafornia merged commit 847865c into apache:main Oct 9, 2026
1 check passed
@Colafornia
Colafornia deleted the fix/5942-mermaid-chat-flicker branch October 9, 2026 02:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

effort/M Under 500 readable lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(desktop): stop Mermaid chat flicker at bottom

3 participants