DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(visualize): add Mermaid mindmap visualizer (#1295)
evan188199-tech61a2cad184d9
diff --git a/deeptutor/agents/visualize/agents/analysis_agent.py b/deeptutor/agents/visualize/agents/analysis_agent.pyindex 9e3b13c50..52eb63338 100644--- a/deeptutor/agents/visualize/agents/analysis_agent.py+++ b/deeptutor/agents/visualize/agents/analysis_agent.py@@ -49,7 +49,7 @@ class AnalysisAgent(BaseAgent):rationale=f"User selected {render_mode} explicitly.",)- if render_mode in ("svg", "chartjs", "mermaid", "html"):+ if render_mode in ("svg", "chartjs", "mermaid", "mindmap", "html"):system_prompt = self.get_prompt("system_fixed")user_template = self.get_prompt("user_template_fixed")elif render_mode == "figure":@@ -67,7 +67,7 @@ class AnalysisAgent(BaseAgent):"user_input": user_input.strip(),"history_context": history_context.strip() or "(none)",}- if render_mode in ("svg", "chartjs", "mermaid", "html"):+ if render_mode in ("svg", "chartjs", "mermaid", "mindmap", "html"):format_kwargs["render_type"] = render_modeuser_prompt = user_template.format(**format_kwargs)@@ -90,7 +90,7 @@ class AnalysisAgent(BaseAgent):),)result = VisualizationAnalysis.model_validate(extract_json_object(raw))- if render_mode in ("svg", "chartjs", "mermaid", "html"):+ if render_mode in ("svg", "chartjs", "mermaid", "mindmap", "html"):result.render_type = render_mode # type: ignore[assignment]elif render_mode == "figure" and result.render_type not in ("svg",diff --git a/deeptutor/agents/visualize/agents/code_generator_agent.py b/deeptutor/agents/visualize/agents/code_generator_agent.pyindex 6012e9568..892b718d2 100644--- a/deeptutor/agents/visualize/agents/code_generator_agent.py+++ b/deeptutor/agents/visualize/agents/code_generator_agent.py@@ -75,7 +75,7 @@ class CodeGeneratorAgent(BaseAgent):if analysis.render_type == "svg":lang_hint = "svg"- elif analysis.render_type == "mermaid":+ elif analysis.render_type in ("mermaid", "mindmap"):lang_hint = "mermaid"elif analysis.render_type == "html":lang_hint = "html"diff --git a/deeptutor/agents/visualize/models.py b/deeptutor/agents/visualize/models.pyindex 8afb3bd40..6a0f0ded6 100644--- a/deeptutor/agents/visualize/models.py+++ b/deeptutor/agents/visualize/models.py@@ -13,6 +13,7 @@ RenderType = Literal["svg","chartjs","mermaid",+ "mindmap","html","manim_video","manim_image",diff --git a/deeptutor/agents/visualize/prompts/en/code_generator_agent.yaml b/deeptutor/agents/visualize/prompts/en/code_generator_agent.yamlindex 12d1dad9a..fbc144405 100644--- a/deeptutor/agents/visualize/prompts/en/code_generator_agent.yaml+++ b/deeptutor/agents/visualize/prompts/en/code_generator_agent.yaml@@ -136,6 +136,14 @@ rules_mermaid: |- Keep labels short and readable; check the diagram type keyword matches thestructure you're describing.+rules_mindmap: |+ Render type: Mermaid mind map. Output valid Mermaid `mindmap` DSL only:+ - The first non-empty line is exactly `mindmap`.+ - Use one root node, then indent each hierarchy level consistently. Include at+ least one child branch and no sibling roots.+ - Prefer short noun labels and no more than three levels. Do not use Markdown+ fences, flowchart arrows, or diagram syntax from another Mermaid type.+rules_html: |Render type: HTML. Output one complete, self-contained single-file HTML pagefor an interactive explainer, stepper, mockup, or clickable demo.@@ -177,4 +185,5 @@ user_template: |- SVG: ```svg ... ```- Chart.js: ```javascript ... ```- Mermaid: ```mermaid ... ```+ - Mind map: ```mermaid ... ```- HTML: ```html ... ```diff --git a/deeptutor/agents/visualize/prompts/zh/code_generator_agent.yaml b/deeptutor/agents/visualize/prompts/zh/code_generator_agent.yamlindex 7780a7df0..de85940bd 100644--- a/deeptutor/agents/visualize/prompts/zh/code_generator_agent.yaml+++ b/deeptutor/agents/visualize/prompts/zh/code_generator_agent.yaml@@ -113,6 +113,13 @@ rules_mermaid: |Mermaid 会自动解决——不要在 SVG 里手画。- 标签简短可读;核对图表类型关键词与你描述的结构一致。+rules_mindmap: |+ 渲染类型:Mermaid 思维导图。只输出有效的 Mermaid `mindmap` DSL:+ - 第一个非空行必须是 `mindmap`。+ - 只有一个根节点,层级缩进保持一致;至少包含一个子分支,不能出现多个根。+ - 优先使用简短名词标签,层级不超过三层。不要输出 Markdown 围栏、流程图箭头+ 或其他 Mermaid 图表语法。+rules_html: |渲染类型:HTML。输出一个完整、自包含的单文件 HTML 页面,用于交互式讲解、分步走读、UI 原型或可点击演示。@@ -150,4 +157,5 @@ user_template: |- SVG 用:```svg ... ```- Chart.js 用:```javascript ... ```- Mermaid 用:```mermaid ... ```+ - 思维导图用:```mermaid ... ```- HTML 用:```html ... ```diff --git a/deeptutor/agents/visualize/utils.py b/deeptutor/agents/visualize/utils.pyindex 0089b41f2..f1d7cbc93 100644--- a/deeptutor/agents/visualize/utils.py+++ b/deeptutor/agents/visualize/utils.py@@ -173,6 +173,24 @@ def validate_visualization(code: str, render_type: str) -> tuple[bool, str]:"erDiagram, gantt, mindmap, ...).")+ if render_type == "mindmap":+ if text.startswith("```"):+ return False, "Mermaid mindmap output must be raw DSL without a Markdown fence."+ lines = [+ (line, len(line) - len(line.lstrip()))+ for line in text.splitlines()+ if line.strip() and not line.lstrip().startswith("%%")+ ]+ if not lines or lines[0][0].strip() != "mindmap":+ return False, "Mermaid mindmap output must start with the `mindmap` keyword."+ root_indent = min(indent for _, indent in lines[1:])+ root_lines = [line for line, indent in lines[1:] if indent == root_indent]+ if len(root_lines) != 1 or not root_lines[0].strip():+ return False, "Mermaid mindmap output must contain exactly one non-empty root node."+ if not any(indent > root_indent for _, indent in lines[2:]):+ return False, "Mermaid mindmap output needs at least one child branch."+ return True, ""+if render_type == "html":if is_valid_html_document(text):return True, ""diff --git a/deeptutor/visualizers/builtin.py b/deeptutor/visualizers/builtin.pyindex a6838da06..0c616c1a2 100644--- a/deeptutor/visualizers/builtin.py+++ b/deeptutor/visualizers/builtin.py@@ -203,6 +203,30 @@ top-to-bottom layout for explanations and left-to-right for short processes.origin="core",validator=_text_validator("mermaid"),),+ VisualizerPlugin(+ manifest=VisualizerManifest(+ id="mindmap",+ display_name="Mind map",+ description="Hierarchical topics and relationships rendered by Mermaid.",+ subjects=["general"],+ intents=["structure", "outline", "explain"],+ native_renderer="mermaid",+ payload_format="text/vnd.mermaid",+ language_tag="mermaid",+ core=True,+ priority=25,+ prompt=_GENERAL+ + """++Return valid Mermaid mindmap DSL only. The first non-empty line must be+`mindmap`, followed by exactly one root node and at least one child branch.+Indent each hierarchy level consistently, keep labels short, and do not use+Markdown fences, arrows, or flowchart node syntax.+""",+ ),+ origin="core",+ validator=_text_validator("mindmap"),+ ),VisualizerPlugin(manifest=VisualizerManifest(id="chartjs",diff --git a/tests/agents/visualize/test_analysis_fallback.py b/tests/agents/visualize/test_analysis_fallback.pyindex 5f97cf74e..442f14767 100644--- a/tests/agents/visualize/test_analysis_fallback.py+++ b/tests/agents/visualize/test_analysis_fallback.py@@ -175,3 +175,18 @@ def test_known_enum_values_are_left_alone() -> None:assert result.render_type == "mermaid"assert result.visual_genre == "structural"+++async def test_fixed_mindmap_mode_is_preserved(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _install_agent_stubs(monkeypatch, _FIXED_PROMPTS, _llm_reply("diagram"))++ result = await AnalysisAgent().process(+ user_input="organize photosynthesis concepts",+ history_context="",+ render_mode="mindmap",+ )++ assert result.render_type == "mindmap"diff --git a/tests/agents/visualize/test_validate_visualization.py b/tests/agents/visualize/test_validate_visualization.pynew file mode 100644index 000000000..b68aa368b--- /dev/null+++ b/tests/agents/visualize/test_validate_visualization.py@@ -0,0 +1,56 @@+from deeptutor.agents.visualize.utils import validate_visualization++VALID_MINDMAP = """mindmap+ root((Cell biology))+ Organelles+ Mitochondria+ Transport+"""+++def test_mindmap_validation_accepts_hierarchical_root() -> None:+ ok, error = validate_visualization(VALID_MINDMAP, "mindmap")++ assert ok is True, error+ assert error == ""+++def test_mindmap_validation_rejects_wrong_keyword() -> None:+ ok, error = validate_visualization("graph TD\n A-->B", "mindmap")++ assert ok is False+ assert "start with the `mindmap` keyword" in error+++def test_mindmap_validation_requires_exact_keyword_case() -> None:+ ok, error = validate_visualization(+ "Mindmap\n Root\n Child",+ "mindmap",+ )++ assert ok is False+ assert "start with the `mindmap` keyword" in error+++def test_mindmap_validation_rejects_multiple_roots() -> None:+ ok, error = validate_visualization(+ "mindmap\n Root A\n Child\n Root B\n Child",+ "mindmap",+ )++ assert ok is False+ assert "exactly one non-empty root" in error+++def test_mindmap_validation_rejects_root_without_children() -> None:+ ok, error = validate_visualization("mindmap\n Root only", "mindmap")++ assert ok is False+ assert "at least one child branch" in error+++def test_mindmap_validation_rejects_markdown_fence() -> None:+ ok, error = validate_visualization(f"```mermaid\n{VALID_MINDMAP}```", "mindmap")++ assert ok is False+ assert "without a Markdown fence" in errordiff --git a/tests/visualizers/test_registry_and_tool.py b/tests/visualizers/test_registry_and_tool.pyindex f77e193c0..e34f017ab 100644--- a/tests/visualizers/test_registry_and_tool.py+++ b/tests/visualizers/test_registry_and_tool.py@@ -115,6 +115,20 @@ def test_core_visualizer_quality_gates(tmp_path: Path) -> None:assert ok is True, errorassert data["data"]["datasets"][0]["label"] == "Recall"+ mindmap = registry.get("mindmap")+ assert mindmap is not None+ assert mindmap.manifest.core is True+ assert mindmap.manifest.native_renderer == "mermaid"+ assert mindmap.manifest.payload_format == "text/vnd.mermaid"+ ok, _, error = mindmap.validate_payload("mindmap\n Root")+ assert ok is False+ assert "child branch" in error+ ok, data, error = mindmap.validate_payload(+ "mindmap\n Root((Learning))\n Memory\n Recall"+ )+ assert ok is True, error+ assert data.startswith("mindmap\n Root((Learning))")+html = registry.get("html")assert html is not Noneok, _, error = html.validate_payload("<div>Not a complete lab</div>")@@ -128,6 +142,14 @@ def test_core_visualizer_quality_gates(tmp_path: Path) -> None:assert ok is True, error+def test_visualize_request_contract_accepts_mindmap() -> None:+ from deeptutor.runtime.request_contracts import validate_visualize_request_config++ config = validate_visualize_request_config({"render_mode": "mindmap"})++ assert config.render_mode == "mindmap"++@pytest.mark.asyncioasync def test_submit_tool_validates_and_commits_geogebra_envelope(tmp_path: Path) -> None:registry = _registry(tmp_path)diff --git a/web/components/visualize/VisualizationViewer.tsx b/web/components/visualize/VisualizationViewer.tsxindex a62bc91b7..29cfe057b 100644--- a/web/components/visualize/VisualizationViewer.tsx+++ b/web/components/visualize/VisualizationViewer.tsx@@ -449,7 +449,7 @@ function CanvasVisualization({ result }: { result: VisualizeCanvasResult }) {if (renderer === "svg") {return <SvgRenderer svg={result.code.content} />;}- if (renderer === "mermaid") {+ if (renderer === "mermaid" || renderer === "mindmap") {return <Mermaid chart={result.code.content} />;}if (renderer === "html") {@@ -500,6 +500,9 @@ function visualizationLabel(result: VisualizeCanvasResult): string {if (renderer === "mermaid") {return `Mermaid · ${result.analysis.chart_type || "diagram"}`;}+ if (renderer === "mindmap") {+ return `Mind map · ${result.presentation.title || "topics"}`;+ }return result.presentation.title? `${result.renderer.id} · ${result.presentation.title}`: result.renderer.id;diff --git a/web/components/visualize/VisualizeConfigPanel.tsx b/web/components/visualize/VisualizeConfigPanel.tsxindex a6ac63ac3..c18dc336c 100644--- a/web/components/visualize/VisualizeConfigPanel.tsx+++ b/web/components/visualize/VisualizeConfigPanel.tsx@@ -120,6 +120,7 @@ export default memo(function VisualizeConfigPanel({<option value="chartjs">{t("Chart.js")}</option><option value="svg">{t("SVG")}</option><option value="mermaid">{t("Mermaid")}</option>+ <option value="mindmap">{t("Mind map")}</option><option value="html">{t("HTML")}</option><option value="manim_video">{t("Animation")}</option><option value="manim_image">{t("Storyboard")}</option>diff --git a/web/lib/visualize-types.ts b/web/lib/visualize-types.tsindex 57a6192f2..ee8e82ae9 100644--- a/web/lib/visualize-types.ts+++ b/web/lib/visualize-types.ts@@ -1,7 +1,12 @@import type { MathAnimatorResult } from "@/lib/math-animator-types";import { extractMathAnimatorResult } from "@/lib/math-animator-types";-export type VisualizeTextRenderType = "svg" | "chartjs" | "mermaid" | "html";+export type VisualizeTextRenderType =+ | "svg"+ | "chartjs"+ | "mermaid"+ | "mindmap"+ | "html";export type VisualizeManimRenderType = "manim_video" | "manim_image";export type VisualizeRenderType = string;export type VisualizeRenderMode = "auto" | (string & {});@@ -33,6 +38,7 @@ const VISUALIZE_RENDER_LABELS: Record<string, string> = {chartjs: "Chart.js",svg: "SVG",mermaid: "Mermaid",+ mindmap: "Mind map",html: "HTML",geogebra: "GeoGebra",manim_video: "Animation",@@ -166,10 +172,13 @@ export function extractVisualizeResult(const inferredRenderer =renderType === "svg" ||renderType === "mermaid" ||+ renderType === "mindmap" ||renderType === "chartjs" ||renderType === "html" ||renderType === "geogebra"- ? renderType+ ? renderType === "mindmap"+ ? "mermaid"+ : renderType: "";return {diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex c746a517f..58d8ea050 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -790,6 +790,7 @@"Chart.js": "Chart.js","SVG": "SVG","Mermaid": "Mermaid",+ "Mind map": "Mind map","Reference": "Reference","Show code": "Show code","Hide code": "Hide code",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex fd70fc556..ca15e5a14 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -819,6 +819,7 @@"Chart.js": "Chart.js","SVG": "SVG","Mermaid": "Mermaid",+ "Mind map": "思维导图","Reference": "引用","Show code": "显示代码","Hide code": "隐藏代码",diff --git a/web/tests/visualize-types.test.ts b/web/tests/visualize-types.test.tsindex 2cc7de0b6..3e4fdc8ee 100644--- a/web/tests/visualize-types.test.ts+++ b/web/tests/visualize-types.test.ts@@ -41,3 +41,16 @@ test("keeps legacy SVG results renderable", () => {assert.equal(result.renderer.native_renderer, "svg");assert.equal(result.payload.data, "<svg viewBox='0 0 10 10'></svg>");});++test("keeps legacy mindmap results renderable with Mermaid", () => {+ const result = extractVisualizeResult({+ render_type: "mindmap",+ code: { language: "mermaid", content: "mindmap\n Root\n Child" },+ });++ assert.ok(result && !isManimResult(result));+ if (!result || isManimResult(result)) return;+ assert.equal(result.renderer.id, "mindmap");+ assert.equal(result.renderer.native_renderer, "mermaid");+ assert.equal(result.code.language, "mermaid");+});