Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

fix(chat): render marimo HTML styled in mo.ui.chat (#9847) (#9888)

Myles Scolnick29352cfe0e72
diff --git a/frontend/package.json b/frontend/package.json
index 71ab468fbd..4c3dce19a5 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -141,6 +141,7 @@
"react-vega": "^8.0.0",
"react-virtuoso": "^4.18.1",
"reactflow": "^11.11.4",
+ "rehype-sanitize": "^6.0.0",
"remark-gfm": "^4.0.1",
"reveal.js": "^6.0.0",
"rpc-anywhere": "^1.7.0",
diff --git a/frontend/src/components/chat/chat-display.tsx b/frontend/src/components/chat/chat-display.tsx
index 13ef992279..249ded2685 100644
--- a/frontend/src/components/chat/chat-display.tsx
+++ b/frontend/src/components/chat/chat-display.tsx
@@ -60,8 +60,8 @@ export const renderUIMessage = ({
switch (part.type) {
case "text":
- // Streamdown sanitizes the HTML which strips out marimo elements
- // So instead, we render the HTML with our custom renderer.
+ // Streamdown strips marimo elements, so render them with our own HTML
+ // renderer. Other markdown (incl. mo.md HTML) goes through Streamdown.
if (part.text.includes("<marimo-")) {
return (
<React.Fragment key={index}>
diff --git a/frontend/src/components/markdown/__tests__/markdown-renderer.test.tsx b/frontend/src/components/markdown/__tests__/markdown-renderer.test.tsx
new file mode 100644
index 0000000000..05f0ad3992
--- /dev/null
+++ b/frontend/src/components/markdown/__tests__/markdown-renderer.test.tsx
@@ -0,0 +1,43 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import { render, screen, waitFor } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import { MarkdownRenderer } from "../markdown-renderer";
+
+describe("MarkdownRenderer", () => {
+ // Regression test for https://github.com/marimo-team/marimo/issues/9847
+ it("preserves class names on raw HTML (e.g. marimo admonitions)", async () => {
+ const { container } = render(
+ <MarkdownRenderer
+ content={
+ '<div class="admonition error">' +
+ '<p class="admonition-title">Error</p>' +
+ "<p>Nope!</p>" +
+ "</div>"
+ }
+ />,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByText("Nope!")).toBeInTheDocument();
+ });
+
+ const admonition = container.querySelector(".admonition.error");
+ expect(admonition).toBeInTheDocument();
+ expect(container.querySelector(".admonition-title")).toBeInTheDocument();
+ });
+
+ it("strips unsafe tags while keeping class names", async () => {
+ const { container } = render(
+ <MarkdownRenderer
+ content={'<div class="safe"><script>alert(1)</script>hello</div>'}
+ />,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByText("hello")).toBeInTheDocument();
+ });
+
+ expect(container.querySelector(".safe")).toBeInTheDocument();
+ expect(container.querySelector("script")).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/components/markdown/markdown-renderer.tsx b/frontend/src/components/markdown/markdown-renderer.tsx
index 05ccc31c26..2396e60abb 100644
--- a/frontend/src/components/markdown/markdown-renderer.tsx
+++ b/frontend/src/components/markdown/markdown-renderer.tsx
@@ -4,7 +4,12 @@ import { EditorView } from "@codemirror/view";
import { useAtomValue } from "jotai";
import { BetweenHorizontalStartIcon } from "lucide-react";
import { memo, Suspense, useState } from "react";
-import { Streamdown, type StreamdownProps } from "streamdown";
+import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
+import {
+ defaultRehypePlugins,
+ Streamdown,
+ type StreamdownProps,
+} from "streamdown";
import { Button, type ButtonProps } from "@/components/ui/button";
import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";
import { useCellActions } from "@/core/cells/cells";
@@ -148,6 +153,23 @@ const CopyButton: React.FC<ButtonProps> = ({ onClick, ...props }) => {
);
};
+// Allow `className` on every element; the default GitHub schema strips it,
+// which drops the styling on marimo HTML like `mo.md(...)` admonitions.
+const sanitizeSchema = {
+ ...defaultSchema,
+ attributes: {
+ ...defaultSchema.attributes,
+ "*": [...(defaultSchema.attributes?.["*"] ?? []), "className"],
+ },
+};
+
+// Keep Streamdown's other rehype plugins (raw, harden) so scripts and unsafe
+// URLs are still sanitized.
+const REHYPE_PLUGINS: StreamdownProps["rehypePlugins"] = Object.values({
+ ...defaultRehypePlugins,
+ sanitize: [rehypeSanitize, sanitizeSchema],
+});
+
type Components = StreamdownProps["components"];
const COMPONENTS: Components = {
@@ -187,6 +209,7 @@ export const MarkdownRenderer = memo(({ content }: { content: string }) => {
<Streamdown
components={COMPONENTS}
plugins={plugins}
+ rehypePlugins={REHYPE_PLUGINS}
className="mo-markdown-renderer"
>
{content}
diff --git a/marimo/_output/md.py b/marimo/_output/md.py
index 21cc60efa2..e800c109db 100644
--- a/marimo/_output/md.py
+++ b/marimo/_output/md.py
@@ -269,10 +269,16 @@ class _md(Html):
# markdown.markdown appends a newline, hence strip
html_text = _render_markdown(text).strip()
- # replace <p> tags with <span> as HTML doesn't allow nested <div>s in <p>s
- html_text = html_text.replace(
- "<p>", '<span class="paragraph">'
- ).replace("</p>", "</span>")
+ # replace <p> tags with <span> as HTML doesn't allow nested <div>s in
+ # <p>s, including the admonition title's <p> so its </p> stays matched
+ html_text = (
+ html_text.replace(
+ '<p class="admonition-title">',
+ '<span class="admonition-title">',
+ )
+ .replace("<p>", '<span class="paragraph">')
+ .replace("</p>", "</span>")
+ )
if apply_markdown_class:
classes = ["markdown", "prose", "dark:prose-invert", "contents"]
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a08f05834b..4460818fa5 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -397,6 +397,9 @@ importers:
reactflow:
specifier: ^11.11.4
+ rehype-sanitize:
+ specifier: ^6.0.0
+ version: 6.0.0
remark-gfm:
specifier: ^4.0.1
version: 4.0.1
diff --git a/tests/_output/test_md.py b/tests/_output/test_md.py
index 1a3706fb71..5870833c11 100644
--- a/tests/_output/test_md.py
+++ b/tests/_output/test_md.py
@@ -278,6 +278,45 @@ def test_md_nested_list_preserves_multi_paragraph() -> None:
)
+def test_md_admonition_paragraph_tags_balanced() -> None:
+ # Regression for https://github.com/marimo-team/marimo/issues/9847
+ input_text = """/// error
+Nope!
+///"""
+
+ result = _md(input_text, apply_markdown_class=False).text
+ assert result == snapshot(
+ """\
+<div class="admonition error">
+<span class="admonition-title">Error</span>
+<span class="paragraph">Nope!</span>
+</div>\
+"""
+ )
+ assert '<p class="admonition-title"' not in result
+ assert "<p>" not in result
+ assert "</p>" not in result
+
+
+ "kind", ["note", "warning", "danger", "tip", "error", "caution"]
+)
+def test_md_admonition_well_formed(kind: str) -> None:
+ result = _md(f"/// {kind}\nBody text\n///").text
+ assert f'<div class="admonition {kind}">' in result
+ assert '<span class="admonition-title">' in result
+ assert '<span class="paragraph">Body text</span>' in result
+ assert "<p>" not in result
+ assert "</p>" not in result
+
+
+def test_md_admonition_custom_title_well_formed() -> None:
+ result = _md("/// note | My Title\nbody here\n///").text
+ assert '<span class="admonition-title">My Title</span>' in result
+ assert "<p>" not in result
+ assert "</p>" not in result
+
+
def test_md_nested_list_with_inline_elements() -> None:
# Inline elements like bold/italic/code should survive p-unwrapping
input_text = """- **Bold item**