DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(book): keep chapter map titles visible (#889)
Bingxi Zhao0e17712888a2
diff --git a/deeptutor/book/blocks/concept_graph.py b/deeptutor/book/blocks/concept_graph.pyindex 90306098b..6b9d38bfa 100644--- a/deeptutor/book/blocks/concept_graph.py+++ b/deeptutor/book/blocks/concept_graph.py@@ -29,12 +29,10 @@ def _safe_id(node_id: str, used: set[str]) -> str:return candidate-def _escape_label(text: str, *, max_len: int = 48) -> str:- """Mermaid-safe label: collapse whitespace and escape quotes."""+def _escape_label(text: str) -> str:+ """Return a complete, single-line Mermaid-safe label."""cleaned = " ".join((text or "").split())cleaned = cleaned.replace('"', "'")- if len(cleaned) > max_len:- cleaned = cleaned[: max_len - 1] + "…"return cleaned or "concept"@@ -43,7 +41,8 @@ def render_mermaid(graph: ConceptGraph) -> str:When nodes carry ``chapter_id`` (chapter-level mind map produced by``_build_chapter_map``), each node is rendered with a chapter number- prefix and a slightly shorter label to keep the diagram readable.+ prefix. Labels stay complete; the frontend provides a scrollable viewport+ for diagrams wider or taller than the available card.The virtual book-title root (no ``chapter_id``) gets a stadium shape``(["..."])`` to stand out visually."""@@ -63,10 +62,10 @@ def render_mermaid(graph: ConceptGraph) -> str:if chapter_mode and node.chapter_id:chapter_seq += 1num = str(chapter_seq).zfill(2)- label = _escape_label(node.label, max_len=28)+ label = _escape_label(node.label)lines.append(f' {sid}["{num} · {label}"]')elif chapter_mode and not node.chapter_id:- label = _escape_label(node.label, max_len=36)+ label = _escape_label(node.label)lines.append(f' {sid}(["{label}"])')else:lines.append(f' {sid}["{_escape_label(node.label)}"]')diff --git a/tests/book/test_concept_graph.py b/tests/book/test_concept_graph.pynew file mode 100644index 000000000..0c778ff11--- /dev/null+++ b/tests/book/test_concept_graph.py@@ -0,0 +1,21 @@+from __future__ import annotations++from deeptutor.book.blocks.concept_graph import render_mermaid+from deeptutor.book.models import ConceptEdge, ConceptGraph, ConceptNode+++def test_mermaid_keeps_complete_chapter_titles() -> None:+ title = "Understanding transformations through complete geometric intuition"+ graph = ConceptGraph(+ nodes=[+ ConceptNode(id="root", label='A "quoted" book'),+ ConceptNode(id="chapter-one", label=title, chapter_id="chapter-1"),+ ],+ edges=[ConceptEdge(src="root", dst="chapter-one")],+ )++ rendered = render_mermaid(graph)++ assert title in rendered+ assert "A 'quoted' book" in rendered+ assert "…" not in rendereddiff --git a/web/app/(workspace)/book/components/blocks/ConceptGraphBlock.tsx b/web/app/(workspace)/book/components/blocks/ConceptGraphBlock.tsxindex a5e0eaaa4..986bd7806 100644--- a/web/app/(workspace)/book/components/blocks/ConceptGraphBlock.tsx+++ b/web/app/(workspace)/book/components/blocks/ConceptGraphBlock.tsx@@ -1,11 +1,11 @@"use client";-import { useMemo } from "react";import Link from "next/link";import { Compass } from "lucide-react";import { useTranslation } from "react-i18next";import MarkdownRenderer from "@/components/common/MarkdownRenderer";+import { renderConceptGraphMermaid } from "@/lib/concept-graph";import type { Block, ConceptGraph } from "@/lib/book-types";export interface ConceptGraphBlockProps {@@ -64,17 +64,15 @@ export default function ConceptGraphBlock({(block.payload?.code as| { language?: string; content?: string }| undefined) || {};- const mermaidSrc = String(code.content || "").trim();const graph = asGraph(block.payload?.graph);+ const mermaidSrc = graph+ ? renderConceptGraphMermaid(graph)+ : String(code.content || "").trim();const index = asIndex(block.payload?.index);- const fenced = useMemo(- () =>- mermaidSrc- ? `\`\`\`mermaid\n${mermaidSrc}\n\`\`\``- : '```mermaid\ngraph TD\n empty["(no concepts yet)"]\n```',- [mermaidSrc],- );+ const fenced = mermaidSrc+ ? `\`\`\`mermaid\n${mermaidSrc}\n\`\`\``+ : '```mermaid\ngraph TD\n empty["(no concepts yet)"]\n```';const chapterNodes = graph?.nodes.filter((n) => n.chapter_id) ?? [];const isChapterMap = chapterNodes.length > 0;@@ -125,7 +123,7 @@ export default function ConceptGraphBlock({<span className="text-[10px] font-mono text-[var(--muted-foreground)]">{String(idx + 1).padStart(2, "0")}</span>- <span className="line-clamp-2 text-xs font-medium leading-snug text-[var(--foreground)]">+ <span className="text-xs font-medium leading-snug text-[var(--foreground)]">{chapter.title}</span></span>@@ -135,6 +133,7 @@ export default function ConceptGraphBlock({<li key={chapter.id}><Linkhref={`/book/${bookId}?page=${chapter.page_id}`}+ title={chapter.title}className="block rounded-md px-2 py-1.5 hover:bg-[var(--background)]">{label}@@ -145,6 +144,7 @@ export default function ConceptGraphBlock({return (<likey={chapter.id}+ title={chapter.title}className="rounded-md px-2 py-1.5 text-[var(--foreground)]">{label}diff --git a/web/lib/concept-graph.ts b/web/lib/concept-graph.tsnew file mode 100644index 000000000..23b5cd974--- /dev/null+++ b/web/lib/concept-graph.ts@@ -0,0 +1,68 @@+import type { ConceptGraph } from "@/lib/book-types";++function safeNodeId(nodeId: string, used: Set<string>): string {+ const cleaned = (nodeId || "n")+ .replace(/[^\p{L}\p{N}]/gu, "_")+ .replace(/^_+|_+$/g, "") || "n";+ let candidate = cleaned.slice(0, 32);+ let suffix = 1;+ while (used.has(candidate)) {+ suffix += 1;+ candidate = `${cleaned.slice(0, 30)}_${suffix}`;+ }+ used.add(candidate);+ return candidate;+}++function safeLabel(label: string): string {+ return label.trim().replace(/\s+/g, " ").replaceAll('"', "'") || "concept";+}++/**+ * Rebuild the deterministic Mermaid source from structured graph data.+ *+ * Stored books created by older releases may carry already-truncated Mermaid+ * labels even though their structured nodes retain the complete titles.+ * Rendering from the structured source repairs those books in place.+ */+export function renderConceptGraphMermaid(graph: ConceptGraph): string {+ if (graph.nodes.length === 0) {+ return 'graph TD\n empty["(no concepts yet)"]';+ }++ const chapterMode = graph.nodes.some((node) => Boolean(node.chapter_id));+ const used = new Set<string>();+ const idMap = new Map<string, string>();+ const lines = ["graph TD"];+ let chapterSequence = 0;++ for (const node of graph.nodes) {+ const id = safeNodeId(node.id || node.label, used);+ idMap.set(node.id, id);+ const label = safeLabel(node.label);+ if (chapterMode && node.chapter_id) {+ chapterSequence += 1;+ lines.push(+ ` ${id}["${String(chapterSequence).padStart(2, "0")} · ${label}"]`,+ );+ } else if (chapterMode) {+ lines.push(` ${id}(["${label}"])`);+ } else {+ lines.push(` ${id}["${label}"]`);+ }+ }++ const arrows = new Map([+ ["depends_on", "-->"],+ ["extends", "==>"],+ ["related", "-.->"],+ ]);+ for (const edge of graph.edges) {+ const source = idMap.get(edge.src);+ const target = idMap.get(edge.dst);+ if (source && target) {+ lines.push(` ${source} ${arrows.get(edge.relation) || "-->"} ${target}`);+ }+ }+ return lines.join("\n");+}diff --git a/web/tests/concept-graph.test.ts b/web/tests/concept-graph.test.tsnew file mode 100644index 000000000..a00edd661--- /dev/null+++ b/web/tests/concept-graph.test.ts@@ -0,0 +1,40 @@+import assert from "node:assert/strict";+import test from "node:test";++import { renderConceptGraphMermaid } from "../lib/concept-graph";++test("stored concept graphs render complete chapter titles", () => {+ const title =+ "Understanding transformations through complete geometric intuition";+ const rendered = renderConceptGraphMermaid({+ nodes: [+ {+ id: "root",+ label: 'A "quoted" book',+ chapter_id: "",+ description: "",+ weight: 1,+ },+ {+ id: "chapter-one",+ label: title,+ chapter_id: "chapter-1",+ description: "",+ weight: 1,+ },+ ],+ edges: [+ {+ src: "root",+ dst: "chapter-one",+ relation: "depends_on",+ rationale: "",+ },+ ],+ });++ assert.match(rendered, /root\(\["A 'quoted' book"\]\)/);+ assert.ok(rendered.includes(`chapter_one["01 · ${title}"]`));+ assert.ok(rendered.includes("root --> chapter_one"));+ assert.equal(rendered.includes("…"), false);+});