feat(web): render mermaid diagrams in Ask answers#1369
Conversation
Render fenced mermaid code blocks in Ask Sourcebot answers as interactive diagrams: pan/zoom, copy source/image, SVG/PNG export, fullscreen, and in-thread deep links. Diagrams are mirrored in the right panel, pre-collapsed and interleaved with referenced sources by order of appearance, with click-to-scroll between the inline diagram and its panel item. The agent is prompted to emit mermaid blocks proactively when a visual aids understanding.
This comment has been minimized.
This comment has been minimized.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughThis PR adds Mermaid diagram support to chat answers. It updates the agent prompt, renders fenced Mermaid blocks, adds an interactive SVG viewer, and interleaves diagrams with referenced sources in the thread panel. ChangesChat Mermaid diagram rendering
Sequence Diagram(s)sequenceDiagram
participant ChatThreadListItem
participant MarkdownRenderer
participant DiagramReferenceChip
participant ReferencedSourcesListView
participant DiagramPanelListItem
participant MermaidDiagram
ChatThreadListItem->>MarkdownRenderer: render answer markdown with diagrams enabled
MarkdownRenderer->>DiagramReferenceChip: render mermaid fences as inline references
DiagramReferenceChip->>ReferencedSourcesListView: reveal diagram in side panel
ReferencedSourcesListView->>DiagramPanelListItem: render diagram item
DiagramPanelListItem->>MermaidDiagram: mount expanded diagram code
ChatThreadListItem->>ReferencedSourcesListView: pass ordered diagram and source items
Estimated review effort🎯 4 (Complex) | ⏱️ ~60 minutes Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
License Audit
Weak Copyleft Packages (informational)
Resolved Packages (22)
|
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (1)
packages/web/src/ee/features/chat/components/chatThread/chatThreadListItem.tsx (1)
366-423: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReuse the shared Mermaid and file-reference parser contracts here.
Line 377 redefines both the Mermaid block matcher and the
@file:prefix instead of reusingMERMAID_BLOCK_REGEXandFILE_REFERENCE_PREFIX.useExtractDiagrams()already depends on the shared Mermaid regex, so this scan can drift and leave diagrams or file references resolved elsewhere but missing or misordered in the right panel.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/web/src/ee/features/chat/components/chatThread/chatThreadListItem.tsx` around lines 366 - 423, The ordered panel scan in chatThreadListItem.tsx is duplicating Mermaid and file-reference parsing rules instead of reusing the shared contracts. Update orderedPanelItems to use MERMAID_BLOCK_REGEX and FILE_REFERENCE_PREFIX (the same symbols used by useExtractDiagrams and file-reference parsing) so the right panel stays aligned with the rest of the app and does not drift on diagram or `@file`: matching.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/web/src/ee/features/chat/components/chatThread/mermaidDiagram.tsx`:
- Around line 215-246: The Mermaid action bar in mermaidDiagram.tsx is only
revealed via group-hover, which hides fullscreen/copy/export on touch and
keyboard-only interactions. Update the toolbar container around the
actions/buttons to also become visible on focus-within and for non-hover/coarse
pointer environments, so the same controls are discoverable without hover. Use
the existing toolbar wrapper and its forceControlsVisible/controlsClassName
visibility logic to add the extra visibility conditions without changing the
button behavior.
- Around line 347-357: The copy actions in mermaidDiagram’s onCopyLink and
onCopySource currently show success before the clipboard write completes, so
update both callbacks to mirror onCopyImage by awaiting
navigator.clipboard.writeText inside try/catch. If the write succeeds, keep the
success toast; if it fails, show a destructive toast with an appropriate failure
message. Use the existing onCopyLink, onCopySource, and onCopyImage functions as
the reference points for the change.
In `@packages/web/src/ee/features/chat/diagramUtils.ts`:
- Around line 15-18: The diagram id/anchor generation in getDiagramId and
getDiagramAnchorId is based only on the diagram code, so repeated identical
diagrams collide across a thread. Update the id generation to include a
per-message or per-occurrence disambiguator while preserving the content hash as
a separate stable key if needed, and make sure the DOM id/anchor returned by
getDiagramAnchorId is unique for each rendered instance.
- Line 2: The Mermaid extractor regex in MERMAID_BLOCK_REGEX only accepts LF
after the opening fence, so update it to also match CRLF. Adjust the pattern
used by useExtractDiagrams() in diagramUtils so fenced Mermaid blocks with \r\n
are captured the same as \n, preserving diagram extraction, right-panel
mirroring, and deep-link ordering.
---
Nitpick comments:
In
`@packages/web/src/ee/features/chat/components/chatThread/chatThreadListItem.tsx`:
- Around line 366-423: The ordered panel scan in chatThreadListItem.tsx is
duplicating Mermaid and file-reference parsing rules instead of reusing the
shared contracts. Update orderedPanelItems to use MERMAID_BLOCK_REGEX and
FILE_REFERENCE_PREFIX (the same symbols used by useExtractDiagrams and
file-reference parsing) so the right panel stays aligned with the rest of the
app and does not drift on diagram or `@file`: matching.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 4477ca7a-9695-4ad0-8223-bddc58bb0915
⛔ Files ignored due to path filters (1)
yarn.lockis excluded by!**/yarn.lock,!**/*.lock
📒 Files selected for processing (12)
CHANGELOG.mdpackages/web/package.jsonpackages/web/src/ee/features/chat/agent.tspackages/web/src/ee/features/chat/components/chatThread/answerCard.tsxpackages/web/src/ee/features/chat/components/chatThread/chatThreadListItem.tsxpackages/web/src/ee/features/chat/components/chatThread/diagramPanelListItem.tsxpackages/web/src/ee/features/chat/components/chatThread/markdownRenderer.tsxpackages/web/src/ee/features/chat/components/chatThread/mermaidDiagram.tsxpackages/web/src/ee/features/chat/components/chatThread/referencedSourcesListView.tsxpackages/web/src/ee/features/chat/diagramPanelContext.tsxpackages/web/src/ee/features/chat/diagramUtils.tspackages/web/src/ee/features/chat/useExtractDiagrams.ts
Make the right "evidence" panel the canonical, default-expanded render for mermaid diagrams and turn the inline answer occurrence into a compact "Diagram"/title reference button that scrolls to and focuses its panel counterpart on click, with hover-sync, mirroring the file-reference chips. The raw mermaid fence in the answer text is untouched, so copy stays valid. Also: - Let the model name diagrams via a mermaid frontmatter title (used as the chip/panel label, falling back to "Diagram N"), with prompt guidance to quote titles containing special characters. - Show a shine-sweep shimmer on the in-progress diagram chip while streaming. - Fix fullscreen zoom to fit-to-surface on open (measured from the rendered SVG), add cursor-anchored scroll-to-zoom, and make the readout relative so the fitted view reads 100%. - Fix the right panel hover ring being clipped at the top edge. Co-authored-by: Cursor <cursoragent@cursor.com>
f05c3d0 to
ee54b41
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/web/src/ee/features/chat/components/chatThread/mermaidDiagram.tsx`:
- Around line 248-268: The useEffect in mermaidDiagram should make the svg
dependency meaningful instead of leaving it unused, since the effect is meant to
refit when the rendered SVG changes. Update the guard inside this effect to
reference svg directly before scheduling the
ResizeObserver/requestAnimationFrame work, and keep the dependency list aligned
with the effect’s actual usage in fitToSurface and the svg-driven render state.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: e991f074-04ce-435b-8ca6-97ffe4639fbb
📒 Files selected for processing (11)
packages/web/src/components/ui/animatedShinyText.tsxpackages/web/src/ee/features/chat/agent.tspackages/web/src/ee/features/chat/components/chatThread/chatThreadListItem.tsxpackages/web/src/ee/features/chat/components/chatThread/diagramPanelListItem.tsxpackages/web/src/ee/features/chat/components/chatThread/diagramReferenceChip.tsxpackages/web/src/ee/features/chat/components/chatThread/markdownRenderer.tsxpackages/web/src/ee/features/chat/components/chatThread/mermaidDiagram.tsxpackages/web/src/ee/features/chat/components/chatThread/referencedSourcesListView.tsxpackages/web/src/ee/features/chat/diagramPanelContext.tsxpackages/web/src/ee/features/chat/diagramUtils.tspackages/web/tailwind.config.ts
✅ Files skipped from review due to trivial changes (1)
- packages/web/src/ee/features/chat/agent.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- packages/web/src/ee/features/chat/components/chatThread/diagramPanelListItem.tsx
- packages/web/src/ee/features/chat/components/chatThread/chatThreadListItem.tsx
- packages/web/src/ee/features/chat/components/chatThread/referencedSourcesListView.tsx
After the inline reference-chip redesign, MermaidDiagram is only ever rendered in the right panel. Remove the unused inline variant, deep-link effect, and "view in panel"/jump actions, and collapse DiagramViewport's three size modes down to fullscreen-fill vs. panel auto-height. Co-authored-by: Cursor <cursoragent@cursor.com>
…item header for diagrams. Also shore up diagram header to avoid overflow visual artifact
… into common panel items
@whoisthey nice lgtm 👍 |
|
Preview deployment for your docs. Learn more about Mintlify Previews.
💡 Tip: Enable Workflows to automatically generate PRs for you. |




Fixes #1240
Summary
```mermaidblocks in Ask Sourcebot answers as interactive diagrams (click-drag pan, zoom, copy source/image, SVG/PNG export, fullscreen) through the existing markdown rendering pipeline — no new stream part type or tool.title(used as the chip/panel label, falling back to "Diagram N"), with prompt guidance to quote titles containing special characters so the frontmatter stays valid. The agent is still prompted to emit diagrams proactively when a visual aids understanding.#diagram-<hash>) that reveal/scroll to the panel diagram.mermaidis lazy-loaded so it stays out of the initial bundle; invalid/streaming source falls back to a code block.Test plan
```mermaidblock; deep links scroll/reveal correctly; invalid or mid-stream mermaid shows the source as a code block until it renders cleanly.Notes
This is the V1 "automatic" path from #1240 plus proactive prompting. The explicit "Visualize" button and the V2 interactive React Flow engine are intentionally out of scope, pending followup gen-UI feature work.
Based on review feedback, the inline rendering was reworked from a full inline diagram (which duplicated the right-panel diagram and defaulted the panel item to collapsed) into a reference chip that defers to the canonical, default-expanded panel diagram. The screenshots below predate that redesign.
Analytics
Adds PostHog events (web-only, prefixed
wa_chat_diagram_) to understand how often the model generates diagrams (and how often they're invalid), and how often users interact with them. Every event carrieschatIdand a content-hasheddiagramId:wa_chat_diagram_rendered—{ outcome: 'success' | 'error', diagramType? }. Fired once per diagram generated live in a session (gated on having observed streaming, so revisiting a chat or viewing one from history does not re-fire). This is the generation/quality signal: generation frequency, diagram type breakdown, and the invalid-render rate.wa_chat_diagram_reference_clicked— the inline reference chip was clicked to focus its panel diagram.wa_chat_diagram_fullscreen_opened— the diagram was opened in fullscreen.wa_chat_diagram_copied—{ format: 'link' | 'source' | 'image' }.wa_chat_diagram_exported—{ format: 'svg' | 'png' }.wa_chat_diagram_panned— click-drag pan on the inline (non-fullscreen) view, reported at most once per diagram.The five interaction events are user-gated (fired from click/drag handlers), so none of them fire on mount or when a chat is revisited.
Screen.Recording.2026-06-25.at.5.35.52.PM.mov
Summary by CodeRabbit