Repository: assistant-ui/assistant-ui
Pull request #2002: feat: Add first class support for Mermaid diagrams
Author: login: AVGVSTVS96
Labels: name: enhancement
description: New feature or request
Created: 2025-05-24T04:27:33Z | Merged: 2025-05-27T23:46:05Z


<!-- ELLIPSIS_HIDDEN -->


> [!IMPORTANT]
> Adds first-class support for Mermaid diagrams with a new component, documentation, styling, and updated dependencies.
> 
>   - **Behavior**:
>     - Adds `MermaidDiagram` component in `mermaid-diagram.tsx` for rendering Mermaid diagrams in chat messages.
>     - Optimized for streaming: smart completion detection and zero failed renders.
>     - Supports various diagram types: flowcharts, sequence diagrams, Gantt charts, etc.
>   - **Documentation**:
>     - New `Mermaid.mdx` file documents how to add and configure the `mermaid-diagram` component.
>     - Updates `meta.json` to include "Mermaid" in the documentation pages.
>   - **Styles**:
>     - Adds `.aui-mermaid-diagram` class in `markdown.css` for styling Mermaid diagrams.
>   - **Dependencies**:
>     - Adds `mermaid` as a dependency in `package.json`.
>   - **Registry**:
>     - Updates `registry.ts` to include `mermaid-diagram` as a registry component.
> 
> <sup>This description was created by </sup>[<img alt="Ellipsis" src="https://img.shields.io/badge/Ellipsis-blue?color=175173">](https://www.ellipsis.dev?ref=assistant-ui%2Fassistant-ui&utm_source=github&utm_medium=referral)<sup> for 85c5c05e89e688ab76d9e111346a97ddb5a0667c. You can [customize](https://app.ellipsis.dev/assistant-ui/settings/summaries) this summary. It will automatically update as commits are pushed.</sup>


<!-- ELLIPSIS_HIDDEN -->


Diff:
diff --git a/.changeset/mighty-actors-brake.md b/.changeset/mighty-actors-brake.md
new file mode 100644
index 0000000000..24047a56a5
--- /dev/null
+++ b/.changeset/mighty-actors-brake.md
@@ -0,0 +1,5 @@
+---
+"@assistant-ui/styles": patch
+---
+
+feat: Add first class support for Mermaid diagrams
diff --git a/apps/docs/content/docs/ui/Mermaid.mdx b/apps/docs/content/docs/ui/Mermaid.mdx
new file mode 100644
index 0000000000..8f68f962c3
--- /dev/null
+++ b/apps/docs/content/docs/ui/Mermaid.mdx
@@ -0,0 +1,79 @@
+---
+title: "Mermaid Diagrams"
+---
+
+import { Callout } from "fumadocs-ui/components/callout";
+import { Step, Steps } from "fumadocs-ui/components/steps";
+
+Render Mermaid diagrams in chat messages with the `mermaid-diagram` component.
+
+<Steps>
+  <Step>
+
+### Add `mermaid-diagram` component
+
+```bash
+npx shadcn@latest add "https://r.assistant-ui.com/mermaid-diagram"
+```
+
+This will install the required dependencies and add the component to your project.
+
+  </Step>
+  <Step>
+
+### Add it to `componentsByLanguage` in `markdown-text.tsx`
+
+```tsx title="/components/assistant-ui/markdown-text.tsx"
+import { MermaidDiagram } from "@/components/assistant-ui/mermaid-diagram"; // [!code ++]
+
+const MarkdownTextImpl = () => {
+  return (
+    <MarkdownTextPrimitive
+      remarkPlugins={[remarkGfm]}
+      className="aui-md"
+      components={defaultComponents}
+      componentsByLanguage={{               // [!code ++]
+        mermaid: {                          // [!code ++]
+          SyntaxHighlighter: MermaidDiagram // [!code ++]
+        },                                  // [!code ++]
+      }}                                    // [!code ++]
+    />
+  );
+};
+
+export const MarkdownText = memo(MarkdownTextImpl);
+```
+
+  </Step>
+</Steps>
+
+## Configuration
+
+Configure mermaid options in `mermaid-diagram.tsx`:
+
+```tsx title="/components/assistant-ui/mermaid-diagram.tsx"
+mermaid.initialize({ theme: "default" });
+```
+
+## Streaming Performance
+
+The `MermaidDiagram` component is optimized for streaming scenarios:
+
+- **Smart completion detection**: Only renders when the specific code block is complete
+- **Zero failed renders**: Avoids parsing incomplete diagram code during streaming  
+
+
+## Supported Diagram Types
+
+Mermaid supports various diagram types including:
+
+- Flowcharts and decision trees
+- Sequence diagrams  
+- Gantt charts
+- Class diagrams
+- State diagrams
+- Git graphs
+- User journey maps
+- Entity relationship diagrams
+
+See the [Mermaid documentation](https://mermaid.js.org/) for complete syntax reference.
diff --git a/apps/docs/content/docs/ui/meta.json b/apps/docs/content/docs/ui/meta.json
index d3348df2aa..aae1104631 100644
--- a/apps/docs/content/docs/ui/meta.json
+++ b/apps/docs/content/docs/ui/meta.json
@@ -7,6 +7,7 @@
     "AssistantModal",
     "AssistantSidebar",
     "Markdown",
+    "Mermaid",
     "SyntaxHighlighting",
     "ToolFallback",
     "Scrollbar"
diff --git a/apps/registry/components/assistant-ui/mermaid-diagram.tsx b/apps/registry/components/assistant-ui/mermaid-diagram.tsx
new file mode 100644
index 0000000000..bc18347413
--- /dev/null
+++ b/apps/registry/components/assistant-ui/mermaid-diagram.tsx
@@ -0,0 +1,89 @@
+"use client";
+
+import { useContentPart } from "@assistant-ui/react";
+import type { SyntaxHighlighterProps } from "@assistant-ui/react-markdown";
+import mermaid from "mermaid";
+import { FC, useEffect, useRef } from "react";
+import { cn } from "@/lib/utils";
+
+/**
+ * Props for the MermaidDiagram component
+ */
+export type MermaidDiagramProps = SyntaxHighlighterProps & {
+  className?: string;
+};
+
+// Configure mermaid options here
+mermaid.initialize({ theme: "default" });
+
+/**
+ * MermaidDiagram component for rendering Mermaid diagrams
+ * Use it by passing to `componentsByLanguage` for mermaid in `markdown-text.tsx`
+ *
+ * @example
+ * const MarkdownTextImpl = () => {
+ *   return (
+ *     <MarkdownTextPrimitive
+ *       remarkPlugins={[remarkGfm]}
+ *       className="aui-md"
+ *       components={defaultComponents}
+ *       componentsByLanguage={{
+ *         mermaid: {
+ *           SyntaxHighlighter: MermaidDiagram
+ *         },
+ *       }}
+ *     />
+ *   );
+ * };
+ */
+export const MermaidDiagram: FC<MermaidDiagramProps> = ({
+  code,
+  className,
+  node: _node,
+  components: _components,
+  language: _language,
+}) => {
+  const ref = useRef<HTMLPreElement>(null);
+
+  // Detect when this code block is complete
+  const isComplete = useContentPart((part) => {
+    if (part.type !== "text") return false;
+
+    // Find the position of this code block
+    const codeIndex = part.text.indexOf(code);
+    if (codeIndex === -1) return false;
+
+    // Check if there are closing backticks immediately after this code block
+    const afterCode = part.text.substring(codeIndex + code.length);
+
+    // Look for the closing backticks - should be at the start or after a newline
+    const closingBackticksMatch = afterCode.match(/^```|^\n```/);
+    return closingBackticksMatch !== null;
+  });
+
+  useEffect(() => {
+    if (!isComplete) return;
+
+    (async () => {
+      try {
+        const element = document.createElement("div");
+        element.textContent = code;
+        element.classList.add("mermaid");
+        await mermaid.run({ nodes: [element] });
+        if (ref.current) {
+          ref.current.replaceChildren(element);
+        }
+      } catch (e) {
+        console.warn("Failed to render Mermaid diagram:", e);
+      }
+    })();
+  }, [isComplete, code]);
+
+  return (
+    <pre ref={ref} className={cn("aui-mermaid-diagram", className)}>
+      Drawing diagram...
+    </pre>
+  );
+};
+
+MermaidDiagram.displayName = "MermaidDiagram";
diff --git a/apps/registry/package.json b/apps/registry/package.json
index aface1fde8..c9c15308f3 100644
--- a/apps/registry/package.json
+++ b/apps/registry/package.json
@@ -8,8 +8,8 @@
     "@ai-sdk/openai": "^1.3.22",
     "@assistant-ui/react": "workspace:*",
     "@assistant-ui/react-markdown": "workspace:*",
-    "@assistant-ui/styles": "workspace:*",
     "@assistant-ui/react-syntax-highlighter": "workspace:*",
+    "@assistant-ui/styles": "workspace:*",
     "@assistant-ui/x-buildutils": "workspace:*",
     "@radix-ui/react-avatar": "^1.1.10",
     "@radix-ui/react-dialog": "^1.1.14",
@@ -27,8 +27,8 @@
     "lucide-react": "^0.511.0",
     "react": "19.1.0",
     "react-resizable-panels": "^3.0.2",
-    "react-syntax-highlighter": "^15.6.1",
     "react-shiki": "^0.6.0",
+    "react-syntax-highlighter": "^15.6.1",
     "rehype-katex": "^7.0.1",
     "remark-gfm": "^4.0.1",
     "remark-math": "^6.0.0",
@@ -42,5 +42,8 @@
   "scripts": {
     "build": "tsx ./scripts/build-registry.ts",
     "lint": "eslint ."
+  },
+  "dependencies": {
+    "mermaid": "^11.6.0"
   }
 }
diff --git a/apps/registry/src/registry.ts b/apps/registry/src/registry.ts
index 4f007257b3..1e5cca17f7 100644
--- a/apps/registry/src/registry.ts
+++ b/apps/registry/src/registry.ts
@@ -186,4 +186,19 @@ export const registry: RegistryItem[] = [
     ],
     dependencies: ["react-shiki"],
   },
+  {
+    name: "mermaid-diagram",
+    type: "registry:component",
+    files: [
+      {
+        type: "registry:component",
+        path: "components/assistant-ui/mermaid-diagram.tsx",
+      },
+    ],
+    dependencies: [
+      "mermaid",
+      "@assistant-ui/react",
+      "@assistant-ui/react-markdown",
+    ],
+  },
 ];
diff --git a/packages/styles/src/styles/tailwindcss/markdown.css b/packages/styles/src/styles/tailwindcss/markdown.css
index def02cd4b5..8c89617eb3 100644
--- a/packages/styles/src/styles/tailwindcss/markdown.css
+++ b/packages/styles/src/styles/tailwindcss/markdown.css
@@ -88,4 +88,6 @@
   @apply bg-muted rounded border font-semibold;
 }
 
-
+.aui-mermaid-diagram {
+  @apply bg-muted rounded-b-lg p-2 text-center [&_svg]:mx-auto;
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 9b9a9eb1f1..e279a914e7 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -233,6 +233,10 @@ importers:
         version: 5.8.3
 
   apps/registry:
+    dependencies:
+      mermaid:
+        specifier: ^11.6.0
+        version: 11.6.0
     devDependencies:
       '@ai-sdk/openai':
         specifier: ^1.3.22


Reviews:
user: login: copilot-pull-request-reviewer[bot]
body: ## Pull Request Overview

Add first-class support for rendering Mermaid diagrams by introducing styling, registry integration, component implementation, and documentation.

- Define a new `.aui-mermaid-diagram` Tailwind class for Mermaid blocks  
- Register `mermaid-diagram` in the component registry and pin the `mermaid` dependency  
- Implement the `MermaidDiagram` React component and provide a new MDX docs page

### Reviewed Changes

Copilot reviewed 6 out of 7 changed files in this pull request and generated no comments.

<details>
<summary>Show a summary per file</summary>

| File                                                       | Description                                        |
| ---------------------------------------------------------- | -------------------------------------------------- |
| packages/styles/src/styles/tailwindcss/markdown.css        | Added `.aui-mermaid-diagram` utility styles        |
| apps/registry/src/registry.ts                              | Registered the new `mermaid-diagram` component     |
| apps/registry/package.json                                 | Added `mermaid` under dependencies                 |
| apps/registry/components/assistant-ui/mermaid-diagram.tsx  | Created the `MermaidDiagram` component             |
| apps/docs/content/docs/ui/meta.json                        | Included `Mermaid` in the UI docs metadata list    |
| apps/docs/content/docs/ui/Mermaid.mdx                      | Added documentation page for Mermaid diagrams      |
</details>


<details>
<summary>Files not reviewed (1)</summary>

* **pnpm-lock.yaml**: Language not supported
</details>

<details>
<summary>Comments suppressed due to low confidence (4)</summary>

**apps/registry/components/assistant-ui/mermaid-diagram.tsx:1**
* The new `MermaidDiagram` component does not have associated tests; consider adding unit or integration tests to verify rendering and error handling.
```
"use client";
```
**apps/registry/src/registry.ts:189**
* The registry entry for `mermaid-diagram` omits the `@assistant-ui/styles` dependency, so the `.aui-mermaid-diagram` CSS won’t be included when users install this component.
```
{
```
**apps/registry/components/assistant-ui/mermaid-diagram.tsx:60**
* Assigning user-provided `code` to `innerHTML` may introduce XSS risks; consider using `textContent` or sanitizing the input before rendering.
```
element.innerHTML = code;
```
**apps/docs/content/docs/ui/Mermaid.mdx:5**
* The `Callout` import is not used in this file; you can remove it to avoid unused code.
```
import { Callout } from "fumadocs-ui/components/callout";
```
</details>


state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-05-24T04:28:31Z
user: login: greptile-apps[bot]
body: 
## PR Summary

Added first-class support for Mermaid diagrams with a new component and documentation, enabling dynamic diagram rendering within chat messages.

- New `mermaid-diagram.tsx` component with streaming-optimized rendering that only processes complete code blocks
- Added Mermaid documentation in `Mermaid.mdx` with installation steps and configuration guide
- Added `.aui-mermaid-diagram` class in `markdown.css` for consistent styling with existing code blocks
- Added `mermaid` v11.6.0 as runtime dependency in `package.json`
- Registered `mermaid-diagram` component in `registry.ts` with proper dependencies and file paths

<sub>6 file(s) reviewed, 4 comment(s)</sub>
<sub>[Edit PR Review Bot Settings](https://app.greptile.com/review/github) | [Greptile](https://greptile.com?utm_source=greptile_expert&utm_medium=github&utm_campaign=code_reviews&utm_content=assistant-ui_2002)</sub>
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-05-24T04:29:40Z
user: login: coderabbitai[bot]
body: **Actionable comments posted: 4**

<details>
<summary>🧹 Nitpick comments (2)</summary><blockquote>

<details>
<summary>apps/docs/content/docs/ui/Mermaid.mdx (1)</summary><blockquote>

`5-7`: **Remove unused import**: The `Callout` import is not used in this document and can be removed to keep the code clean.

</blockquote></details>
<details>
<summary>apps/registry/components/assistant-ui/mermaid-diagram.tsx (1)</summary><blockquote>

`42-44`: **Consider using rest operator to clean up unused parameters.**

The underscored parameters are intentionally unused, which is fine, but you can clean up the ESLint warnings by using the rest operator pattern:

```diff
export const MermaidDiagram: FC<MermaidDiagramProps> = ({
  code,
  className,
-  node: _node,
-  components: _components,
-  language: _language,
+  ...props
}) => {
```

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 GitHub Check: ESLint & Prettier</summary>

[failure] 44-44: 
'_language' is defined but never used  

---

[failure] 43-43: 
'_components' is defined but never used

---

[failure] 42-42: 
'_node' is defined but never used      

</details>

</details>

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

**Configuration used: CodeRabbit UI**
**Review profile: CHILL**
**Plan: Pro**


<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 49dc68548a11b16c009276d9141488b1ccf3a0ed and 2f4284cafcd3378f562af6814856160091e9a37d.

</details>

<details>
<summary>⛔ Files ignored due to path filters (1)</summary>

* `pnpm-lock.yaml` is excluded by `!**/pnpm-lock.yaml`

</details>

<details>
<summary>📒 Files selected for processing (6)</summary>

* `apps/docs/content/docs/ui/Mermaid.mdx` (1 hunks)
* `apps/docs/content/docs/ui/meta.json` (1 hunks)
* `apps/registry/components/assistant-ui/mermaid-diagram.tsx` (1 hunks)
* `apps/registry/package.json` (3 hunks)
* `apps/registry/src/registry.ts` (1 hunks)
* `packages/styles/src/styles/tailwindcss/markdown.css` (1 hunks)

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>🪛 GitHub Check: ESLint & Prettier</summary>

<details>
<summary>apps/registry/components/assistant-ui/mermaid-diagram.tsx</summary>

[failure] 44-44: 
'_language' is defined but never used  

---

[failure] 43-43: 
'_components' is defined but never used

---

[failure] 42-42: 
'_node' is defined but never used      

</details>

</details>
<details>
<summary>🪛 GitHub Actions: Code Quality</summary>

<details>
<summary>apps/registry/components/assistant-ui/mermaid-diagram.tsx</summary>

[error] 1-1: Prettier formatting check failed. Run 'prettier --write' to fix code style issues.

</details>

</details>

</details>

<details>
<summary>⏰ Context from checks skipped due to timeout of 90000ms (2)</summary>

* GitHub Check: Greptile Review
* GitHub Check: Analyze (javascript-typescript)

</details>

<details>
<summary>🔇 Additional comments (8)</summary><blockquote>

<details>
<summary>packages/styles/src/styles/tailwindcss/markdown.css (1)</summary>

`85-88`: **Mermaid diagram styling added**  
The `.aui-mermaid-diagram` class correctly applies a muted background and rounded bottom corners, aligning with existing markdown element styles.

</details>
<details>
<summary>apps/registry/package.json (1)</summary>

`12-12`: Also applies to: 31-31

</details>
<details>
<summary>apps/docs/content/docs/ui/meta.json (1)</summary>

`10-10`: **Documentation navigation updated**: Added `"Mermaid"` entry between `"Markdown"` and `"SyntaxHighlighting"` to surface the new Mermaid diagrams page.

</details>
<details>
<summary>apps/registry/src/registry.ts (1)</summary>

`189-203`: **Register `mermaid-diagram` component**: The new registry entry correctly references `components/assistant-ui/mermaid-diagram.tsx` and includes the necessary dependencies (`mermaid`, `@assistant-ui/react`, `@assistant-ui/react-markdown`).

</details>
<details>
<summary>apps/docs/content/docs/ui/Mermaid.mdx (2)</summary>

`1-3`: **Frontmatter is correct**: The title `"Mermaid Diagrams"` matches the entry in `meta.json` and aligns with the feature being documented.

---

`10-17`: Also applies to: 26-45, 52-56, 60-64, 68-79

</details>
<details>
<summary>apps/registry/components/assistant-ui/mermaid-diagram.tsx (2)</summary>

`1-7`: **Clean imports and proper client directive setup.**

The imports are well-organized and include all necessary dependencies for the Mermaid diagram functionality.

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 GitHub Actions: Code Quality</summary>

[error] 1-1: Prettier formatting check failed. Run 'prettier --write' to fix code style issues.

</details>

</details>

---

`9-17`: **Well-defined types and proper mermaid initialization.**

The type definition correctly extends `SyntaxHighlighterProps` and the mermaid initialization with default theme is appropriate.

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-05-24T04:31:38Z
user: login: coderabbitai[bot]
body: **Actionable comments posted: 0**

<details>
<summary>♻️ Duplicate comments (4)</summary><blockquote>

<details>
<summary>apps/registry/components/assistant-ui/mermaid-diagram.tsx (4)</summary><blockquote>

`17-17`: **Move mermaid initialization inside the component to prevent SSR issues.**

The mermaid initialization is still happening at module level, which can cause issues during server-side rendering as mentioned in previous reviews.



Move the initialization inside a `useEffect` hook:

```diff
-// Configure mermaid options here
-mermaid.initialize({ theme: "default" });
```

Then add inside the component:

```diff
+  useEffect(() => {
+    mermaid.initialize({ theme: "default" });
+  }, []);
```

---

`49-51`: **The completion detection logic remains fragile and should be improved.**

The current completion detection approach using `part.text.split(code)[1]?.includes("```")` still has the edge cases mentioned in previous reviews:

1. If the mermaid code contains the same string as `code`, the split logic could behave unexpectedly
2. Multiple code blocks could cause confusion
3. It assumes the code block always ends with exactly ```



Consider using a more robust regex-based approach:

```diff
-  const isComplete = useContentPart((part) => {
-    if (part.type !== "text") return false;
-    return part.text.split(code)[1]?.includes("```");
-  });
+  const isComplete = useContentPart((part) => {
+    if (part.type !== "text") return false;
+    // Use regex to find the code block and check if it ends with ```
+    const regex = new RegExp(`\`\`\`mermaid\\s*\\n${code.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*\\n\`\`\``, 'g');
+    return regex.test(part.text);
+  });
```

---

`62-62`: **Add null safety check for ref.current to prevent runtime errors.**

The non-null assertion `ref.current!` still assumes the ref is always available without checking, which can cause runtime errors as mentioned in previous reviews.



```diff
-        ref.current!.replaceChildren(element);
+        if (ref.current) {
+          ref.current.replaceChildren(element);
+        }
```

---

`65-65`: **Consider displaying error state to users instead of just console logging.**

While console.warn is better than silent failure, users should be informed when diagram rendering fails.



Consider showing an error message in the UI:

```diff
+  const [renderError, setRenderError] = useState<string | null>(null);

   useEffect(() => {
     if (!isComplete) return;

     (async () => {
       try {
+        setRenderError(null);
         const element = document.createElement("div");
         element.innerHTML = code;
         element.classList.add("mermaid");
-        if (ref.current) {
-          ref.current.replaceChildren(element);
-        }
+        if (ref.current) {
+          ref.current.replaceChildren(element);
+        }
         await mermaid.run({ nodes: [element] });
       } catch (e) {
         console.warn("Failed to render Mermaid diagram:", e);
+        setRenderError(e instanceof Error ? e.message : "Failed to render diagram");
       }
     })();
   }, [isComplete, code]);

   return (
     <pre ref={ref} className={cn("aui-mermaid-diagram", className)}>
-      Drawing diagram...
+      {renderError ? `Error: ${renderError}` : "Drawing diagram..."}
     </pre>
   );
```

</blockquote></details>

</blockquote></details>

<details>
<summary>🧹 Nitpick comments (1)</summary><blockquote>

<details>
<summary>apps/registry/components/assistant-ui/mermaid-diagram.tsx (1)</summary><blockquote>

`70-74`: **Consider adding ARIA attributes for better accessibility.**

The component should be more accessible to screen readers when rendering diagrams.



```diff
-    <pre ref={ref} className={cn("aui-mermaid-diagram", className)}>
+    <pre 
+      ref={ref} 
+      className={cn("aui-mermaid-diagram", className)}
+      role="img"
+      aria-label="Mermaid diagram"
+    >
       Drawing diagram...
     </pre>
```

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

**Configuration used: CodeRabbit UI**
**Review profile: CHILL**
**Plan: Pro**


<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 2f4284cafcd3378f562af6814856160091e9a37d and 51d15a8d9bf28db3a5cd8ce93d19426f9497d477.

</details>

<details>
<summary>⛔ Files ignored due to path filters (1)</summary>

* `.changeset/mighty-actors-brake.md` is excluded by `!.changeset/**`

</details>

<details>
<summary>📒 Files selected for processing (1)</summary>

* `apps/registry/components/assistant-ui/mermaid-diagram.tsx` (1 hunks)

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>🪛 GitHub Check: ESLint & Prettier</summary>

<details>
<summary>apps/registry/components/assistant-ui/mermaid-diagram.tsx</summary>

[failure] 44-44: 
'_language' is defined but never used  

---

[failure] 43-43: 
'_components' is defined but never used

---

[failure] 42-42: 
'_node' is defined but never used      

</details>

</details>

</details>

<details>
<summary>⏰ Context from checks skipped due to timeout of 90000ms (1)</summary>

* GitHub Check: Analyze (javascript-typescript)

</details>

<details>
<summary>🔇 Additional comments (1)</summary><blockquote>

<details>
<summary>apps/registry/components/assistant-ui/mermaid-diagram.tsx (1)</summary>

`42-44`: **The ESLint warnings about unused parameters are acceptable.**

The underscore-prefixed parameters (`_node`, `_components`, `_language`) are intentionally unused, which is a common TypeScript pattern to indicate they're part of the interface but not needed in this implementation.



The underscore prefix properly indicates these are intentionally unused parameters from the `SyntaxHighlighterProps` interface.

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 GitHub Check: ESLint & Prettier</summary>

[failure] 44-44: 
'_language' is defined but never used  

---

[failure] 43-43: 
'_components' is defined but never used

---

[failure] 42-42: 
'_node' is defined but never used      

</details>

</details>

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-05-24T04:45:06Z
user: login: coderabbitai[bot]
body: **Actionable comments posted: 0**

<details>
<summary>♻️ Duplicate comments (4)</summary><blockquote>

<details>
<summary>apps/registry/components/assistant-ui/mermaid-diagram.tsx (4)</summary><blockquote>

`17-17`: **Move mermaid initialization to prevent SSR issues.**

The mermaid initialization at module level can cause issues during server-side rendering since `mermaid` expects a browser environment.



Move the initialization inside a `useEffect` to ensure it only runs on the client:

```diff
-// Configure mermaid options here
-mermaid.initialize({ theme: "default" });
```

Then add this inside the component:

```diff
export const MermaidDiagram: FC<MermaidDiagramProps> = ({
  code,
  className,
  node: _node,
  components: _components,
  language: _language,
}) => {
  const ref = useRef<HTMLPreElement>(null);
+
+  // Configure mermaid options in useEffect to prevent SSR issues
+  useEffect(() => {
+    mermaid.initialize({ theme: "default" });
+  }, []);
```

---

`49-51`: **Improve completion detection robustness.**

The current completion detection logic has potential edge cases where it could fail if the mermaid code itself contains the split string or with multiple code blocks.



Consider a more robust pattern matching approach:

```diff
  const isComplete = useContentPart((part) => {
    if (part.type !== "text") return false;
-    return part.text.split(code)[1]?.includes("```");
+    // More robust pattern to detect closing backticks after the code
+    const codeIndex = part.text.indexOf(code);
+    if (codeIndex === -1) return false;
+    const afterCode = part.text.slice(codeIndex + code.length);
+    return /^\s*```/.test(afterCode);
  });
```

---

`62-62`: **Add null safety check for ref access.**

The non-null assertion `ref.current!` can cause runtime errors if the ref is unexpectedly null.



Add a safety check:

```diff
-        ref.current!.replaceChildren(element);
+        if (ref.current) {
+          ref.current.replaceChildren(element);
+        }
```

---

`64-66`: **Enhance error handling with user feedback.**

Currently, rendering errors are only logged to the console without providing visual feedback to users.



Consider showing an error state in the UI:

```diff
export const MermaidDiagram: FC<MermaidDiagramProps> = ({
  code,
  className,
  node: _node,
  components: _components,
  language: _language,
}) => {
  const ref = useRef<HTMLPreElement>(null);
+  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!isComplete) return;

    (async () => {
      try {
+        setError(null);
        const element = document.createElement("div");
        element.innerHTML = code;
        element.classList.add("mermaid");
        if (ref.current) {
          ref.current.replaceChildren(element);
        }
        await mermaid.run({ nodes: [element] });
      } catch (e) {
-        console.warn("Failed to render Mermaid diagram:", e);
+        const errorMessage = "Failed to render Mermaid diagram";
+        console.warn(errorMessage, e);
+        setError(errorMessage);
      }
    })();
  }, [isComplete, code]);

  return (
    <pre ref={ref} className={cn("aui-mermaid-diagram", className)}>
-      Drawing diagram...
+      {error ? error : "Drawing diagram..."}
    </pre>
  );
```

</blockquote></details>

</blockquote></details>

<details>
<summary>🧹 Nitpick comments (1)</summary><blockquote>

<details>
<summary>apps/registry/components/assistant-ui/mermaid-diagram.tsx (1)</summary><blockquote>

`42-44`: **Address unused variable warnings.**

The static analysis correctly identifies unused destructured props. These are required by the `SyntaxHighlighterProps` interface but not used in this implementation.



Consider using more explicit naming or add ESLint disable comment:

```diff
export const MermaidDiagram: FC<MermaidDiagramProps> = ({
  code,
  className,
-  node: _node,
-  components: _components,
-  language: _language,
+  node: _node, // eslint-disable-line @typescript-eslint/no-unused-vars
+  components: _components, // eslint-disable-line @typescript-eslint/no-unused-vars  
+  language: _language, // eslint-disable-line @typescript-eslint/no-unused-vars
}) => {
```

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 GitHub Check: ESLint & Prettier</summary>

[failure] 44-44: 
'_language' is defined but never used  

---

[failure] 43-43: 
'_components' is defined but never used

---

[failure] 42-42: 
'_node' is defined but never used      

</details>

</details>

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

**Configuration used: CodeRabbit UI**
**Review profile: CHILL**
**Plan: Pro**


<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 9d1befe547e2725f6ad3ea10d1b09e36539895d9 and 832b1c821efebf05800afc8d12ee6eb49489e193.

</details>

<details>
<summary>⛔ Files ignored due to path filters (2)</summary>

* `.changeset/mighty-actors-brake.md` is excluded by `!.changeset/**`
* `pnpm-lock.yaml` is excluded by `!**/pnpm-lock.yaml`

</details>

<details>
<summary>📒 Files selected for processing (6)</summary>

* `apps/docs/content/docs/ui/Mermaid.mdx` (1 hunks)
* `apps/docs/content/docs/ui/meta.json` (1 hunks)
* `apps/registry/components/assistant-ui/mermaid-diagram.tsx` (1 hunks)
* `apps/registry/package.json` (3 hunks)
* `apps/registry/src/registry.ts` (1 hunks)
* `packages/styles/src/styles/tailwindcss/markdown.css` (1 hunks)

</details>

<details>
<summary>🚧 Files skipped from review as they are similar to previous changes (5)</summary>

* packages/styles/src/styles/tailwindcss/markdown.css
* apps/docs/content/docs/ui/meta.json
* apps/registry/package.json
* apps/registry/src/registry.ts
* apps/docs/content/docs/ui/Mermaid.mdx

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>🪛 GitHub Check: ESLint & Prettier</summary>

<details>
<summary>apps/registry/components/assistant-ui/mermaid-diagram.tsx</summary>

[failure] 44-44: 
'_language' is defined but never used  

---

[failure] 43-43: 
'_components' is defined but never used

---

[failure] 42-42: 
'_node' is defined but never used      

</details>

</details>

</details>

<details>
<summary>⏰ Context from checks skipped due to timeout of 90000ms (1)</summary>

* GitHub Check: Analyze (javascript-typescript)

</details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-05-25T20:02:37Z
user: login: coderabbitai[bot]
body: **Actionable comments posted: 0**

<details>
<summary>♻️ Duplicate comments (3)</summary><blockquote>

<details>
<summary>apps/docs/content/docs/ui/Mermaid.mdx (1)</summary><blockquote>

`71-71`: **Fix trailing whitespace.**

There is extra whitespace after 'Sequence diagrams' that should be removed.

</blockquote></details>
<details>
<summary>apps/registry/components/assistant-ui/mermaid-diagram.tsx (2)</summary><blockquote>

`17-17`: **Move mermaid initialization to prevent SSR issues.**

Initializing mermaid at module level can cause issues during server-side rendering.

---

`62-62`: **Add null safety check for ref access.**

The non-null assertion `ref.current!` could cause runtime errors if the ref is null.

</blockquote></details>

</blockquote></details>

<details>
<summary>🧹 Nitpick comments (1)</summary><blockquote>

<details>
<summary>apps/registry/components/assistant-ui/mermaid-diagram.tsx (1)</summary><blockquote>

`42-44`: **Remove unused parameters to fix ESLint warnings.**

The destructured parameters `_node`, `_components`, and `_language` are unused and causing ESLint warnings.


Apply this diff to remove the unused parameters:

```diff
export const MermaidDiagram: FC<MermaidDiagramProps> = ({
  code,
  className,
-  node: _node,
-  components: _components,
-  language: _language,
+  ...props
}) => {
```

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 GitHub Check: ESLint & Prettier</summary>

[failure] 44-44: 
'_language' is defined but never used  

---

[failure] 43-43: 
'_components' is defined but never used

---

[failure] 42-42: 
'_node' is defined but never used      

</details>

</details>

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

**Configuration used: CodeRabbit UI**
**Review profile: CHILL**
**Plan: Pro**


<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 832b1c821efebf05800afc8d12ee6eb49489e193 and 017b29ebd546fce4cd2d28e61bc6dff7241462d8.

</details>

<details>
<summary>⛔ Files ignored due to path filters (2)</summary>

* `.changeset/mighty-actors-brake.md` is excluded by `!.changeset/**`
* `pnpm-lock.yaml` is excluded by `!**/pnpm-lock.yaml`

</details>

<details>
<summary>📒 Files selected for processing (6)</summary>

* `apps/docs/content/docs/ui/Mermaid.mdx` (1 hunks)
* `apps/docs/content/docs/ui/meta.json` (1 hunks)
* `apps/registry/components/assistant-ui/mermaid-diagram.tsx` (1 hunks)
* `apps/registry/package.json` (3 hunks)
* `apps/registry/src/registry.ts` (1 hunks)
* `packages/styles/src/styles/tailwindcss/markdown.css` (1 hunks)

</details>

<details>
<summary>🚧 Files skipped from review as they are similar to previous changes (4)</summary>

* apps/docs/content/docs/ui/meta.json
* packages/styles/src/styles/tailwindcss/markdown.css
* apps/registry/package.json
* apps/registry/src/registry.ts

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>🪛 LanguageTool</summary>

<details>
<summary>apps/docs/content/docs/ui/Mermaid.mdx</summary>

[uncategorized] ~68-~68: Possible missing comma found.
Context: ...Types  Mermaid supports various diagram types including:  - Flowcharts and decision t...

(AI_HYDRA_LEO_MISSING_COMMA)

</details>

</details>
<details>
<summary>🪛 GitHub Check: ESLint & Prettier</summary>

<details>
<summary>apps/registry/components/assistant-ui/mermaid-diagram.tsx</summary>

[failure] 44-44: 
'_language' is defined but never used  

---

[failure] 43-43: 
'_components' is defined but never used

---

[failure] 42-42: 
'_node' is defined but never used      

</details>

</details>

</details>

<details>
<summary>⏰ Context from checks skipped due to timeout of 90000ms (1)</summary>

* GitHub Check: Analyze (javascript-typescript)

</details>

<details>
<summary>🔇 Additional comments (2)</summary><blockquote>

<details>
<summary>apps/docs/content/docs/ui/Mermaid.mdx (1)</summary>

`1-79`: **Excellent documentation structure and content.**

The documentation is comprehensive, well-organized, and provides clear step-by-step instructions for implementing Mermaid diagram support. The examples are practical and the performance considerations are well explained.

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 LanguageTool</summary>

[uncategorized] ~68-~68: Possible missing comma found.
Context: ...Types  Mermaid supports various diagram types including:  - Flowcharts and decision t...

(AI_HYDRA_LEO_MISSING_COMMA)

</details>

</details>

</details>
<details>
<summary>apps/registry/components/assistant-ui/mermaid-diagram.tsx (1)</summary>

`39-75`: **Well-structured component with clear purpose.**

The component is well-documented and implements the core functionality effectively. The streaming optimization approach and async rendering logic are sound architectural decisions.

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 GitHub Check: ESLint & Prettier</summary>

[failure] 44-44: 
'_language' is defined but never used  

---

[failure] 43-43: 
'_components' is defined but never used

---

[failure] 42-42: 
'_node' is defined but never used      

</details>

</details>

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-05-27T02:42:06Z
user: login: coderabbitai[bot]
body: **Actionable comments posted: 1**

<details>
<summary>♻️ Duplicate comments (4)</summary><blockquote>

<details>
<summary>apps/registry/components/assistant-ui/mermaid-diagram.tsx (4)</summary><blockquote>

`17-17`: **Move mermaid initialization inside the component to prevent SSR issues.**

The mermaid initialization should be moved inside a `useEffect` to prevent initialization during server-side rendering, as noted in a previous review.



```diff
-// Configure mermaid options here
-mermaid.initialize({ theme: "default" });
```

And add inside the component:

```diff
+  useEffect(() => {
+    mermaid.initialize({ theme: "default" });
+  }, []);
```

---

`49-51`: **Improve completion detection logic to handle edge cases.**

The current completion detection logic has several potential issues as noted in previous reviews. The approach of splitting by code content and checking for "```" can fail in various scenarios.



Consider using a more robust regex-based approach:

```diff
-  const isComplete = useContentPart((part) => {
-    if (part.type !== "text") return false;
-    return part.text.split(code)[1]?.includes("```");
-  });
+  const isComplete = useContentPart((part) => {
+    if (part.type !== "text") return false;
+    // Look for the complete mermaid code block pattern
+    const pattern = new RegExp(`\`\`\`mermaid\\s*\\n${code.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*\\n\`\`\``, 'g');
+    return pattern.test(part.text);
+  });
```

---

`62-62`: **Add null safety check for ref.current.**

The code uses a non-null assertion without checking if `ref.current` exists, which could cause runtime errors as noted in previous reviews.



```diff
-        ref.current!.replaceChildren(element);
+        if (ref.current) {
+          ref.current.replaceChildren(element);
+        }
```

---

`65-65`: **Consider displaying error state to users instead of just console logging.**

As noted in previous reviews, users should be informed when diagram rendering fails rather than just logging to console.



Consider showing an error message in the UI:

```diff
+  const [error, setError] = useState<string | null>(null);
+
   useEffect(() => {
     if (!isComplete) return;
+    setError(null);
 
     (async () => {
       try {
         const element = document.createElement("div");
         element.textContent = code;
         element.classList.add("mermaid");
-        ref.current!.replaceChildren(element);
+        if (ref.current) {
+          ref.current.replaceChildren(element);
+        }
         await mermaid.run({ nodes: [element] });
       } catch (e) {
         console.warn("Failed to render Mermaid diagram:", e);
+        setError("Failed to render diagram");
       }
     })();
   }, [isComplete, code]);
```

And update the JSX:

```diff
   return (
     <pre ref={ref} className={cn("aui-mermaid-diagram", className)}>
-      Drawing diagram...
+      {error ? `Error: ${error}` : "Drawing diagram..."}
     </pre>
   );
```

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

**Configuration used: CodeRabbit UI**
**Review profile: CHILL**
**Plan: Pro**


<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 017b29ebd546fce4cd2d28e61bc6dff7241462d8 and 1655abcda85cea09dc908a88b72bfd2afff14222.

</details>

<details>
<summary>📒 Files selected for processing (1)</summary>

* `apps/registry/components/assistant-ui/mermaid-diagram.tsx` (1 hunks)

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>🪛 GitHub Check: ESLint & Prettier</summary>

<details>
<summary>apps/registry/components/assistant-ui/mermaid-diagram.tsx</summary>

[failure] 44-44: 
'_language' is defined but never used  

---

[failure] 43-43: 
'_components' is defined but never used

---

[failure] 42-42: 
'_node' is defined but never used      

</details>

</details>

</details>

<details>
<summary>⏰ Context from checks skipped due to timeout of 90000ms (1)</summary>

* GitHub Check: Analyze (javascript-typescript)

</details>

<details>
<summary>🔇 Additional comments (2)</summary><blockquote>

<details>
<summary>apps/registry/components/assistant-ui/mermaid-diagram.tsx (2)</summary>

`60-60`: **Good security practice using textContent instead of innerHTML.**

Using `textContent` instead of `innerHTML` is a good security practice as it prevents potential XSS attacks, even though Mermaid 10.x+ has improved input sanitization.

---

`70-77`: **LGTM: Good JSX structure and component naming.**

The JSX return structure is clean, properly uses the `cn` utility for className merging, provides appropriate loading feedback, and follows React best practices with the displayName.

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-05-27T03:11:44Z
user: login: AVGVSTVS96
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-05-27T03:49:57Z
user: login: coderabbitai[bot]
body: **Actionable comments posted: 0**

<details>
<summary>♻️ Duplicate comments (2)</summary><blockquote>

<details>
<summary>apps/docs/content/docs/ui/Mermaid.mdx (1)</summary><blockquote>

`71-71`: **Address whitespace formatting issue.**

There appears to be extra whitespace after "Sequence diagrams" that was flagged in a previous review.

</blockquote></details>
<details>
<summary>apps/registry/components/assistant-ui/mermaid-diagram.tsx (1)</summary><blockquote>

`42-44`: **Fix ESLint warnings for unused parameters.**

The static analysis correctly identifies unused parameters. These are required by the `SyntaxHighlighterProps` interface but not used in this implementation.

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 GitHub Check: ESLint & Prettier</summary>

[failure] 44-44: 
'_language' is defined but never used  

---

[failure] 43-43: 
'_components' is defined but never used

---

[failure] 42-42: 
'_node' is defined but never used      

</details>

</details>

</blockquote></details>

</blockquote></details>

<details>
<summary>🧹 Nitpick comments (1)</summary><blockquote>

<details>
<summary>apps/docs/content/docs/ui/Mermaid.mdx (1)</summary><blockquote>

`68-68`: **Consider adding comma for better readability.**

The sentence "Mermaid supports various diagram types including:" could benefit from a comma after "types" for improved readability, though it's grammatically optional.


```diff
-Mermaid supports various diagram types including:
+Mermaid supports various diagram types, including:
```

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 LanguageTool</summary>

[uncategorized] ~68-~68: Possible missing comma found.
Context: ...Types  Mermaid supports various diagram types including:  - Flowcharts and decision t...

(AI_HYDRA_LEO_MISSING_COMMA)

</details>

</details>

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

**Configuration used: CodeRabbit UI**
**Review profile: CHILL**
**Plan: Pro**


<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 3b781fd06e29db54f68010a063eed2a3f9be6b46 and 89adfbe0c5a372dab7cf77cd27cb6359cb463acd.

</details>

<details>
<summary>⛔ Files ignored due to path filters (2)</summary>

* `.changeset/mighty-actors-brake.md` is excluded by `!.changeset/**`
* `pnpm-lock.yaml` is excluded by `!**/pnpm-lock.yaml`

</details>

<details>
<summary>📒 Files selected for processing (6)</summary>

* `apps/docs/content/docs/ui/Mermaid.mdx` (1 hunks)
* `apps/docs/content/docs/ui/meta.json` (1 hunks)
* `apps/registry/components/assistant-ui/mermaid-diagram.tsx` (1 hunks)
* `apps/registry/package.json` (3 hunks)
* `apps/registry/src/registry.ts` (1 hunks)
* `packages/styles/src/styles/tailwindcss/markdown.css` (1 hunks)

</details>

<details>
<summary>🚧 Files skipped from review as they are similar to previous changes (4)</summary>

* apps/registry/package.json
* apps/docs/content/docs/ui/meta.json
* apps/registry/src/registry.ts
* packages/styles/src/styles/tailwindcss/markdown.css

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>🪛 LanguageTool</summary>

<details>
<summary>apps/docs/content/docs/ui/Mermaid.mdx</summary>

[uncategorized] ~68-~68: Possible missing comma found.
Context: ...Types  Mermaid supports various diagram types including:  - Flowcharts and decision t...

(AI_HYDRA_LEO_MISSING_COMMA)

</details>

</details>
<details>
<summary>🪛 GitHub Check: ESLint & Prettier</summary>

<details>
<summary>apps/registry/components/assistant-ui/mermaid-diagram.tsx</summary>

[failure] 44-44: 
'_language' is defined but never used  

---

[failure] 43-43: 
'_components' is defined but never used

---

[failure] 42-42: 
'_node' is defined but never used      

</details>

</details>

</details>

<details>
<summary>⏰ Context from checks skipped due to timeout of 90000ms (1)</summary>

* GitHub Check: Analyze (javascript-typescript)

</details>

<details>
<summary>🔇 Additional comments (5)</summary><blockquote>

<details>
<summary>apps/docs/content/docs/ui/Mermaid.mdx (1)</summary>

`1-79`: **Excellent documentation structure and content.**

The documentation is comprehensive and well-organized, providing clear step-by-step instructions for installation, integration, and configuration. The inclusion of streaming performance optimizations and supported diagram types makes this a valuable resource for users.

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 LanguageTool</summary>

[uncategorized] ~68-~68: Possible missing comma found.
Context: ...Types  Mermaid supports various diagram types including:  - Flowcharts and decision t...

(AI_HYDRA_LEO_MISSING_COMMA)

</details>

</details>

</details>
<details>
<summary>apps/registry/components/assistant-ui/mermaid-diagram.tsx (4)</summary>

`49-62`: **Improved completion detection logic is robust.**

The updated completion detection using regex pattern matching (`/^```|^\n```/`) is much more reliable than the previous string splitting approach. This properly handles edge cases and provides accurate detection of complete code blocks.

---

`67-80`: **Excellent async rendering implementation with proper error handling.**

The implementation correctly:
- Uses async/await for mermaid rendering
- Includes ref safety check before DOM manipulation
- Provides meaningful error logging
- Handles the streaming scenario efficiently

The use of `textContent` instead of `innerHTML` is also secure as Mermaid v10.x+ handles sanitization internally.

---

`17-17`: **Mermaid initialization placement is appropriate.**

The initialization at module level is correct for a client-only component as confirmed by the author's previous response. This ensures mermaid is configured before any diagrams are rendered.

---

`1-90`: **High-quality component implementation with excellent streaming optimization.**

This component demonstrates solid engineering practices:
- Smart completion detection for streaming scenarios
- Proper error handling and ref safety
- Clear documentation and examples
- Secure rendering approach using Mermaid's built-in sanitization
- Appropriate separation of concerns

The implementation successfully addresses the complex challenge of rendering Mermaid diagrams in a streaming context while maintaining performance and security.

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 GitHub Check: ESLint & Prettier</summary>

[failure] 44-44: 
'_language' is defined but never used  

---

[failure] 43-43: 
'_components' is defined but never used

---

[failure] 42-42: 
'_node' is defined but never used      

</details>

</details>

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-05-27T15:57:08Z

Review comments:
diff_hunk: @@ -0,0 +1,83 @@
+"use client";
+
+import { useContentPart } from "@assistant-ui/react";
+import type { SyntaxHighlighterProps } from "@assistant-ui/react-markdown";
+import mermaid from "mermaid";
+import { FC, useEffect, useRef } from "react";
+import { cn } from "@/lib/utils";
+
+/**
+ * Props for the MermaidDiagram component
+ */
+export type MermaidDiagramProps = SyntaxHighlighterProps & {
+  className?: string;
+};
+
+// Configure mermaid options here
+mermaid.initialize({ theme: "default" });
path: apps/registry/components/assistant-ui/mermaid-diagram.tsx
user: login: greptile-apps[bot]
body: logic: mermaid.initialize() should be inside the component to prevent initialization during SSR

```suggestion
// Configure mermaid options in useEffect
useEffect(() => {
  mermaid.initialize({ theme: "default" });
}, []);
```
created_at: 2025-05-24T04:28:22Z
author_association: CONTRIBUTOR
diff_hunk: @@ -0,0 +1,83 @@
+"use client";
+
+import { useContentPart } from "@assistant-ui/react";
+import type { SyntaxHighlighterProps } from "@assistant-ui/react-markdown";
+import mermaid from "mermaid";
+import { FC, useEffect, useRef } from "react";
+import { cn } from "@/lib/utils";
+
+/**
+ * Props for the MermaidDiagram component
+ */
+export type MermaidDiagramProps = SyntaxHighlighterProps & {
+  className?: string;
+};
+
+// Configure mermaid options here
+mermaid.initialize({ theme: "default" });
+
+/**
+ * MermaidDiagram component for rendering Mermaid diagrams
+ * Use it by passing to `componentsByLanguage` for mermaid in `markdown-text.tsx`
+ *
+ * @example
+ * const MarkdownTextImpl = () => {
+ *   return (
+ *     <MarkdownTextPrimitive
+ *       remarkPlugins={[remarkGfm]}
+ *       className="aui-md"
+ *       components={defaultComponents}
+ *       componentsByLanguage={{
+ *         mermaid: {
+ *           SyntaxHighlighter: MermaidDiagram
+ *         },
+ *       }}
+ *     />
+ *   );
+ * };
+ */
+export const MermaidDiagram: FC<MermaidDiagramProps> = ({
+  code,
+  className,
+  node: _node,
+  components: _components,
+  language: _language,
+}) => {
+  const ref = useRef<HTMLPreElement>(null);
+
+  // Detect when this specific code block is complete (not the whole message)
+  const isComplete = useContentPart((part) => {
+    if (part.type !== "text") return false;
+    return part.text.split(code)[1]?.includes("```");
+  });
+
+  useEffect(() => {
+    if (!isComplete) return;
+
+    (async () => {
+      try {
+        const element = document.createElement("div");
+        element.innerHTML = code;
+        element.classList.add("mermaid");
+        ref.current!.replaceChildren(element);
path: apps/registry/components/assistant-ui/mermaid-diagram.tsx
user: login: greptile-apps[bot]
body: logic: ref.current could be null here despite the non-null assertion

```suggestion
        if (ref.current) ref.current.replaceChildren(element);
```
created_at: 2025-05-24T04:28:22Z
author_association: CONTRIBUTOR
diff_hunk: @@ -0,0 +1,83 @@
+"use client";
+
+import { useContentPart } from "@assistant-ui/react";
+import type { SyntaxHighlighterProps } from "@assistant-ui/react-markdown";
+import mermaid from "mermaid";
+import { FC, useEffect, useRef } from "react";
+import { cn } from "@/lib/utils";
+
+/**
+ * Props for the MermaidDiagram component
+ */
+export type MermaidDiagramProps = SyntaxHighlighterProps & {
+  className?: string;
+};
+
+// Configure mermaid options here
+mermaid.initialize({ theme: "default" });
+
+/**
+ * MermaidDiagram component for rendering Mermaid diagrams
+ * Use it by passing to `componentsByLanguage` for mermaid in `markdown-text.tsx`
+ *
+ * @example
+ * const MarkdownTextImpl = () => {
+ *   return (
+ *     <MarkdownTextPrimitive
+ *       remarkPlugins={[remarkGfm]}
+ *       className="aui-md"
+ *       components={defaultComponents}
+ *       componentsByLanguage={{
+ *         mermaid: {
+ *           SyntaxHighlighter: MermaidDiagram
+ *         },
+ *       }}
+ *     />
+ *   );
+ * };
+ */
+export const MermaidDiagram: FC<MermaidDiagramProps> = ({
+  code,
+  className,
+  node: _node,
+  components: _components,
+  language: _language,
+}) => {
+  const ref = useRef<HTMLPreElement>(null);
+
+  // Detect when this specific code block is complete (not the whole message)
+  const isComplete = useContentPart((part) => {
+    if (part.type !== "text") return false;
+    return part.text.split(code)[1]?.includes("```");
+  });
+
+  useEffect(() => {
+    if (!isComplete) return;
+
+    (async () => {
+      try {
+        const element = document.createElement("div");
+        element.innerHTML = code;
+        element.classList.add("mermaid");
+        ref.current!.replaceChildren(element);
+        await mermaid.run({ nodes: [element] });
+      } catch (e) {
+        console.warn("Failed to render Mermaid diagram:", e);
path: apps/registry/components/assistant-ui/mermaid-diagram.tsx
user: login: greptile-apps[bot]
body: style: should display error state to user instead of just logging to console
created_at: 2025-05-24T04:28:23Z
author_association: CONTRIBUTOR
diff_hunk: @@ -0,0 +1,79 @@
+---
+title: "Mermaid Diagrams"
+---
+
+import { Callout } from "fumadocs-ui/components/callout";
+import { Step, Steps } from "fumadocs-ui/components/steps";
+
+Render Mermaid diagrams in chat messages with the `mermaid-diagram` component.
+
+<Steps>
+  <Step>
+
+### Add `mermaid-diagram` component
+
+```bash
+npx shadcn@latest add "https://r.assistant-ui.com/mermaid-diagram"
+```
+
+This will install the required dependencies and add the component to your project.
+
+  </Step>
+  <Step>
+
+### Add it to `componentsByLanguage` in `markdown-text.tsx`
+
+```tsx title="/components/assistant-ui/markdown-text.tsx"
+import { MermaidDiagram } from "@/components/assistant-ui/mermaid-diagram"; // [!code ++]
+
+const MarkdownTextImpl = () => {
+  return (
+    <MarkdownTextPrimitive
+      remarkPlugins={[remarkGfm]}
+      className="aui-md"
+      components={defaultComponents}
+      componentsByLanguage={{               // [!code ++]
+        mermaid: {                          // [!code ++]
+          SyntaxHighlighter: MermaidDiagram // [!code ++]
+        },                                  // [!code ++]
+      }}                                    // [!code ++]
+    />
+  );
+};
+
+export const MarkdownText = memo(MarkdownTextImpl);
+```
+
+  </Step>
+</Steps>
+
+## Configuration
+
+Configure mermaid options in `mermaid-diagram.tsx`:
+
+```tsx title="/components/assistant-ui/mermaid-diagram.tsx"
+mermaid.initialize({ theme: "default" });
+```
+
+## Streaming Performance
+
+The `MermaidDiagram` component is optimized for streaming scenarios:
+
+- **Smart completion detection**: Only renders when the specific code block is complete
+- **Zero failed renders**: Avoids parsing incomplete diagram code during streaming  
+
+
+## Supported Diagram Types
+
+Mermaid supports various diagram types including:
+
+- Flowcharts and decision trees
+- Sequence diagrams  
path: apps/docs/content/docs/ui/Mermaid.mdx
user: login: greptile-apps[bot]
body: syntax: Extra whitespace after 'Sequence diagrams'
created_at: 2025-05-24T04:28:30Z
author_association: CONTRIBUTOR
diff_hunk: @@ -42,5 +42,8 @@
   "scripts": {
     "build": "tsx ./scripts/build-registry.ts",
     "lint": "eslint ."
+  },
+  "dependencies": {
+    "mermaid": "^11.6.0"
   }
path: apps/registry/package.json
user: login: coderabbitai[bot]
body: _💡 Verification agent_

<details>
<summary>🧩 Analysis chain</summary>

**Verify TypeScript types availability**: Check if `@types/mermaid` exists or if mermaid provides built-in types to avoid compilation errors.

---

🏁 Script executed:

```shell
#!/bin/bash
# Check for TypeScript type definitions for 'mermaid'
npm view @types/mermaid version
```

Length of output: 39

---



</details>

**Add TypeScript types for Mermaid**  
We verified that `@types/mermaid@9.2.0` is published on npm. Please install it as a dev-dependency to ensure proper type checking.

• apps/registry/package.json  
```diff
 "dependencies": {
   "mermaid": "^11.6.0"
 },
 "devDependencies": {
+  "@types/mermaid": "^9.2.0"
 }
```  


<!-- suggestion_start -->

<details>
<summary>📝 Committable suggestion</summary>

> ‼️ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

```suggestion
  },
  "dependencies": {
    "mermaid": "^11.6.0"
  },
  "devDependencies": {
    "@types/mermaid": "^9.2.0"
  }
```

</details>

<!-- suggestion_end -->

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
In apps/registry/package.json around lines 45 to 48, the dependency "mermaid" is
added but the TypeScript types for Mermaid are missing. To fix this, add
"@types/mermaid" as a devDependency with version "9.2.0" to ensure proper type
checking and avoid compilation errors.
```

</details>

<!-- This is an auto-generated comment by CodeRabbit -->
created_at: 2025-05-24T04:31:38Z
author_association: CONTRIBUTOR
diff_hunk: @@ -0,0 +1,83 @@
+"use client";
+
+import { useContentPart } from "@assistant-ui/react";
+import type { SyntaxHighlighterProps } from "@assistant-ui/react-markdown";
+import mermaid from "mermaid";
+import { FC, useEffect, useRef } from "react";
+import { cn } from "@/lib/utils";
+
+/**
+ * Props for the MermaidDiagram component
+ */
+export type MermaidDiagramProps = SyntaxHighlighterProps & {
+  className?: string;
+};
+
+// Configure mermaid options here
+mermaid.initialize({ theme: "default" });
+
+/**
+ * MermaidDiagram component for rendering Mermaid diagrams
+ * Use it by passing to `componentsByLanguage` for mermaid in `markdown-text.tsx`
+ *
+ * @example
+ * const MarkdownTextImpl = () => {
+ *   return (
+ *     <MarkdownTextPrimitive
+ *       remarkPlugins={[remarkGfm]}
+ *       className="aui-md"
+ *       components={defaultComponents}
+ *       componentsByLanguage={{
+ *         mermaid: {
+ *           SyntaxHighlighter: MermaidDiagram
+ *         },
+ *       }}
+ *     />
+ *   );
+ * };
+ */
+export const MermaidDiagram: FC<MermaidDiagramProps> = ({
+  code,
+  className,
+  node: _node,
+  components: _components,
+  language: _language,
+}) => {
+  const ref = useRef<HTMLPreElement>(null);
+
+  // Detect when this specific code block is complete (not the whole message)
+  const isComplete = useContentPart((part) => {
+    if (part.type !== "text") return false;
+    return part.text.split(code)[1]?.includes("```");
+  });
+
+  useEffect(() => {
+    if (!isComplete) return;
+
+    (async () => {
+      try {
+        const element = document.createElement("div");
+        element.innerHTML = code;
+        element.classList.add("mermaid");
+        ref.current!.replaceChildren(element);
+        await mermaid.run({ nodes: [element] });
+      } catch (e) {
+        console.warn("Failed to render Mermaid diagram:", e);
+      }
+    })();
+  }, [isComplete, code]);
+
+  return (
+    <pre
+      ref={ref}
+      className={cn(
+        "aui-mermaid-diagram",
+        className,
+      )}
+    >
+      Drawing diagram...
+    </pre>
+  );
+};
+
+MermaidDiagram.displayName = "MermaidDiagram";
path: apps/registry/components/assistant-ui/mermaid-diagram.tsx
user: login: coderabbitai[bot]
body: _⚠️ Potential issue_

**Fix prettier formatting issues.**

The JSX structure and logic are correct, but there are formatting issues that need to be addressed.




Run the following command to fix the prettier formatting:

```shell
prettier --write apps/registry/components/assistant-ui/mermaid-diagram.tsx
```

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
In apps/registry/components/assistant-ui/mermaid-diagram.tsx around lines 70 to
83, the JSX code is functionally correct but has formatting issues. Run the
command "prettier --write
apps/registry/components/assistant-ui/mermaid-diagram.tsx" to automatically fix
the formatting according to the project's prettier configuration.
```

</details>

<!-- This is an auto-generated comment by CodeRabbit -->

✅ Addressed in commits 7a723c1 to 51d15a8
created_at: 2025-05-24T04:31:38Z
author_association: CONTRIBUTOR
diff_hunk: @@ -0,0 +1,83 @@
+"use client";
+
+import { useContentPart } from "@assistant-ui/react";
+import type { SyntaxHighlighterProps } from "@assistant-ui/react-markdown";
+import mermaid from "mermaid";
+import { FC, useEffect, useRef } from "react";
+import { cn } from "@/lib/utils";
+
+/**
+ * Props for the MermaidDiagram component
+ */
+export type MermaidDiagramProps = SyntaxHighlighterProps & {
+  className?: string;
+};
+
+// Configure mermaid options here
+mermaid.initialize({ theme: "default" });
+
+/**
+ * MermaidDiagram component for rendering Mermaid diagrams
+ * Use it by passing to `componentsByLanguage` for mermaid in `markdown-text.tsx`
+ *
+ * @example
+ * const MarkdownTextImpl = () => {
+ *   return (
+ *     <MarkdownTextPrimitive
+ *       remarkPlugins={[remarkGfm]}
+ *       className="aui-md"
+ *       components={defaultComponents}
+ *       componentsByLanguage={{
+ *         mermaid: {
+ *           SyntaxHighlighter: MermaidDiagram
+ *         },
+ *       }}
+ *     />
+ *   );
+ * };
+ */
+export const MermaidDiagram: FC<MermaidDiagramProps> = ({
+  code,
+  className,
+  node: _node,
+  components: _components,
+  language: _language,
+}) => {
+  const ref = useRef<HTMLPreElement>(null);
+
+  // Detect when this specific code block is complete (not the whole message)
+  const isComplete = useContentPart((part) => {
+    if (part.type !== "text") return false;
+    return part.text.split(code)[1]?.includes("```");
path: apps/registry/components/assistant-ui/mermaid-diagram.tsx
user: login: coderabbitai[bot]
body: _🛠️ Refactor suggestion_

**Consider a more robust completion detection approach.**

The current logic `part.text.split(code)[1]?.includes("```")` may have edge cases:

1. If the mermaid code itself contains the same string as `code`, the split logic could behave unexpectedly
2. Multiple code blocks in the same message could cause confusion
3. The logic assumes the code block always ends with exactly ``` 

Consider a more robust pattern matching approach or using the existing Assistant UI completion mechanisms if available.

<details>
<summary>🤖 Prompt for AI Agents</summary>

````
In apps/registry/components/assistant-ui/mermaid-diagram.tsx around lines 49 to
51, the current completion detection uses splitting by the code string and
checking for "```", which can fail if the code contains the split string or
multiple code blocks exist. Replace this logic with a more robust pattern
matching approach, such as using regular expressions to detect the closing
triple backticks after the code block, or leverage existing Assistant UI
completion utilities if available, to reliably determine if the code block is
complete.
````

</details>

<!-- This is an auto-generated comment by CodeRabbit -->

✅ Addressed in commit ce3b88e
created_at: 2025-05-24T04:31:38Z
author_association: CONTRIBUTOR
diff_hunk: @@ -0,0 +1,83 @@
+"use client";
+
+import { useContentPart } from "@assistant-ui/react";
+import type { SyntaxHighlighterProps } from "@assistant-ui/react-markdown";
+import mermaid from "mermaid";
+import { FC, useEffect, useRef } from "react";
+import { cn } from "@/lib/utils";
+
+/**
+ * Props for the MermaidDiagram component
+ */
+export type MermaidDiagramProps = SyntaxHighlighterProps & {
+  className?: string;
+};
+
+// Configure mermaid options here
+mermaid.initialize({ theme: "default" });
+
+/**
+ * MermaidDiagram component for rendering Mermaid diagrams
+ * Use it by passing to `componentsByLanguage` for mermaid in `markdown-text.tsx`
+ *
+ * @example
+ * const MarkdownTextImpl = () => {
+ *   return (
+ *     <MarkdownTextPrimitive
+ *       remarkPlugins={[remarkGfm]}
+ *       className="aui-md"
+ *       components={defaultComponents}
+ *       componentsByLanguage={{
+ *         mermaid: {
+ *           SyntaxHighlighter: MermaidDiagram
+ *         },
+ *       }}
+ *     />
+ *   );
+ * };
+ */
+export const MermaidDiagram: FC<MermaidDiagramProps> = ({
+  code,
+  className,
+  node: _node,
+  components: _components,
+  language: _language,
+}) => {
+  const ref = useRef<HTMLPreElement>(null);
+
+  // Detect when this specific code block is complete (not the whole message)
+  const isComplete = useContentPart((part) => {
+    if (part.type !== "text") return false;
+    return part.text.split(code)[1]?.includes("```");
+  });
+
+  useEffect(() => {
+    if (!isComplete) return;
+
+    (async () => {
+      try {
+        const element = document.createElement("div");
+        element.innerHTML = code;
+        element.classList.add("mermaid");
+        ref.current!.replaceChildren(element);
+        await mermaid.run({ nodes: [element] });
+      } catch (e) {
+        console.warn("Failed to render Mermaid diagram:", e);
+      }
+    })();
+  }, [isComplete, code]);
path: apps/registry/components/assistant-ui/mermaid-diagram.tsx
user: login: coderabbitai[bot]
body: _💡 Verification agent_

<details>
<summary>🧩 Analysis chain</summary>

**Address potential security and safety concerns.**

The implementation has good error handling and async patterns, but consider these improvements:

1. **Security**: Using `innerHTML` with user-provided code could be a security risk. Ensure mermaid properly sanitizes input, or consider additional validation.

2. **Ref safety**: The non-null assertion `ref.current!` assumes the ref is always available. Add a safety check:

```diff
- ref.current!.replaceChildren(element);
+ if (ref.current) {
+   ref.current.replaceChildren(element);
+ }
```




Verify that mermaid library properly sanitizes input to prevent XSS attacks:

---

🌐 Web query:

```web
Does the Mermaid library sanitize input to prevent XSS attacks in version 10.x?
```

💡 Result:

In earlier versions of the Mermaid library, particularly those prior to version 8.13.8, there were known vulnerabilities related to Cross-Site Scripting (XSS) attacks due to improper input sanitization. For instance, versions before 8.11.0 were susceptible when the antiscript feature was used, allowing attackers to inject malicious scripts into generated diagrams. ([security.snyk.io](https://security.snyk.io/vuln/SNYK-JS-MERMAID-1314738?utm_source=openai))

However, these vulnerabilities have been addressed in subsequent releases. By version 10.x, Mermaid has implemented improved input sanitization measures to prevent XSS attacks. Notably, version 10.9.3 and later have patched a vulnerability involving a bundled version of DOMPurify, which could have led to prototype pollution and XSS risks. ([vulert.com](https://vulert.com/vuln-db/npm-mermaid-173332?utm_source=openai))

Therefore, if you're using Mermaid version 10.x, your application benefits from enhanced security features that mitigate the risk of XSS attacks.

Citations:

- 1: https://security.snyk.io/vuln/SNYK-JS-MERMAID-1314738?utm_source=openai
- 2: https://vulert.com/vuln-db/npm-mermaid-173332?utm_source=openai

---



</details>

**Ensure ref safety and leverage Mermaid’s built-in sanitization**

Mermaid 10.x+ includes improved input sanitization to mitigate XSS risks, so using `innerHTML` here is acceptable as long as your dependency is v10.x or later. Also, guard against null refs to avoid runtime errors.

- File: `apps/registry/components/assistant-ui/mermaid-diagram.tsx`
  - Wrap `ref.current` access in a null check.
  - Confirm your `mermaid` dependency is at v10.x or later.

Suggested diff:
```diff
- ref.current!.replaceChildren(element);
+ if (ref.current) {
+   ref.current.replaceChildren(element);
+ }
```


<!-- suggestion_start -->

<details>
<summary>📝 Committable suggestion</summary>

> ‼️ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

```suggestion
  useEffect(() => {
    if (!isComplete) return;

    (async () => {
      try {
        const element = document.createElement("div");
        element.innerHTML = code;
        element.classList.add("mermaid");
        if (ref.current) {
          ref.current.replaceChildren(element);
        }
        await mermaid.run({ nodes: [element] });
      } catch (e) {
        console.warn("Failed to render Mermaid diagram:", e);
      }
    })();
  }, [isComplete, code]);
```

</details>

<!-- suggestion_end -->

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
In apps/registry/components/assistant-ui/mermaid-diagram.tsx around lines 54 to
68, the code uses ref.current! without checking if ref.current is null, which
can cause runtime errors. Add a null check before accessing ref.current to
ensure it exists before calling replaceChildren. Also, verify that the mermaid
library version used is 10.x or later to rely on its built-in input
sanitization, making the use of innerHTML safe in this context.
```

</details>

<!-- This is an auto-generated comment by CodeRabbit -->

✅ Addressed in commit 121b239
created_at: 2025-05-24T04:31:38Z
author_association: CONTRIBUTOR
diff_hunk: @@ -0,0 +1,77 @@
+"use client";
+
+import { useContentPart } from "@assistant-ui/react";
+import type { SyntaxHighlighterProps } from "@assistant-ui/react-markdown";
+import mermaid from "mermaid";
+import { FC, useEffect, useRef } from "react";
+import { cn } from "@/lib/utils";
+
+/**
+ * Props for the MermaidDiagram component
+ */
+export type MermaidDiagramProps = SyntaxHighlighterProps & {
+  className?: string;
+};
+
+// Configure mermaid options here
+mermaid.initialize({ theme: "default" });
+
+/**
+ * MermaidDiagram component for rendering Mermaid diagrams
+ * Use it by passing to `componentsByLanguage` for mermaid in `markdown-text.tsx`
+ *
+ * @example
+ * const MarkdownTextImpl = () => {
+ *   return (
+ *     <MarkdownTextPrimitive
+ *       remarkPlugins={[remarkGfm]}
+ *       className="aui-md"
+ *       components={defaultComponents}
+ *       componentsByLanguage={{
+ *         mermaid: {
+ *           SyntaxHighlighter: MermaidDiagram
+ *         },
+ *       }}
+ *     />
+ *   );
+ * };
+ */
+export const MermaidDiagram: FC<MermaidDiagramProps> = ({
+  code,
+  className,
+  node: _node,
+  components: _components,
+  language: _language,
path: apps/registry/components/assistant-ui/mermaid-diagram.tsx
user: login: coderabbitai[bot]
body: _⚠️ Potential issue_

**Remove ESLint warnings for unused parameters.**

The static analysis correctly identifies that these parameters are defined but never used. Since they're part of the `SyntaxHighlighterProps` interface, they should be properly handled.



```diff
-  node: _node,
-  components: _components,
-  language: _language,
+  node: _,
+  components: _,
+  language: _,
```


> Committable suggestion skipped: line range outside the PR's diff.

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 GitHub Check: ESLint & Prettier</summary>

[failure] 44-44: 
'_language' is defined but never used  

---

[failure] 43-43: 
'_components' is defined but never used

---

[failure] 42-42: 
'_node' is defined but never used      

</details>

</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
In apps/registry/components/assistant-ui/mermaid-diagram.tsx around lines 42 to
44, the parameters node, components, and language are defined but unused,
causing ESLint warnings. To fix this, explicitly mark these parameters as unused
by prefixing their names with an underscore or use them in a no-op way to
satisfy the interface requirements and suppress the warnings.
```

</details>

<!-- This is an auto-generated comment by CodeRabbit -->

✅ Addressed in commits 75a297a to 0b99c9b
created_at: 2025-05-27T03:11:43Z
author_association: CONTRIBUTOR
diff_hunk: @@ -0,0 +1,83 @@
+"use client";
+
+import { useContentPart } from "@assistant-ui/react";
+import type { SyntaxHighlighterProps } from "@assistant-ui/react-markdown";
+import mermaid from "mermaid";
+import { FC, useEffect, useRef } from "react";
+import { cn } from "@/lib/utils";
+
+/**
+ * Props for the MermaidDiagram component
+ */
+export type MermaidDiagramProps = SyntaxHighlighterProps & {
+  className?: string;
+};
+
+// Configure mermaid options here
+mermaid.initialize({ theme: "default" });
path: apps/registry/components/assistant-ui/mermaid-diagram.tsx
user: login: AVGVSTVS96
body: this is client only :)
created_at: 2025-05-27T03:49:57Z
author_association: MEMBER

PR comments:
user: login: jazzberry-ai[bot]
created_at: 2025-05-24T04:27:36Z
body: # Bug Report

Name|Severity|Example test case|Description
XSS Vulnerability in Mermaid Diagram Component|Critical|A user can inject malicious JavaScript code into a Mermaid diagram, which will then be executed when the diagram is rendered using `<img src=x onerror=alert('XSS')>`.|The `mermaid-diagram` component uses `innerHTML` to render the Mermaid diagram, which allows for the execution of arbitrary JavaScript code. The documentation doesn't mention this security risk, which could lead to users unknowingly introducing XSS vulnerabilities into their applications.

<sub>Comments? [Email us](mailto:support@jazzberry.ai).</sub>
author_association: NONE
user: login: changeset-bot[bot]
created_at: 2025-05-24T04:27:36Z
body: ###  🦋  Changeset detected

Latest commit: 89adfbe0c5a372dab7cf77cd27cb6359cb463acd

**The changes in this PR will be included in the next version bump.**

<details><summary>This PR includes changesets to release 1 package</summary>

  | Name                 | Type  |
| -------------------- | ----- |
| @assistant-ui/styles | Patch |

</details>

Not sure what this means? [Click here  to learn what changesets are](https://github.com/changesets/changesets/blob/main/docs/adding-a-changeset.md).

[Click here if you're a maintainer who wants to add another changeset to this PR](https://github.com/assistant-ui/assistant-ui/new/add-mermaid-support?filename=.changeset/thin-dogs-own.md&value=---%0A%22%40assistant-ui%2Fstyles%22%3A%20patch%0A%22%40assistant-ui%2Fdocs%22%3A%20patch%0A%22%40assistant-ui%2Fshadcn-registry%22%3A%20patch%0A---%0A%0Afeat%3A%20Add%20first%20class%20support%20for%20Mermaid%20diagrams%0A)


author_association: NONE
user: login: vercel[bot]
created_at: 2025-05-24T04:27:38Z
body: [vc]: #A8dEDdWRYoYLEoVkKS4tBroaaYXztB/i56FDKheKsGY=:eyJpc01vbm9yZXBvIjp0cnVlLCJ0eXBlIjoiZ2l0aHViIiwicHJvamVjdHMiOlt7Im5hbWUiOiJhc3Npc3RhbnQtdWkiLCJpbnNwZWN0b3JVcmwiOiJodHRwczovL3ZlcmNlbC5jb20vYXNzaXN0YW50LXVpL2Fzc2lzdGFudC11aS85RmZoRVp6QTM4dkNHQkpCOVZYNWU0OXR3b0pyIiwicHJldmlld1VybCI6ImFzc2lzdGFudC11aS1naXQtYWRkLW1lcm1haWQtc3VwcG9ydC1hc3Npc3RhbnQtdWkudmVyY2VsLmFwcCIsIm5leHRDb21taXRTdGF0dXMiOiJERVBMT1lFRCIsImxpdmVGZWVkYmFjayI6eyJyZXNvbHZlZCI6MCwidW5yZXNvbHZlZCI6MCwidG90YWwiOjAsImxpbmsiOiJhc3Npc3RhbnQtdWktZ2l0LWFkZC1tZXJtYWlkLXN1cHBvcnQtYXNzaXN0YW50LXVpLnZlcmNlbC5hcHAifSwicm9vdERpcmVjdG9yeSI6ImFwcHMvZG9jcyJ9XX0=
**The latest updates on your projects**. Learn more about [Vercel for Git ↗︎](https://vercel.link/github-learn-more)

| Name | Status | Preview | Comments | Updated (UTC) |
| :--- | :----- | :------ | :------- | :------ |
| **assistant-ui** | ✅ Ready ([Inspect](https://vercel.com/assistant-ui/assistant-ui/9FfhEZzA38vCGBJB9VX5e49twoJr)) | [Visit Preview](https://assistant-ui-git-add-mermaid-support-assistant-ui.vercel.app) | 💬 [**Add feedback**](https://vercel.live/open-feedback/assistant-ui-git-add-mermaid-support-assistant-ui.vercel.app?via=pr-comment-feedback-link) | May 27, 2025 3:55pm |


author_association: NONE
user: login: promptless[bot]
created_at: 2025-05-24T04:28:52Z
body: 📝 Documentation updates detected!

New suggestion: **[Add first-class support for Mermaid diagrams documentation](https://app.gopromptless.ai/change-history/2e4d3f62-e6da-4501-be40-fcbecd543511)**
author_association: CONTRIBUTOR
user: login: entelligence-ai-pr-reviews[bot]
created_at: 2025-05-24T04:29:03Z
body: ## Review Summary

Skipped posting 1 drafted comments based on your review threshold. Feel free to update them [here](https://www.entelligence.ai/pull-requests).

<details>
<summary>Draft Comments</summary>

<details>
<summary>apps/registry/components/assistant-ui/mermaid-diagram.tsx:62-62</summary>

```
Using non-null assertion (`!`) on `ref.current` is unsafe as it could be `null` during rendering. Using optional chaining (`?.`) would prevent potential runtime errors.
```

Scores:
- Production Impact: 4
- Fix Specificity: 5
- Urgency Impact: 4
- Total Score: 13

Reason for filtering: The comment addresses a legitimate TypeScript safety issue that could cause runtime errors

Analysis: Using non-null assertion (!) when ref.current could be null creates a real risk of runtime errors. The fix is direct and specific, changing ! to ?. to prevent crashes when ref.current is null. This is a TypeScript safety issue that could directly impact production with errors, and the solution is straightforward and immediately applicable.
</details>

</details>


author_association: CONTRIBUTOR
user: login: coderabbitai[bot]
created_at: 2025-05-24T04:31:34Z
body: <!-- This is an auto-generated comment: summarize by coderabbit.ai -->
<!-- walkthrough_start -->

## Walkthrough

A new feature for rendering Mermaid diagrams within chat messages has been introduced. This includes the creation of a `MermaidDiagram` React component, which leverages the Mermaid library to render diagrams from code blocks. The component is registered in the system registry and documented in a newly added documentation page that explains installation, integration, and supported diagram types. The package dependencies are updated to include the Mermaid library, and a new CSS class is added for diagram styling. The documentation navigation is updated to reference the new Mermaid diagrams page. No existing public APIs or entities are modified.

<!-- walkthrough_end -->
<!-- internal state start -->


<!-- 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 -->

<!-- internal state end -->
<!-- finishing_touch_checkbox_start -->

<details open="true">
<summary>✨ Finishing Touches</summary>

- [ ] <!-- {"checkboxId": "7962f53c-55bc-4827-bfbf-6a18da830691"} --> 📝 Generate Docstrings

</details>

<!-- finishing_touch_checkbox_end -->
<!-- tips_start -->

---

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.

<details>
<summary>❤️ Share</summary>

- [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai)
- [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai)
- [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai)
- [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)

</details>

<details>
<summary>🪧 Tips</summary>

### Chat

There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=assistant-ui/assistant-ui&utm_content=2002):

- Review comments: Directly reply to a review comment made by CodeRabbit. Example:
  - `I pushed a fix in commit <commit_id>, please review it.`
  - `Explain this complex logic.`
  - `Open a follow-up GitHub issue for this discussion.`
- Files and specific lines of code (under the "Files changed" tab): Tag `@coderabbitai` in a new review comment at the desired location with your query. Examples:
  - `@coderabbitai explain this code block.`
  -	`@coderabbitai modularize this function.`
- PR comments: Tag `@coderabbitai` in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
  - `@coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.`
  - `@coderabbitai read src/utils.ts and explain its main purpose.`
  - `@coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.`
  - `@coderabbitai help me debug CodeRabbit configuration file.`

### Support

Need help? Create a ticket on our [support page](https://www.coderabbit.ai/contact-us/support) for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

### CodeRabbit Commands (Invoked using PR comments)

- `@coderabbitai pause` to pause the reviews on a PR.
- `@coderabbitai resume` to resume the paused reviews.
- `@coderabbitai review` to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
- `@coderabbitai full review` to do a full review from scratch and review all the files again.
- `@coderabbitai summary` to regenerate the summary of the PR.
- `@coderabbitai generate docstrings` to [generate docstrings](https://docs.coderabbit.ai/finishing-touches/docstrings) for this PR.
- `@coderabbitai generate sequence diagram` to generate a sequence diagram of the changes in this PR.
- `@coderabbitai resolve` resolve all the CodeRabbit review comments.
- `@coderabbitai configuration` to show the current CodeRabbit configuration for the repository.
- `@coderabbitai help` to get help.

### Other keywords and placeholders

- Add `@coderabbitai ignore` anywhere in the PR description to prevent this PR from being reviewed.
- Add `@coderabbitai summary` to generate the high-level summary at a specific location in the PR description.
- Add `@coderabbitai` anywhere in the PR title to generate the title automatically.

### CodeRabbit Configuration File (`.coderabbit.yaml`)

- You can programmatically configure CodeRabbit by adding a `.coderabbit.yaml` file to the root of your repository.
- Please see the [configuration documentation](https://docs.coderabbit.ai/guides/configure-coderabbit) for more information.
- If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: `# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json`

### Documentation and Community

- Visit our [Documentation](https://docs.coderabbit.ai) for detailed information on how to use CodeRabbit.
- Join our [Discord Community](http://discord.gg/coderabbit) to get help, request features, and share feedback.
- Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.

</details>

<!-- tips_end -->
author_association: CONTRIBUTOR
user: login: jazzberry-ai[bot]
created_at: 2025-05-24T04:39:48Z
body: # Bug Report

Name|Severity|Example test case|Description
---|---|---|---
Incomplete Mermaid Diagram Rendering|Medium|A Mermaid diagram that ends at the end of the message may not render correctly. The code contains the splitting sequence of characters.|The `isComplete` check in `apps/registry/components/assistant-ui/mermaid-diagram.tsx` uses `part.text.split(code)[1]?.includes("```")` to determine if the Mermaid code block is complete. This check is flawed as it assumes that the closing "```" will always be present after the code block in the `part.text`. This assumption fails when the Mermaid diagram is the last part of the message or the code contains the same character sequence as the splitting `code` variable.

<sub>Comments? [Email us](mailto:support@jazzberry.ai).</sub>
author_association: NONE
user: login: jazzberry-ai[bot]
created_at: 2025-05-24T04:42:45Z
body: # Bug Report

Name|Severity|Example test case|Description
---|---|---|---
Potential XSS vulnerability in `MermaidDiagram` component|Medium|Inject malicious JavaScript code within a Mermaid diagram definition.|The `MermaidDiagram` component directly renders the `code` prop into the `innerHTML` of a `div` element, creating a potential XSS vulnerability if the `code` prop contains malicious JavaScript code. An attacker could inject malicious JavaScript code through a crafted Mermaid diagram, potentially compromising the user's session or performing unauthorized actions.

<sub>Comments? [Email us](mailto:support@jazzberry.ai).</sub>
author_association: NONE
user: login: jazzberry-ai[bot]
created_at: 2025-05-25T04:29:09Z
body: # Bug Report

Name: Premature Mermaid Diagram Rendering due to `isComplete` Bypass
Severity: Medium
Example test case: Include a "```" sequence *before* the mermaid code block in a chat message. The diagram will attempt to render prematurely.
Description: The `isComplete` check in `mermaid-diagram.tsx` relies on `part.text.split(code)[1]?.includes("```")`, which can be bypassed if the message contains a "```" sequence *before* the closing fence of the mermaid code block. This leads to the diagram attempting to render before the code is fully available. This also will result in zero failed renders.

<sub>Comments? [Email us](mailto:support@jazzberry.ai).</sub>
author_association: NONE
user: login: jazzberry-ai[bot]
created_at: 2025-05-25T20:00:14Z
body: # Bug Report

| Name                    | Severity | Example test case                                                            | Description                                                                                                                                                                                                                                                                      |
| :----------------------- | :------- | :--------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Incomplete Diagram Rendering | Medium  | Split a mermaid diagram across two content parts, with the closing "```" in the second part. | The `isComplete` logic in `MermaidDiagram` only checks for the closing "```" within the same content part as the diagram code. If the closing "```" is in a subsequent content part (e.g., due to streaming), the diagram will never be rendered. |
| Incomplete Diagram Rendering | Low  | Use a mermaid diagram when the `part.type` is not `text` | The `isComplete` logic in `MermaidDiagram` immediately returns `false` if `part.type !== "text"`. This means that mermaid diagrams will only work when the code is part of a `text` content part. If the mermaid diagram is part of some other type of content part, it will not render. |


<sub>Comments? [Email us](mailto:support@jazzberry.ai).</sub>
author_association: NONE
user: login: jazzberry-ai[bot]
created_at: 2025-05-27T02:39:34Z
body: # Bug Report

| Name | Severity | Example test case | Description |
|---|---|---|---|
| XSS vulnerability in Mermaid diagram rendering | Critical | Render a Mermaid diagram containing malicious JavaScript code, such as `<img src=x onerror=alert(1)>`. | The `mermaid-diagram.tsx` component uses `element.innerHTML = code` to render the Mermaid diagram, which allows for arbitrary JavaScript execution. This can be exploited by an attacker to inject malicious code into the chat message. |

<sub>Comments? [Email us](mailto:support@jazzberry.ai).</sub>
author_association: NONE
user: login: jazzberry-ai[bot]
created_at: 2025-05-27T03:07:52Z
body: # Bug Report

Name|Severity|Example test case|Description\n---|---|---|---\nIncorrect Mermaid Completion Detection|Medium|Mermaid code contains triple backticks within the diagram's code.|\`isComplete\` incorrectly identifies a Mermaid diagram as complete when the code contains triple backticks within the diagram itself, leading to premature rendering and potential errors.

<sub>Comments? [Email us](mailto:support@jazzberry.ai).</sub>
author_association: NONE
user: login: jazzberry-ai[bot]
created_at: 2025-05-27T03:11:28Z
body: # Bug Report

| Name | Severity | Example test case | Description |
|---|---|---|---|
| Potential XSS vulnerability in Mermaid diagram rendering | High |  Include a javascript: URL in a Mermaid diagram (e.g., `graph TD A[Click Me] --> B((javascript:alert('XSS!')))`) | The `mermaid.run` function might be vulnerable to XSS if it renders the Mermaid diagram by directly manipulating the DOM in an unsafe way. Although `textContent` is used, it's not sufficient to prevent XSS if Mermaid itself introduces a vulnerability during rendering. |

<sub>Comments? [Email us](mailto:support@jazzberry.ai).</sub>
author_association: NONE
user: login: jazzberry-ai[bot]
created_at: 2025-05-27T03:29:57Z
body: # Bug Report

Name|Severity|Example test case|Description
XSS Vulnerability in Mermaid Diagram Rendering|High|Craft a Mermaid diagram containing malicious JavaScript that executes upon rendering by the Mermaid library.|The Mermaid diagram component uses `element.textContent = code` for initial sanitization. However, the `mermaid.run` function then processes the content and renders an SVG.  If the Mermaid code contains malicious scripts, the Mermaid library may introduce XSS vulnerabilities during rendering the resulting SVG and inserting it into the DOM.

<sub>Comments? [Email us](mailto:support@jazzberry.ai).</sub>
author_association: NONE
user: login: jazzberry-ai[bot]
created_at: 2025-05-27T03:37:05Z
body: # Bug Report

| Name | Severity | Example test case | Description |\n|---|---|---|---|\n| Mermaid Diagram Rendering Error Feedback | Low | Render a Mermaid diagram that fails to parse. | The component logs an error to the console when a Mermaid diagram fails to render, but it doesn't provide any visual feedback to the user in the UI. The UI should provide some indication that the diagram failed to render. |\n| Mermaid Diagram Completion Detection Bypass | Medium | Render a Mermaid diagram that contains \`\`\`. | The component's completion detection logic can be bypassed if the mermaid diagram contains a triple backtick. This could prevent the diagram from rendering correctly. |\n

<sub>Comments? [Email us](mailto:support@jazzberry.ai).</sub>
author_association: NONE
user: login: jazzberry-ai[bot]
created_at: 2025-05-27T05:07:48Z
body: # Bug Report

| Name | Severity | Example test case | Description |
|---|---|---|---|
| Premature Mermaid Diagram Rendering with Backticks in Code | Medium | Render a mermaid diagram with backticks (`) inside the diagram code. | The `isComplete` check in `apps/registry/components/assistant-ui/mermaid-diagram.tsx` uses `part.text.split(code)[1]?.includes("```")` to determine if the mermaid code block is complete. This check is flawed because it doesn't account for backticks that may be present within the mermaid code itself. This leads to premature rendering or rendering failures when the mermaid code contains backticks. |

<sub>Comments? [Email us](mailto:support@jazzberry.ai).</sub>
author_association: NONE
user: login: jazzberry-ai[bot]
created_at: 2025-05-27T05:10:21Z
body: # Bug Report

| Name | Severity | Example test case | Description |
|---|---|---|---|
| Invalid Mermaid Code | Low | ```mermaid\ninvalid code``` |  The component logs an error to the console when the Mermaid code is invalid, but there is no visual indication to the user that the diagram failed to render. |

<sub>Comments? [Email us](mailto:support@jazzberry.ai).</sub>
author_association: NONE
user: login: jazzberry-ai[bot]
created_at: 2025-05-27T05:11:05Z
body: # Bug Report


Name | Severity | Example test case | Description
------- | -------- | -------- | --------
Potential XSS vulnerability | High | Include a malicious Mermaid diagram in a chat message (e.g., using the payload in `/tmp/xss2.md`) | The `mermaid-diagram` component renders Mermaid code as SVG. If the Mermaid library has XSS vulnerabilities, it could allow attackers to inject malicious JavaScript code into the user's browser.
Incomplete closing backtick detection | Low | Include whitespace before closing backticks | The `isComplete` check does not handle cases where whitespace is included before the closing backticks.


<sub>Comments? [Email us](mailto:support@jazzberry.ai).</sub>
author_association: NONE
user: login: jazzberry-ai[bot]
created_at: 2025-05-27T05:12:23Z
body: # Bug Report

Name | Severity | Example test case | Description
------- | -------- | ------------------- | -----------
Premature rendering of subsequent Mermaid diagrams in the same message | Medium | Include two Mermaid diagrams in the same chat message. | The `isComplete` function in `mermaid-diagram.tsx` uses `indexOf` which only finds the first mermaid diagram. The code block completion check is not robust and can lead to diagrams rendering prematurely in streaming scenarios.

<sub>Comments? [Email us](mailto:support@jazzberry.ai).</sub>
author_association: NONE
user: login: jazzberry-ai[bot]
created_at: 2025-05-27T15:52:51Z
body: # Bug Report

| Name | Severity | Example test case | Description |
|---|---|---|---|
| Incorrect Mermaid diagram completion check | Medium | A message containing two identical Mermaid diagrams. | The `isComplete` function in `mermaid-diagram.tsx` uses `indexOf` to find the code block, which can lead to incorrect completion detection when the same diagram code appears multiple times in a message. This can cause rendering issues. |


<sub>Comments? [Email us](mailto:support@jazzberry.ai).</sub>
author_association: NONE
user: login: trag-bot[bot]
created_at: 2025-05-27T15:54:03Z
body: @trag-bot didn't find any issues in the code! ✅✨
author_association: NONE