DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
release: v1.5.13
Bingxi Zhao (Frank)96d6df9eb1a3
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlindex d8d4c287b..1ff723967 100644--- a/.github/ISSUE_TEMPLATE/bug_report.yml+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -46,8 +46,12 @@ body:- Question Generator- Deep Research- Co-Writer+ - Book- Notebook- Guided Learning+ - Partners / TutorBot+ - Memory+ - Skills / MCP- Idea Generation- API/Backend- Frontend/Webdiff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.ymlindex 756d08c17..53cd20b54 100644--- a/.github/ISSUE_TEMPLATE/feature_request.yml+++ b/.github/ISSUE_TEMPLATE/feature_request.yml@@ -30,8 +30,12 @@ body:- Question Generator- Deep Research- Co-Writer+ - Book- Notebook- Guided Learning+ - Partners / TutorBot+ - Memory+ - Skills / MCP- Idea Generation- API/Backend- Frontend/Webdiff --git a/README.md b/README.mdindex 4803248eb..cfcacf30a 100644--- a/README.md+++ b/README.md@@ -49,15 +49,17 @@### 📦 Releases+> **[2026.8.17]** [v1.5.13](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.13) — Books stream while they compile, track your progress, and export to Markdown; a cost estimate before you approve a spine; and home starter suggestions drawn from memory.+> **[2026.8.13]** [v1.5.12](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.12) — Web search rebuilt with six new providers (**Doubao**, **Bocha**, **Zhipu**, **Firecrawl**, **Qianfan**, **Aliyun IQS**), a **LiteParse** parsing engine, MCP servers that reconnect on credential change, and **CodeBuddy** + **OrcaRouter**.+<details>+<summary><b>Past releases (more than 1 week ago)</b></summary>+> **[2026.8.10]** [v1.5.11](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.11) — Prose around a DSML tool call stops vanishing, a truncated reply continues instead of ending, live memory usage in Settings, and LightRAG indexing off the event loop.> **[2026.8.7]** [v1.5.10](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.10) — Every account signs in to its own **Codex**, model output language becomes its own setting, empty tool calls are rejected instead of retried, and uploads stop blocking the loop.-<details>-<summary><b>Past releases (more than 1 week ago)</b></summary>-> **[2026.8.4]** [v1.5.9](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.9) — Gemini **Embedding 2** on its native endpoint, a per-model **reasoning effort** control, a **Novita AI** gateway, retrieval roles for queries, and Compose deployments that keep all of `data/`.> **[2026.8.2]** [v1.5.8](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.8) — Memory: a real heap ceiling for the dev server, source installs serve a production build, bounded LLM client and index caches, and a keep-alive fix for stray 500s.@@ -566,7 +568,7 @@ Book turns selected sources into an interactive **living book** — not a static<img src="assets/figs/web-1.4.6+/book/03-book-demo%20interactive%20module.png" alt="Book interactive widget block" width="31%"></p>-Each chapter compiles into typed blocks — text, callouts, quizzes, flash cards, timelines, code, figures, interactive HTML, animations, concept graphs, deep dives, and user notes — and every page has its own Page Chat. Blocks are editable: insert, move, regenerate, or switch a block's type without rewriting the chapter. Maintenance commands such as `deeptutor book health` and `deeptutor book refresh-fingerprints` help detect when source knowledge has drifted from compiled pages.+Each chapter compiles into typed blocks — text, callouts, quizzes, flash cards, timelines, code, figures, interactive HTML, animations, concept graphs, deep dives, and user notes — and every page has its own Page Chat. Blocks are editable: insert, move, regenerate, rewrite a body, or switch a type without redoing the chapter. Visited pages, bookmarks, and quiz attempts roll up into a completion score and weak chapters; any book exports to Markdown. A long compile pauses and resumes; `deeptutor book health` and `refresh-fingerprints` flag source knowledge that has drifted.</details>diff --git a/assets/README/README_AR.md b/assets/README/README_AR.mdindex 4eee7e581..c162d8b5f 100644--- a/assets/README/README_AR.md+++ b/assets/README/README_AR.md@@ -409,7 +409,7 @@ Co-Writer هو مساحة عمل Markdown ذات عرض مقسَّم للتقا<img src="../../assets/figs/web-1.4.6+/book/03-book-demo%20interactive%20module.png" alt="كتلة ودجت تفاعلية في الكتاب" width="31%"></p>-يُجمِّع كل فصل إلى كتل مكتوبة — نصوص وأقسام وتنبيهات واختبارات وبطاقات فلاش وجداول زمنية ورمز وأشكال وHTML تفاعلية ورسوم متحركة وأشكال مفاهيم وغوص عميق وملاحظات مستخدم — وكل صفحة لها Page Chat الخاصة بها. الكتل قابلة للتحرير: أدرج أو حرّك أو أعد التوليد أو غيّر نوع الكتلة بدون إعادة كتابة الفصل. أوامر الصيانة مثل `deeptutor book health` و`deeptutor book refresh-fingerprints` تساعد في الكشف عن انجراف معرفة المصدر من الصفحات المُجمَّعة.+يُجمِّع كل فصل إلى كتل مكتوبة — نصوص وأقسام وتنبيهات واختبارات وبطاقات فلاش وجداول زمنية ورمز وأشكال وHTML تفاعلية ورسوم متحركة وأشكال مفاهيم وغوص عميق وملاحظات مستخدم — وكل صفحة لها Page Chat الخاصة بها. الكتل قابلة للتحرير: أدرج أو حرّك أو أعد التوليد أو أعد كتابة المحتوى أو غيّر النوع دون إعادة عمل الفصل. تتجمّع الصفحات التي زُرتها والإشارات المرجعية ومحاولات الاختبار في نتيجة إتمام وفصول ضعيفة؛ ويمكن تصدير أي كتاب إلى Markdown. التجميع الطويل يتوقف مؤقتاً ويستأنف؛ ويُبلِّغ `deeptutor book health` و`refresh-fingerprints` عن انجراف معرفة المصدر.</details>@@ -426,7 +426,7 @@ Co-Writer هو مساحة عمل Markdown ذات عرض مقسَّم للتقا<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="إنشاء قاعدة معرفة" width="900"></div>-عند إنشاء قاعدة معرفة، إما أن **تنشئ جديدة** (تحميل مستندات وبناء فهرس جديد) أو **تربط موجودة** (إعادة استخدام فهرس مبني في مكان آخر، قراءة في مكانه بدون إعادة فهرسة). تكتب إعادة الفهرسة دليل `version-N` مسطحاً جديداً وتحتفظ بالسابقة، لذا لا يُدمَّر فهرس عامل أبداً أثناء إعادة البناء. يمكن إزالة مستند واحد حتى من قاعدة في حالة **خطأ** — إسقاط ملف فشل تحليله بدون حذف وإعادة بناء كاملين. تحليل المستندات — نص فقط أو MinerU أو Docling أو markitdown أو PyMuPDF4LLM أو LiteParse — يُختار في **الإعدادات ← قاعدة المعرفة**، مع إيقاف تنزيلات النماذج المحلية افتراضياً. تعكس واجهة CLI دورة الحياة مع `deeptutor kb list` و`info` و`create` و`add` و`search` و`set-default` و`delete`.+عند إنشاء قاعدة معرفة، إما أن **تنشئ جديدة** (تحميل مستندات وبناء فهرس جديد) أو **تربط موجودة** (إعادة استخدام فهرس مبني في مكان آخر، قراءة في مكانه بدون إعادة فهرسة). تكتب إعادة الفهرسة دليل `version-N` مسطحاً جديداً وتحتفظ بالسابقة، لذا لا يُدمَّر فهرس عامل أبداً أثناء إعادة البناء. يمكن إزالة مستند واحد حتى من قاعدة في حالة **خطأ** — إسقاط ملف فشل تحليله بدون حذف وإعادة بناء كاملين. تحليل المستندات — نص فقط أو MinerU أو Docling أو markitdown أو PyMuPDF4LLM أو LiteParse — يُختار في **الإعدادات ← قاعدة المعرفة**، مع إيقاف تنزيلات النماذج المحلية افتراضياً. يمكن لـ Docling أيضاً العمل في وضع **بعيد** مقابل خادم Docling Serve (بلا حاجة إلى تثبيت محلي أو نماذج)، يُهيَّأ عبر **الإعدادات ← تحليل المستندات** (`mode=remote`، وعنوان URL أساسي للخادم، ومفتاح API اختياري) أو متغيرات البيئة `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN`. تعكس واجهة CLI دورة الحياة مع `deeptutor kb list` و`info` و`create` و`add` و`search` و`set-default` و`delete`.</details>diff --git a/assets/README/README_CN.md b/assets/README/README_CN.mdindex dd16c56fb..e3814d0b0 100644--- a/assets/README/README_CN.md+++ b/assets/README/README_CN.md@@ -409,7 +409,7 @@ Book 将选定的来源转化为交互式**活书** — 不是静态 PDF,而<img src="../../assets/figs/web-1.4.6+/book/03-book-demo%20interactive%20module.png" alt="Book 交互式组件块" width="31%"></p>-每章编译为类型化块 — 文本、标注、测验、闪卡、时间轴、代码、图形、交互式 HTML、动画、概念图、深度解析和用户笔记 — 每页都有独立的 Page Chat。块可编辑:插入、移动、重新生成或切换块类型,无需重写整章。维护命令如 `deeptutor book health` 和 `deeptutor book refresh-fingerprints` 有助于检测来源知识库与已编译页面的漂移情况。+每章编译为类型化块 — 文本、标注、测验、闪卡、时间轴、代码、图形、交互式 HTML、动画、概念图、深度解析和用户笔记 — 每页都有独立的 Page Chat。块可编辑:插入、移动、重新生成、改写正文或切换类型,无需重做整章。访问过的页面、书签和测验作答会汇总为完成度分数和薄弱章节;任何书籍都可导出为 Markdown。长时间编译可暂停并恢复;`deeptutor book health` 和 `refresh-fingerprints` 会标记出已漂移的来源知识。</details>@@ -426,7 +426,7 @@ Book 将选定的来源转化为交互式**活书** — 不是静态 PDF,而<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="创建知识库" width="900"></div>-创建 KB 时,可以选择**新建**(上传文档并构建全新索引)或**链接已有**(复用在其他地方构建的索引,原位读取无需重新索引)。重新索引会写入新的平铺 `version-N` 目录并保留旧版本,因此重建过程中现有索引不会被破坏。即使知识库处于 **error** 状态,也可以单独移除其中一份文档 — 无需完整地删除重建,就能丢弃解析失败的文件。文档解析 — 纯文本、MinerU、Docling、markitdown、PyMuPDF4LLM 或 LiteParse — 在 **Settings → Knowledge Base** 中选择,本地模型下载默认关闭。CLI 通过 `deeptutor kb list`、`info`、`create`、`add`、`search`、`set-default` 和 `delete` 来管理完整生命周期。+创建 KB 时,可以选择**新建**(上传文档并构建全新索引)或**链接已有**(复用在其他地方构建的索引,原位读取无需重新索引)。重新索引会写入新的平铺 `version-N` 目录并保留旧版本,因此重建过程中现有索引不会被破坏。即使知识库处于 **error** 状态,也可以单独移除其中一份文档 — 无需完整地删除重建,就能丢弃解析失败的文件。文档解析 — 纯文本、MinerU、Docling、markitdown、PyMuPDF4LLM 或 LiteParse — 在 **Settings → Knowledge Base** 中选择,本地模型下载默认关闭。Docling 也可以以 **remote** 模式运行,对接 Docling Serve 服务器(无需本地安装或模型),可在 **Settings → Document Parsing** 中配置(`mode=remote`、服务器 Base URL 和可选的 API Key),或通过 `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN` 环境变量配置。CLI 通过 `deeptutor kb list`、`info`、`create`、`add`、`search`、`set-default` 和 `delete` 来管理完整生命周期。</details>diff --git a/assets/README/README_ES.md b/assets/README/README_ES.mdindex 7e7047bff..a97c26470 100644--- a/assets/README/README_ES.md+++ b/assets/README/README_ES.md@@ -421,7 +421,7 @@ Book convierte las fuentes seleccionadas en un **libro vivo** interactivo — no<img src="../../assets/figs/web-1.4.6+/book/03-book-demo%20interactive%20module.png" alt="Bloque de widget interactivo en Book" width="31%"></p>-Cada capítulo se compila en bloques tipados — texto, callouts, quizzes, tarjetas flash, líneas de tiempo, código, figuras, HTML interactivo, animaciones, gráficos de conceptos, profundizaciones y notas de usuario — y cada página tiene su propio Page Chat. Los bloques son editables: inserta, mueve, regenera o cambia el tipo de un bloque sin reescribir el capítulo. Los comandos de mantenimiento como `deeptutor book health` y `deeptutor book refresh-fingerprints` ayudan a detectar cuándo el conocimiento fuente ha divergido de las páginas compiladas.+Cada capítulo se compila en bloques tipados — texto, callouts, quizzes, tarjetas flash, líneas de tiempo, código, figuras, HTML interactivo, animaciones, gráficos de conceptos, profundizaciones y notas de usuario — y cada página tiene su propio Page Chat. Los bloques son editables: inserta, mueve, regenera, reescribe un cuerpo o cambia el tipo sin rehacer el capítulo. Las páginas visitadas, los marcadores y los intentos de quiz se acumulan en una puntuación de finalización y los capítulos débiles; cualquier libro se exporta a Markdown. Una compilación larga se pausa y se reanuda; `deeptutor book health` y `refresh-fingerprints` señalan cuándo el conocimiento fuente ha divergido.</details>@@ -438,7 +438,7 @@ Las bases de conocimiento son las colecciones de documentos detrás del RAG —<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="Crear una base de conocimiento" width="900"></div>-Al crear una KB, puedes **crear nueva** (subir documentos y construir un índice nuevo) o **vincular existente** (reutilizar un índice construido en otro lugar, leer en el lugar sin re-indexar). La re-indexación escribe un nuevo directorio `version-N` plano y conserva los anteriores, de modo que un índice funcional nunca se destruye a mitad de la reconstrucción. Un solo documento puede eliminarse incluso de una base en estado de **error** — descartando un archivo que no se pudo analizar sin necesidad de borrar y reconstruir todo. El análisis de documentos — Text-only, MinerU, Docling, markitdown, PyMuPDF4LLM o LiteParse — se elige en **Settings → Knowledge Base**, con descargas de modelos locales desactivadas por defecto. La CLI refleja el ciclo de vida con `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` y `delete`.+Al crear una KB, puedes **crear nueva** (subir documentos y construir un índice nuevo) o **vincular existente** (reutilizar un índice construido en otro lugar, leer en el lugar sin re-indexar). La re-indexación escribe un nuevo directorio `version-N` plano y conserva los anteriores, de modo que un índice funcional nunca se destruye a mitad de la reconstrucción. Un solo documento puede eliminarse incluso de una base en estado de **error** — descartando un archivo que no se pudo analizar sin necesidad de borrar y reconstruir todo. El análisis de documentos — Text-only, MinerU, Docling, markitdown, PyMuPDF4LLM o LiteParse — se elige en **Settings → Knowledge Base**, con descargas de modelos locales desactivadas por defecto. Docling también puede ejecutarse en modo **remoto** contra un servidor Docling Serve (sin necesidad de instalación local ni modelos), configurado a través de **Settings → Document Parsing** (`mode=remote`, una URL base de servidor y una clave API opcional) o las variables de entorno `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN`. La CLI refleja el ciclo de vida con `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` y `delete`.</details>diff --git a/assets/README/README_FR.md b/assets/README/README_FR.mdindex 9cb095ff3..93bd82108 100644--- a/assets/README/README_FR.md+++ b/assets/README/README_FR.md@@ -431,7 +431,7 @@ Book transforme des sources sélectionnées en un **livre vivant** interactif<img src="../../assets/figs/web-1.4.6+/book/03-book-demo%20interactive%20module.png" alt="Bloc widget interactif du livre" width="31%"></p>-Chaque chapitre se compile en blocs typés — texte, encadrés, quiz, fiches, chronologies, code, figures, HTML interactif, animations, graphes de concepts, approfondissements et notes utilisateur — et chaque page a son propre Chat de Page. Les blocs sont modifiables : insérez, déplacez, régénérez ou changez le type d'un bloc sans réécrire le chapitre. Les commandes de maintenance comme `deeptutor book health` et `deeptutor book refresh-fingerprints` aident à détecter quand les connaissances source ont divergé des pages compilées.+Chaque chapitre se compile en blocs typés — texte, encadrés, quiz, fiches, chronologies, code, figures, HTML interactif, animations, graphes de concepts, approfondissements et notes utilisateur — et chaque page a son propre Chat de Page. Les blocs sont modifiables : insérez, déplacez, régénérez, réécrivez le corps d'un bloc, ou changez son type sans refaire le chapitre. Les pages visitées, les signets et les tentatives de quiz se combinent en un score de complétion et des chapitres faibles ; tout livre s'exporte en Markdown. Une compilation longue se met en pause et reprend ; `deeptutor book health` et `refresh-fingerprints` signalent les connaissances source qui ont divergé.</details>@@ -448,7 +448,7 @@ Les bases de connaissances sont les collections de documents derrière le RAG<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="Créer une base de connaissances" width="900"></div>-En créant une KB, vous choisissez soit de **créer nouvelle** (uploadez des documents et construisez un index frais) soit de **lier une existante** (réutilisez un index construit ailleurs, lu en place sans re-indexation). La re-indexation écrit un nouveau répertoire plat `version-N` et conserve les précédents, donc un index fonctionnel n'est jamais détruit en milieu de reconstruction. Un seul document peut être supprimé même d'une base en état d'**erreur** — retirer un fichier dont l'analyse a échoué sans devoir tout supprimer et reconstruire. L'analyse de documents — Text-only, MinerU, Docling, markitdown, PyMuPDF4LLM ou LiteParse — est choisie dans **Paramètres → Base de Connaissances**, avec les téléchargements de modèles locaux désactivés par défaut. La CLI reprend le cycle de vie avec `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` et `delete`.+En créant une KB, vous choisissez soit de **créer nouvelle** (uploadez des documents et construisez un index frais) soit de **lier une existante** (réutilisez un index construit ailleurs, lu en place sans re-indexation). La re-indexation écrit un nouveau répertoire plat `version-N` et conserve les précédents, donc un index fonctionnel n'est jamais détruit en milieu de reconstruction. Un seul document peut être supprimé même d'une base en état d'**erreur** — retirer un fichier dont l'analyse a échoué sans devoir tout supprimer et reconstruire. L'analyse de documents — Text-only, MinerU, Docling, markitdown, PyMuPDF4LLM ou LiteParse — est choisie dans **Paramètres → Base de Connaissances**, avec les téléchargements de modèles locaux désactivés par défaut. Docling peut aussi fonctionner en mode **distant** contre un serveur Docling Serve (aucune installation ni modèle local nécessaire), configuré via **Paramètres → Analyse de Documents** (`mode=remote`, une URL de base de serveur, et une clé API optionnelle) ou les variables d'environnement `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN`. La CLI reprend le cycle de vie avec `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` et `delete`.</details>diff --git a/assets/README/README_HI.md b/assets/README/README_HI.mdindex 01b385893..61e32f954 100644--- a/assets/README/README_HI.md+++ b/assets/README/README_HI.md@@ -409,7 +409,7 @@ Book selected sources को एक interactive **living book** में बद<img src="../../assets/figs/web-1.4.6+/book/03-book-demo%20interactive%20module.png" alt="Book interactive widget block" width="31%"></p>-हर chapter typed blocks में compile होती है — text, callouts, quizzes, flash cards, timelines, code, figures, interactive HTML, animations, concept graphs, deep dives, और user notes — और हर page का अपना Page Chat है। Blocks editable हैं: chapter rewrite किए बिना किसी block को insert, move, regenerate, या उसका type switch करें। Maintenance commands जैसे `deeptutor book health` और `deeptutor book refresh-fingerprints` तब detect करने में मदद करते हैं जब source knowledge compiled pages से drift हो गया हो।+हर chapter typed blocks में compile होती है — text, callouts, quizzes, flash cards, timelines, code, figures, interactive HTML, animations, concept graphs, deep dives, और user notes — और हर page का अपना Page Chat है। Blocks editable हैं: किसी block को insert, move, regenerate, body rewrite करें, या chapter दोबारा किए बिना उसका type switch करें। Visited pages, bookmarks, और quiz attempts मिलकर एक completion score और weak chapters में roll up होते हैं; कोई भी book Markdown में export होती है। एक लंबी compile pause और resume होती है; `deeptutor book health` और `refresh-fingerprints` उस source knowledge को flag करते हैं जो drift हो गई हो।</details>@@ -426,7 +426,7 @@ Knowledge bases RAG के पीछे document collections हैं — व<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="एक knowledge base बनाएं" width="900"></div>-KB बनाते समय, आप either **नया create** करते हैं (documents upload करें और fresh index build करें) या **existing link** करते हैं (कहीं और बना index reuse करें, re-index के बिना in-place पढ़ें)। Re-indexing एक नई flat `version-N` directory लिखता है और prior ones रखता है, इसलिए एक working index rebuild के दौरान कभी destroy नहीं होता। एक single document को **error**-state base से भी remove किया जा सकता है — पूरी delete-and-rebuild के बिना parse होने में failed हुई file को drop करना। Document parsing — Text-only, MinerU, Docling, markitdown, PyMuPDF4LLM, या LiteParse — **Settings → Knowledge Base** में choose किया जाता है, local model downloads default रूप से off हैं। CLI lifecycle को `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default`, और `delete` से mirror करता है।+KB बनाते समय, आप either **नया create** करते हैं (documents upload करें और fresh index build करें) या **existing link** करते हैं (कहीं और बना index reuse करें, re-index के बिना in-place पढ़ें)। Re-indexing एक नई flat `version-N` directory लिखता है और prior ones रखता है, इसलिए एक working index rebuild के दौरान कभी destroy नहीं होता। एक single document को **error**-state base से भी remove किया जा सकता है — पूरी delete-and-rebuild के बिना parse होने में failed हुई file को drop करना। Document parsing — Text-only, MinerU, Docling, markitdown, PyMuPDF4LLM, या LiteParse — **Settings → Knowledge Base** में choose किया जाता है, local model downloads default रूप से off हैं। Docling को **remote** mode में भी एक Docling Serve server के विरुद्ध चलाया जा सकता है (कोई local install या models की जरूरत नहीं), जिसे **Settings → Document Parsing** (`mode=remote`, एक server base URL, और एक optional API key) या `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN` environment variables के जरिए configure किया जाता है। CLI lifecycle को `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default`, और `delete` से mirror करता है।</details>diff --git a/assets/README/README_JA.md b/assets/README/README_JA.mdindex c367a0049..046823d6d 100644--- a/assets/README/README_JA.md+++ b/assets/README/README_JA.md@@ -409,7 +409,7 @@ Bookは選択したソースをインタラクティブな**生きている本**<img src="../../assets/figs/web-1.4.6+/book/03-book-demo%20interactive%20module.png" alt="Bookインタラクティブウィジェットブロック" width="31%"></p>-各章はタイプ指定されたブロックにコンパイルされます — テキスト、コールアウト、クイズ、フラッシュカード、タイムライン、コード、図、インタラクティブHTML、アニメーション、概念グラフ、詳細解説、ユーザーノート — 各ページには独自のPage Chatがあります。ブロックは編集可能です:章全体を書き直すことなく、挿入、移動、再生成、またはブロックの種類を変更できます。`deeptutor book health`や`deeptutor book refresh-fingerprints`などのメンテナンスコマンドは、ソース知識がコンパイル済みページからドリフトした場合に検出するのに役立ちます。+各章はタイプ指定されたブロックにコンパイルされます — テキスト、コールアウト、クイズ、フラッシュカード、タイムライン、コード、図、インタラクティブHTML、アニメーション、概念グラフ、詳細解説、ユーザーノート — 各ページには独自のPage Chatがあります。ブロックは編集可能です:章をやり直すことなく、挿入、移動、再生成、本文の書き直し、ブロックの種類の変更ができます。訪問したページ、ブックマーク、クイズの受験結果は完了スコアと弱点章に集約され、どの本もMarkdownにエクスポートできます。長時間のコンパイルは一時停止と再開が可能で、`deeptutor book health`と`refresh-fingerprints`はソース知識がドリフトした場合にフラグを立てます。</details>@@ -426,7 +426,7 @@ Bookは選択したソースをインタラクティブな**生きている本**<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="知識ベースの作成" width="900"></div>-KBを作成する際は、**新規作成**(ドキュメントをアップロードして新しいインデックスを構築)または**既存をリンク**(再インデックスなしで既に構築されたインデックスを再利用)を選択します。再インデックスは新しいフラットな`version-N`ディレクトリを書き込み、以前のものを保持するため、再構築中に作業中のインデックスが破壊されることはありません。解析に失敗したファイルを完全な削除・再構築なしで取り除けるよう、**error**状態のベースからでも単一のドキュメントを削除できます。ドキュメント解析(Text-only、MinerU、Docling、markitdown、PyMuPDF4LLM、LiteParse)は**Settings → Knowledge Base**で選択し、ローカルモデルのダウンロードはデフォルトでオフです。CLIは`deeptutor kb list`、`info`、`create`、`add`、`search`、`set-default`、`delete`でライフサイクルをミラーします。+KBを作成する際は、**新規作成**(ドキュメントをアップロードして新しいインデックスを構築)または**既存をリンク**(再インデックスなしで既に構築されたインデックスを再利用)を選択します。再インデックスは新しいフラットな`version-N`ディレクトリを書き込み、以前のものを保持するため、再構築中に作業中のインデックスが破壊されることはありません。解析に失敗したファイルを完全な削除・再構築なしで取り除けるよう、**error**状態のベースからでも単一のドキュメントを削除できます。ドキュメント解析(Text-only、MinerU、Docling、markitdown、PyMuPDF4LLM、LiteParse)は**Settings → Knowledge Base**で選択し、ローカルモデルのダウンロードはデフォルトでオフです。Docling は、Docling Serve サーバーに対して**remote**モードで実行することもできます(ローカルインストールやモデルは不要)。この設定は**Settings → Document Parsing**(`mode=remote`、サーバーのベースURL、オプションのAPIキー)または `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN` 環境変数で行います。CLIは`deeptutor kb list`、`info`、`create`、`add`、`search`、`set-default`、`delete`でライフサイクルをミラーします。</details>diff --git a/assets/README/README_PL.md b/assets/README/README_PL.mdindex 16fdc77cd..816186fe0 100644--- a/assets/README/README_PL.md+++ b/assets/README/README_PL.md@@ -409,7 +409,7 @@ Book zamienia wybrane źródła w interaktywną **żywą książkę** — nie st<img src="../../assets/figs/web-1.4.6+/book/03-book-demo%20interactive%20module.png" alt="Blok interaktywnego widżetu w książce" width="31%"></p>-Każdy rozdział kompiluje się do typowanych bloków — tekst, callouts, quizy, fiszki, osie czasu, kod, figury, interaktywny HTML, animacje, grafy konceptów, dogłębne analizy i notatki użytkownika — a każda strona ma swój własny Page Chat. Bloki są edytowalne: wstawiaj, przenoś, regeneruj lub zmieniaj typ bloku bez przepisywania rozdziału. Polecenia konserwacyjne takie jak `deeptutor book health` i `deeptutor book refresh-fingerprints` pomagają wykryć kiedy wiedza źródłowa odbiega od skompilowanych stron.+Każdy rozdział kompiluje się do typowanych bloków — tekst, callouts, quizy, fiszki, osie czasu, kod, figury, interaktywny HTML, animacje, grafy konceptów, dogłębne analizy i notatki użytkownika — a każda strona ma swój własny Page Chat. Bloki są edytowalne: wstawiaj, przenoś, regeneruj, przepisuj treść lub zmieniaj typ bez ponownego wykonywania rozdziału. Odwiedzone strony, zakładki i próby quizów sumują się w wynik ukończenia i słabe rozdziały; każdą książkę można wyeksportować do Markdown. Długa kompilacja pauzuje się i wznawia; `deeptutor book health` i `refresh-fingerprints` sygnalizują, gdy wiedza źródłowa uległa dryfowi.</details>@@ -426,7 +426,7 @@ Bazy wiedzy to kolekcje dokumentów za RAG — ugruntowują tury Chat, edycje Co<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="Tworzenie bazy wiedzy" width="900"></div>-Tworząc KB, albo **tworzysz nową** (przesyłasz dokumenty i budujesz świeży indeks) albo **łączysz istniejącą** (ponownie używasz indeksu zbudowanego gdzie indziej, czytasz w miejscu bez ponownego indeksowania). Ponowne indeksowanie zapisuje nowy płaski katalog `version-N` i zachowuje poprzednie, więc działający indeks nigdy nie jest niszczony w trakcie przebudowy. Pojedynczy dokument można usunąć nawet z bazy w stanie **błędu** — usuwając plik, który nie sparsował się poprawnie, bez pełnego usuwania i przebudowy. Parsowanie dokumentów — Tylko tekst, MinerU, Docling, markitdown, PyMuPDF4LLM lub LiteParse — jest wybierane w **Settings → Knowledge Base**, z domyślnie wyłączonymi pobieraniami lokalnego modelu. CLI odzwierciedla cykl życia za pomocą `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` i `delete`.+Tworząc KB, albo **tworzysz nową** (przesyłasz dokumenty i budujesz świeży indeks) albo **łączysz istniejącą** (ponownie używasz indeksu zbudowanego gdzie indziej, czytasz w miejscu bez ponownego indeksowania). Ponowne indeksowanie zapisuje nowy płaski katalog `version-N` i zachowuje poprzednie, więc działający indeks nigdy nie jest niszczony w trakcie przebudowy. Pojedynczy dokument można usunąć nawet z bazy w stanie **błędu** — usuwając plik, który nie sparsował się poprawnie, bez pełnego usuwania i przebudowy. Parsowanie dokumentów — Tylko tekst, MinerU, Docling, markitdown, PyMuPDF4LLM lub LiteParse — jest wybierane w **Settings → Knowledge Base**, z domyślnie wyłączonymi pobieraniami lokalnego modelu. Docling może też działać w trybie **zdalnym** względem serwera Docling Serve (bez lokalnej instalacji czy modeli), konfigurowanym przez **Settings → Document Parsing** (`mode=remote`, bazowy URL serwera i opcjonalny klucz API) lub zmienne środowiskowe `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN`. CLI odzwierciedla cykl życia za pomocą `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` i `delete`.</details>diff --git a/assets/README/README_PT.md b/assets/README/README_PT.mdindex bac2f8fbd..124ce790c 100644--- a/assets/README/README_PT.md+++ b/assets/README/README_PT.md@@ -421,7 +421,7 @@ Book converte fontes selecionadas num **livro vivo** interativo — não um PDF<img src="../../assets/figs/web-1.4.6+/book/03-book-demo%20interactive%20module.png" alt="Bloco de widget interativo do Book" width="31%"></p>-Cada capítulo compila em blocos tipados — texto, callouts, quizzes, cartões flash, linhas do tempo, código, figuras, HTML interativo, animações, gráficos de conceitos, mergulhos profundos e notas de utilizador — e cada página tem o seu próprio Page Chat. Os blocos são editáveis: inserir, mover, regenerar ou mudar o tipo de um bloco sem reescrever o capítulo. Os comandos de manutenção como `deeptutor book health` e `deeptutor book refresh-fingerprints` ajudam a detetar quando o conhecimento de origem divergiu das páginas compiladas.+Cada capítulo compila em blocos tipados — texto, callouts, quizzes, cartões flash, linhas do tempo, código, figuras, HTML interativo, animações, gráficos de conceitos, mergulhos profundos e notas de utilizador — e cada página tem o seu próprio Page Chat. Os blocos são editáveis: inserir, mover, regenerar, reescrever um corpo, ou mudar um tipo sem refazer o capítulo. Páginas visitadas, marcadores e tentativas de quiz acumulam-se numa pontuação de conclusão e capítulos fracos; qualquer livro exporta para Markdown. Uma compilação longa pausa e retoma; `deeptutor book health` e `refresh-fingerprints` assinalam conhecimento de origem que divergiu.</details>@@ -438,7 +438,7 @@ As bases de conhecimento são as coleções de documentos por trás do RAG — f<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="Criar uma base de conhecimento" width="900"></div>-Ao criar uma KB, pode **criar nova** (carregar documentos e construir um índice novo) ou **vincular existente** (reutilizar um índice construído noutro lugar, ler no lugar sem reindexação). A reindexação escreve um novo diretório plano `version-N` e mantém os anteriores, pelo que um índice funcional nunca é destruído a meio de uma reconstrução. Um único documento pode ser removido mesmo de uma base em estado de **erro** — descartando um ficheiro que falhou a análise sem uma eliminação e reconstrução completas. A análise de documentos — Somente Texto, MinerU, Docling, markitdown, PyMuPDF4LLM ou LiteParse — é escolhida em **Settings → Knowledge Base**, com downloads de modelos locais desativados por predefinição. A CLI espelha o ciclo de vida com `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` e `delete`.+Ao criar uma KB, pode **criar nova** (carregar documentos e construir um índice novo) ou **vincular existente** (reutilizar um índice construído noutro lugar, ler no lugar sem reindexação). A reindexação escreve um novo diretório plano `version-N` e mantém os anteriores, pelo que um índice funcional nunca é destruído a meio de uma reconstrução. Um único documento pode ser removido mesmo de uma base em estado de **erro** — descartando um ficheiro que falhou a análise sem uma eliminação e reconstrução completas. A análise de documentos — Somente Texto, MinerU, Docling, markitdown, PyMuPDF4LLM ou LiteParse — é escolhida em **Settings → Knowledge Base**, com downloads de modelos locais desativados por predefinição. O Docling também pode correr em modo **remoto** contra um servidor Docling Serve (sem necessidade de instalação local nem de modelos), configurado através de **Settings → Document Parsing** (`mode=remote`, um URL base do servidor e uma chave API opcional) ou das variáveis de ambiente `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN`. A CLI espelha o ciclo de vida com `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` e `delete`.</details>diff --git a/assets/README/README_RU.md b/assets/README/README_RU.mdindex 7d56b82e9..6d8ab286b 100644--- a/assets/README/README_RU.md+++ b/assets/README/README_RU.md@@ -409,7 +409,7 @@ Co-Writer — это разделённое рабочее пространст<img src="../../assets/figs/web-1.4.6+/book/03-book-demo%20interactive%20module.png" alt="Блок интерактивного виджета книги" width="31%"></p>-Каждая глава компилируется в типизированные блоки — текст, выноски, викторины, флэш-карточки, временные шкалы, код, рисунки, интерактивный HTML, анимации, концептуальные графы, углублённые рассуждения и пользовательские заметки — и каждая страница имеет свой собственный чат. Блоки редактируемы: вставляйте, перемещайте, регенерируйте или меняйте тип блока без переписывания главы. Команды обслуживания `deeptutor book health` и `deeptutor book refresh-fingerprints` помогают обнаружить, когда исходные знания расходятся со скомпилированными страницами.+Каждая глава компилируется в типизированные блоки — текст, выноски, викторины, флэш-карточки, временные шкалы, код, рисунки, интерактивный HTML, анимации, концептуальные графы, углублённые рассуждения и пользовательские заметки — и каждая страница имеет свой собственный чат. Блоки редактируемы: вставляйте, перемещайте, регенерируйте, переписывайте содержимое блока или меняйте его тип без переделки главы. Посещённые страницы, закладки и попытки прохождения викторин складываются в оценку завершённости и список слабых глав; любую книгу можно экспортировать в Markdown. Длительная компиляция приостанавливается и возобновляется; `deeptutor book health` и `refresh-fingerprints` отмечают исходные знания, которые разошлись со скомпилированными страницами.</details>@@ -426,7 +426,7 @@ Co-Writer — это разделённое рабочее пространст<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="Создание базы знаний" width="900"></div>-При создании KB вы либо **создаёте новую** (загружаете документы и строите свежий индекс), либо **связываете существующую** (повторно используете индекс, построенный в другом месте, читаете на месте без переиндексирования). Переиндексирование записывает новую плоскую директорию `version-N` и сохраняет предыдущие, поэтому рабочий индекс никогда не уничтожается в процессе перестройки. Отдельный документ можно удалить даже из базы в состоянии **error** — убрав файл, который не удалось разобрать, без полного удаления и пересборки. Разбор документов — только текст, MinerU, Docling, markitdown, PyMuPDF4LLM или LiteParse — выбирается в **Настройки → База знаний**, с отключёнными по умолчанию загрузками локальных моделей. CLI отражает жизненный цикл командами `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` и `delete`.+При создании KB вы либо **создаёте новую** (загружаете документы и строите свежий индекс), либо **связываете существующую** (повторно используете индекс, построенный в другом месте, читаете на месте без переиндексирования). Переиндексирование записывает новую плоскую директорию `version-N` и сохраняет предыдущие, поэтому рабочий индекс никогда не уничтожается в процессе перестройки. Отдельный документ можно удалить даже из базы в состоянии **error** — убрав файл, который не удалось разобрать, без полного удаления и пересборки. Разбор документов — только текст, MinerU, Docling, markitdown, PyMuPDF4LLM или LiteParse — выбирается в **Настройки → База знаний**, с отключёнными по умолчанию загрузками локальных моделей. Docling может также работать в **удалённом режиме**, обращаясь к серверу Docling Serve (без локальной установки и моделей), который настраивается в **Настройки → Разбор документов** (`mode=remote`, базовый URL сервера и необязательный API-ключ) или через переменные окружения `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN`. CLI отражает жизненный цикл командами `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` и `delete`.</details>diff --git a/assets/README/README_TH.md b/assets/README/README_TH.mdindex 08731aa18..aeff66d27 100644--- a/assets/README/README_TH.md+++ b/assets/README/README_TH.md@@ -409,7 +409,7 @@ Book แปลงแหล่งที่มาที่เลือกให้<img src="../../assets/figs/web-1.4.6+/book/03-book-demo%20interactive%20module.png" alt="Book interactive widget block" width="31%"></p>-แต่ละบทคอมไพล์เป็น typed blocks — text, callouts, quizzes, flash cards, timelines, code, figures, interactive HTML, animations, concept graphs, deep dives และ user notes — และทุกหน้ามี Page Chat ของตัวเอง Blocks สามารถแก้ไขได้: แทรก, ย้าย, สร้างใหม่ หรือเปลี่ยนประเภทของ block โดยไม่ต้องเขียนบทใหม่ คำสั่ง maintenance เช่น `deeptutor book health` และ `deeptutor book refresh-fingerprints` ช่วยตรวจจับว่าเมื่อใดที่ความรู้ต้นทางเปลี่ยนแปลงไปจากหน้าที่คอมไพล์แล้ว+แต่ละบทคอมไพล์เป็น typed blocks — text, callouts, quizzes, flash cards, timelines, code, figures, interactive HTML, animations, concept graphs, deep dives และ user notes — และทุกหน้ามี Page Chat ของตัวเอง Blocks สามารถแก้ไขได้: แทรก, ย้าย, สร้างใหม่, เขียนเนื้อหาใหม่ หรือเปลี่ยนประเภท โดยไม่ต้องทำบททั้งบทใหม่ หน้าที่เข้าชมแล้ว, bookmarks และการทำ quiz จะรวมกันเป็นคะแนนความสำเร็จและบทที่ยังอ่อนอยู่ หนังสือเล่มใดก็ export เป็น Markdown ได้ การคอมไพล์ที่ใช้เวลานานจะหยุดพักและทำต่อได้ในภายหลัง; `deeptutor book health` และ `refresh-fingerprints` ช่วยตรวจจับความรู้ต้นทางที่เปลี่ยนแปลงไป</details>@@ -426,7 +426,7 @@ Knowledge bases คือคอลเลกชันเอกสารที่<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="สร้าง knowledge base" width="900"></div>-เมื่อสร้าง KB คุณ **สร้างใหม่** (อัพโหลดเอกสารและสร้าง index ใหม่) หรือ **เชื่อมโยงที่มีอยู่** (นำ index ที่สร้างไว้มาใช้ซ้ำ อ่านในที่โดยไม่ต้อง re-index) การ re-indexing จะเขียน directory `version-N` ใหม่และเก็บอันก่อนหน้าไว้ ดังนั้น index ที่ทำงานอยู่จะไม่ถูกทำลายระหว่างการสร้างใหม่ การแยกวิเคราะห์เอกสาร — Text-only, MinerU, Docling, markitdown, PyMuPDF4LLM หรือ LiteParse — ถูกเลือกใน **Settings → Knowledge Base** โดยการดาวน์โหลด local model ปิดโดยค่าเริ่มต้น CLI ครอบคลุม lifecycle ด้วย `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` และ `delete`+เมื่อสร้าง KB คุณ **สร้างใหม่** (อัพโหลดเอกสารและสร้าง index ใหม่) หรือ **เชื่อมโยงที่มีอยู่** (นำ index ที่สร้างไว้มาใช้ซ้ำ อ่านในที่โดยไม่ต้อง re-index) การ re-indexing จะเขียน directory `version-N` ใหม่และเก็บอันก่อนหน้าไว้ ดังนั้น index ที่ทำงานอยู่จะไม่ถูกทำลายระหว่างการสร้างใหม่ การแยกวิเคราะห์เอกสาร — Text-only, MinerU, Docling, markitdown, PyMuPDF4LLM หรือ LiteParse — ถูกเลือกใน **Settings → Knowledge Base** โดยการดาวน์โหลด local model ปิดโดยค่าเริ่มต้น Docling ยังสามารถรันในโหมด **remote** กับเซิร์ฟเวอร์ Docling Serve ได้ (ไม่ต้องติดตั้ง local หรือใช้ model ใด ๆ) โดยถูกกำหนดค่าผ่าน **Settings → Document Parsing** (`mode=remote`, server base URL และ API key ที่เป็นทางเลือก) หรือผ่าน environment variables `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN` CLI ครอบคลุม lifecycle ด้วย `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` และ `delete`</details>diff --git a/assets/README/README_TW.md b/assets/README/README_TW.mdindex 2ac254572..0be271426 100644--- a/assets/README/README_TW.md+++ b/assets/README/README_TW.md@@ -47,141 +47,6 @@> 🤝 **我們歡迎任何形式的貢獻!** 歡迎在 [`Roadmap`](https://github.com/HKUDS/DeepTutor/issues/498) 為規劃項目投票或提出新構想,並參閱[貢獻指南](../../CONTRIBUTING.md),了解分支策略、程式碼規範與參與方式。-### 📦 發行版本--> **[2026.8.13]** [v1.5.12](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.12) — Web 搜尋以六個新供應商(**Doubao**、**Bocha**、**Zhipu**、**Firecrawl**、**Qianfan**、**Aliyun IQS**)重建,新增 **LiteParse** 解析引擎、會在憑證變更時重新連線的 MCP 伺服器,以及 **CodeBuddy** 與 **OrcaRouter**。--> **[2026.8.10]** [v1.5.11](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.11) — DSML 工具呼叫前後的文字不再消失、遭截斷的回覆會繼續生成而非直接結束、設定中可查看即時記憶體用量,且 LightRAG 索引作業不再阻塞事件迴圈。--> **[2026.8.7]** [v1.5.10](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.10) — 每個帳號都能登入自己的 **Codex**、模型輸出語言成為獨立設定、空白工具呼叫會被拒絕而非重試,且上傳作業不再阻塞事件迴圈。--> **[2026.8.4]** [v1.5.9](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.9) — 透過原生端點使用 Gemini **Embedding 2**、可針對各模型調整 **reasoning effort**、新增 **Novita AI** 閘道,以及查詢的檢索角色與保留完整 `data/` 的 Compose 部署。--<details>-<summary><b>過往發行版本(超過一週)</b></summary>--> **[2026.8.2]** [v1.5.8](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.8) — 記憶體:開發伺服器具備真正的 heap 上限、原始碼安裝會提供正式環境建置、LLM 用戶端與索引快取受到限制,並修正游離 500 錯誤的 keep-alive 問題。--> **[2026.7.31]** [v1.5.7](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.7) — 每個帳號各自擁有 **MCP Services** 商店、導師可執行 101 個 **CLI Apps**、憑證移出沙箱可觸及範圍,並新增行動版版面。--> **[2026.7.29]** [v1.5.6](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.6) — 遠端 **Codex** 登入可透過 SSH 通道完成、產生的檔案在活動面板中有獨立卡片、非英語語言不再一律退回中文,且建立書籍不再逾時。--> **[2026.7.26]** [v1.5.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.5) — 可透過 **OpenAI Codex** OAuth 使用 ChatGPT 方案登入、新增 **Eden AI** 供應商、知識庫會回報所含內容、`rag` 引用可追溯,且 GraphRAG 索引無須因應措施即可運作。--> **[2026.7.24]** [v1.5.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.4) — 維護更新:回答後卡在「產生中」的問題已排除、IM 夥伴能正確呈現 Markdown 表格、LLM JSON 解析更穩健,並修正測驗、建立知識庫表單與 Math Animator。--> **[2026.7.24]** [v1.5.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.3) — 可套用主題的程式碼區塊、My Agents 新增四個程式設計 CLI(Gemini、Kimi、opencode、MiMo)、新增 Atlas Cloud LLM 供應商,並全面提升聊天、記憶、嵌入與解析的可靠性。--> **[2026.7.19]** [v1.5.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.2) — 可設定聊天附件上限、PageIndex 檢索可透過代理程式工具呼叫跨文件推理、更廣泛的 Anthropic/OpenAI 模型支援,以及更穩定的 Book、Knowledge Base 與聊天介面。--> **[2026.7.9]** [v1.5.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.1) — 可從知識庫移除單一失敗文件(即使處於 **error** 狀態),無須刪除並重建整個知識庫。--> **[2026.7.4]** [v1.5.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.0) — LlamaIndex 擷取流程現在會採用你設定的 **Document Parsing** 引擎與多模態影像擷取、Partner 與 Soul ID 對非拉丁字元名稱保持 URL 安全,且選用的 RAG 額外套件可在 Python 3.14+ 正確安裝。--> **[2026.6.30]** [v1.4.15](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.15) — Partners 新增原生 **Mattermost** 頻道,並修正 Guided Learning 選擇題評分與設定為零的區塊重疊值未被採用的問題。--> **[2026.6.29]** [v1.4.14](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.14) — 點選指派的夥伴即可一步開始聊天、Deep Research 會標示不完整報告、LightRAG 無須 MinerU 也能建立索引、FAISS 可處理非 ASCII 路徑,且 PocketBase 工作階段依使用者隔離。--> **[2026.6.27]** [v1.4.13](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.13) — Partners 支援非拉丁字元名稱並可指派給使用者、登入後標誌可正確呈現(#599)、小型知識庫能可靠檢索,且容器可在 rootless Podman 下順利啟動。--> **[2026.6.24]** [v1.4.12](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.12) — 新增 **LightRAG Server** 檢索引擎、輕量 **PyMuPDF4LLM** 解析引擎,以及能大幅加速大型知識庫檢索的 FAISS 向量後端。--> **[2026.6.23]** [v1.4.11](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.11) — 所有雲端 OpenAI 相容供應商皆支援原生工具呼叫、重新設計管理員 Users 頁面、測驗選項支援 LaTeX、工作階段載入指示更如實,且容器主機繫結可設定。--> **[2026.6.21]** [v1.4.10](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.10) — 新增具備頭像的自助式 **Profile** 頁面、單一連接埠請求代理且支援 rootless 的容器指南,以及非管理員預設拒絕使用 MCP 工具。--> **[2026.6.19]** [v1.4.9](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.9) — 設定改善:Search 只顯示供應商需要的欄位、連線設定檔可重新命名或依供應商自動命名,且已評分的 Mastery Path 題目會送入 Question Bank。--> **[2026.6.18]** [v1.4.8](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.8) — 可在 **My Agents** 下連接自己的 **Partners**,並在聊天中即時諮詢;它們會透過各自的角色、知識庫與技能回答,並擁有獨立的私人記憶。--> **[2026.6.18]** [v1.4.7](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.7) — 可連接本機 **Claude Code/Codex** 並在回合中即時諮詢、**My Agents** 升格為頂層 `/agents`,且 Partner 對話新增分支、繼續與刪除功能,並保留可重播的軌跡。--> **[2026.6.17]** [v1.4.6](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.6) — 四大介面整合:Space 學習儀表板可匯入 **My Agents** 並提供頂層 Memory、**Knowledge Center** 支援 GraphRAG/PageIndex/LightRAG/連結知識庫/Obsidian、開放更多設定,且各模型能力具備閘控。--> **[2026.6.14]** [v1.4.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.5) — Guided Learning 以聊天代理程式迴圈重建,針對各主題類型設置嚴格的精熟度門檻並新增 `/learning` 儀表板、引入新的迴圈外掛架構,且 Partner 對話支援 Markdown 匯出與儲存至筆記本。--> **[2026.6.13]** [v1.4.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.4) — 可透過安全閘道從 [ClawHub](https://clawhub.ai/) 安裝社群技能 `deeptutor skill install`,知識庫檔案也支援真正的瀏覽器內 DOCX/XLSX 預覽。--> **[2026.6.12]** [v1.4.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.3) — TutorBot 演進為正式環境等級 IM 管線上的 **Partners**(15 種頻道、即時串流)、Chat 改用單一代理程式迴圈、提供真正的每位使用者隔離,並重建 Visualize。--> **[2026.5.28]** [v1.4.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.2) — 穩定性與細節改善:解除 Visualize 與 Chat 對 Gemini 2.5+ 的限制、修正驗證路由(#485)、改善聊天串流流暢度、加入 Recents 側邊欄,並支援 Lemonade 本機供應商。--> **[2026.5.27]** [v1.4.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.1) — 安全性與穩定性:鎖定 TutorBot 工具沙箱、提供每位使用者資源隔離、多模態影像備援、TutorBot 的 HTTP/SSE API,並修正 v1.4.0 聊天迴歸問題。--> **[2026.5.22]** [v1.4.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.0) — v1.4 正式版:Auto Mode、三層 Memory、代理式 Deep Research/Solve/Question、LlamaIndex RAG 重構、Visualize/Animator 合併,以及重新啟動後仍可恢復的回合執行階段。--> **[2026.5.21]** [v1.4.0-beta](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.0-beta) — 三層 Memory 工作台、所有聊天能力以單一代理式引擎重建、僅使用 LlamaIndex 的 RAG,以及整合的 Settings 與 Capabilities 介面。--> **[2026.5.10]** [v1.3.10](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.10) — 遠端 Docker CORS 復原、SDK 供應商全面支援 `DISABLE_SSL_VERIFY`、更安全的程式碼區塊引用,以及選用的 Matrix E2EE 附加套件。--> **[2026.5.9]** [v1.3.9](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.9) — TutorBot 支援 Zulip 與 NVIDIA NIM、更安全的思考模型路由、`deeptutor start`、側邊欄工具提示,以及工作階段儲存的一致性。--> **[2026.5.8]** [v1.3.8](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.8) — 選用的多使用者部署,具備隔離的使用者工作區、管理員授權、驗證路由與限定範圍的執行階段存取。--> **[2026.5.4]** [v1.3.7](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.7) — 思考模型/供應商修正、可見的 Knowledge 索引記錄,以及更安全的 Co-Writer 清除與範本編輯。--> **[2026.5.3]** [v1.3.6](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.6) — 以型錄為基礎選擇聊天與 TutorBot 模型、更安全的 RAG 重新索引、OpenAI Responses token 上限修正,以及 Skills 編輯器驗證。--> **[2026.5.2]** [v1.3.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.5) — 更順暢的本機啟動設定、更安全的 RAG 查詢、更簡潔的本機 embedding 驗證,以及 Settings 深色模式改善。--> **[2026.5.1]** [v1.3.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.4) — Book 頁面聊天持久化與重建流程、聊天轉書籍引用、更可靠的語言/推理處理,以及 RAG 文件擷取強化。--> **[2026.4.30]** [v1.3.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.3) — 支援 NVIDIA NIM 與 Gemini embedding、統一 Chat 歷程/skills/memory 的 Space 情境、工作階段快照,以及 RAG 重新索引韌性。--> **[2026.4.29]** [v1.3.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.2) — 透明的 embedding 端點 URL、對無效持久化向量提供 RAG 重新索引韌性、清理思考模型輸出的記憶,並修正 Deep Solve 執行階段。--> **[2026.4.28]** [v1.3.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.1) — 穩定性:更安全的 RAG 路由與 embedding 驗證、Docker 持久化、支援輸入法的輸入,以及 Windows/GBK 強化。--> **[2026.4.27]** [v1.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.0) — 具備重新索引流程的版本化知識庫索引、重建 Knowledge 工作區、embedding 自動探索與新轉接器,以及 Space 中心。--> **[2026.4.25]** [v1.2.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.5) — 持久化聊天附件與檔案預覽抽屜、可感知附件的能力管線,以及 TutorBot Markdown 匯出。--> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — 文字/程式碼/SVG 附件、一鍵 Setup Tour、Markdown 聊天匯出,以及精簡的知識庫管理介面。--> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — 文件附件(PDF/DOCX/XLSX/PPTX)、推理思考區塊顯示、Soul 範本編輯器,以及 Co-Writer 儲存至筆記本。--> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — 使用者自訂 Skills 系統、全面改善聊天輸入效能、TutorBot 自動啟動、Book Library 介面,以及視覺化全螢幕。--> **[2026.4.21]** [v1.2.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.1) — 各階段 token 上限、所有入口皆支援 Regenerate 回覆,並修正 RAG 與 Gemma 相容性。--> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — Book Engine「活書」編譯器、多文件 Co-Writer、互動式 HTML 視覺化,以及 Question Bank @ 提及。--> **[2026.4.18]** [v1.1.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.2) — 結構描述驅動的 Channels 分頁、RAG 單一管線整合,以及外部化聊天提示。--> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — 通用「Answer now」、Co-Writer 捲動同步、統一設定面板,以及串流 Stop 按鈕。--> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) — LaTeX 區塊數學全面翻修、LLM 診斷探測,以及 Docker 與本機 LLM 指南。--> **[2026.4.14]** [v1.1.0-beta](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0-beta) — 可加入書籤的工作階段、Snow 主題、WebSocket 心跳與自動重新連線、embedding registry 全面翻修。--> **[2026.4.13]** [v1.0.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.3) — Question Notebook 支援書籤與分類、Visualize 支援 Mermaid、embedding 不相符偵測、Qwen/vLLM 相容性、LM Studio 與 llama.cpp 支援,以及 Glass 主題。--> **[2026.4.11]** [v1.0.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.2) — 整合搜尋並提供 SearXNG 備援、修正供應商切換,以及前端資源洩漏。--> **[2026.4.10]** [v1.0.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.1) — Visualize 能力(Chart.js/SVG)、防止測驗重複,以及支援 o4-mini 模型。--> **[2026.4.10]** [v1.0.0-beta.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.0-beta.4) — embedding 進度追蹤與速率限制重試、跨平台相依性修正,以及 MIME 驗證修正。--> **[2026.4.8]** [v1.0.0-beta.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.0-beta.3) — 原生 OpenAI/Anthropic SDK(移除 litellm)、Windows Math Animator 支援、更穩健的 JSON 解析,以及完整中文國際化。--> **[2026.4.7]** [v1.0.0-beta.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.0-beta.2) — 熱載入設定、MinerU 巢狀輸出、WebSocket 修正,以及 Python 3.11+ 最低版本。--> **[2026.4.4]** [v1.0.0-beta.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.0-beta.1) — 代理程式原生架構重寫(約 20 萬行):Tools+Capabilities 外掛模型、CLI 與 SDK、TutorBot、Co-Writer、Guided Learning,以及持久化記憶。--> **[2026.1.23]** [v0.6.0](https://github.com/HKUDS/DeepTutor/releases/tag/v0.6.0) — 工作階段持久化、增量文件上傳、彈性的 RAG 管線匯入,以及完整中文在地化。--> **[2026.1.18]** [v0.5.2](https://github.com/HKUDS/DeepTutor/releases/tag/v0.5.2) — RAG-Anything 支援 Docling、記錄系統最佳化,以及錯誤修正。--> **[2026.1.15]** [v0.5.0](https://github.com/HKUDS/DeepTutor/releases/tag/v0.5.0) — 統一服務設定、每個知識庫可選 RAG 管線、重新設計問題生成,以及側邊欄自訂。--> **[2026.1.9]** [v0.4.0](https://github.com/HKUDS/DeepTutor/releases/tag/v0.4.0) — 多供應商 LLM 與 embedding 支援、新首頁、RAG 模組解耦,以及環境變數重構。--> **[2026.1.5]** [v0.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v0.3.0) — 統一 PromptManager 架構、GitHub Actions CI/CD,以及 GHCR 預先建置的 Docker 映像檔。--> **[2026.1.2]** [v0.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v0.2.0) — Docker 部署、Next.js 16 與 React 19 升級、WebSocket 安全強化,以及重大弱點修正。--</details>-### 📰 最新消息- **2026-05-22** 🌐 官方文件網站 [**deeptutor.info**](https://deeptutor.info/) 正式上線 — 指南、參考資料與能力導覽集中在同一處。@@ -544,7 +409,7 @@ Book 會將選定來源轉換成互動式**活書**;它不是靜態 PDF,而<img src="../../assets/figs/web-1.4.6+/book/03-book-demo%20interactive%20module.png" alt="Book 互動式元件區塊" width="31%"></p>-每章都會編譯成具型別區塊:文字、提示框、測驗、單字卡、時間軸、程式碼、圖表、互動式 HTML、動畫、概念圖、深入探討與使用者筆記;每一頁也都有自己的 Page Chat。區塊皆可編輯:插入、移動、重新生成或切換區塊型別都不必重寫整章。`deeptutor book health` 與 `deeptutor book refresh-fingerprints` 等維護指令可協助偵測來源知識何時已與編譯後的頁面不同步。+每章都會編譯成具型別區塊:文字、提示框、測驗、單字卡、時間軸、程式碼、圖表、互動式 HTML、動畫、概念圖、深入探討與使用者筆記;每一頁也都有自己的 Page Chat。區塊皆可編輯:插入、移動、重新生成、重寫內文或切換型別,都不必重做整章。已瀏覽頁面、書籤與測驗嘗試會彙整成完成度分數與待加強章節;任何書籍皆可匯出為 Markdown。長時間的編譯可暫停並續行;`deeptutor book health` 與 `refresh-fingerprints` 可標記出已與編譯頁面不同步的來源知識。</details>@@ -561,7 +426,7 @@ Book 會將選定來源轉換成互動式**活書**;它不是靜態 PDF,而<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="建立知識庫" width="900"></div>-建立知識庫時,可以選擇**建立新的知識庫**(上傳文件並建立全新索引),或**連結現有知識庫**(重複使用在其他位置建立的索引、就地讀取且不重新建立索引)。重新建立索引時,系統會寫入新的扁平 `version-N` 目錄並保留先前版本,因此可用索引不會在重建途中遭到破壞。即使知識庫處於 **error** 狀態,也能移除單一文件;可直接刪除解析失敗的檔案,無須刪除並重建全部內容。文件解析方式(Text-only、MinerU、Docling、markitdown 或 PyMuPDF4LLM)可在 **Settings → Knowledge Base** 選擇,預設不下載本機模型。CLI 也提供對應的完整生命週期指令:`deeptutor kb list`、`info`、`create`、`add`、`search`、`set-default` 與 `delete`。+建立知識庫時,可以選擇**建立新的知識庫**(上傳文件並建立全新索引),或**連結現有知識庫**(重複使用在其他位置建立的索引、就地讀取且不重新建立索引)。重新建立索引時,系統會寫入新的扁平 `version-N` 目錄並保留先前版本,因此可用索引不會在重建途中遭到破壞。即使知識庫處於 **error** 狀態,也能移除單一文件;可直接刪除解析失敗的檔案,無須刪除並重建全部內容。文件解析方式(Text-only、MinerU、Docling、markitdown 或 PyMuPDF4LLM)可在 **Settings → Knowledge Base** 選擇,預設不下載本機模型。Docling 也可以在**遠端(remote)**模式下運作,改連線至 Docling Serve 伺服器(無須本機安裝或下載模型),可透過 **Settings → Document Parsing**(設定 `mode=remote`、伺服器基礎 URL 與選用的 API 金鑰)或 `DOCLING_MODE`/`DOCLING_API_BASE_URL`/`DOCLING_API_TOKEN` 環境變數進行設定。CLI 也提供對應的完整生命週期指令:`deeptutor kb list`、`info`、`create`、`add`、`search`、`set-default` 與 `delete`。</details>diff --git a/assets/releases/ver1-5-10.md b/assets/releases/past_releases/ver1-5-10.mdsimilarity index 92%rename from assets/releases/ver1-5-10.mdrename to assets/releases/past_releases/ver1-5-10.mdindex 7d1793fc1..ceffde0ee 100644--- a/assets/releases/ver1-5-10.md+++ b/assets/releases/past_releases/ver1-5-10.md@@ -2,7 +2,7 @@**Release Date:** 2026.08.07-[v1.5.9](past_releases/ver1-5-9.md) was about providers; this one is about the paths underneath them holding up — a batch upload that stalled every other request, a knowledge-base list that rescanned every index, a tool call dispatched with no arguments and retried until the budget ran out. Two things that were quietly missing also land: an account can sign in to its own Codex, and the model's reply language is finally its own setting. Drop-in — no migrations, nothing to re-index.+[v1.5.9](ver1-5-9.md) was about providers; this one is about the paths underneath them holding up — a batch upload that stalled every other request, a knowledge-base list that rescanned every index, a tool call dispatched with no arguments and retried until the budget ran out. Two things that were quietly missing also land: an account can sign in to its own Codex, and the model's reply language is finally its own setting. Drop-in — no migrations, nothing to re-index.## What's Newdiff --git a/assets/releases/ver1-5-11.md b/assets/releases/past_releases/ver1-5-11.mdsimilarity index 100%rename from assets/releases/ver1-5-11.mdrename to assets/releases/past_releases/ver1-5-11.mddiff --git a/assets/releases/ver1-5-12.md b/assets/releases/ver1-5-12.mdindex ff2535c65..f75603543 100644--- a/assets/releases/ver1-5-12.md+++ b/assets/releases/ver1-5-12.md@@ -2,7 +2,7 @@**Release Date:** 2026.08.13-[v1.5.11](ver1-5-11.md) was about what happens while an answer is being written. This one is about where its material comes from. The web-search layer was rebuilt onto a single table — which is how three defects that had been quietly costing you results got found — and six providers were added on top of it, most of them reachable from mainland China. A sixth document-parsing engine lands, and an MCP server whose credential you rotated now reconnects instead of answering with the one explanation that rules out the real cause. Drop-in — no migrations, nothing to re-index.+[v1.5.11](past_releases/ver1-5-11.md) was about what happens while an answer is being written. This one is about where its material comes from. The web-search layer was rebuilt onto a single table — which is how three defects that had been quietly costing you results got found — and six providers were added on top of it, most of them reachable from mainland China. A sixth document-parsing engine lands, and an MCP server whose credential you rotated now reconnects instead of answering with the one explanation that rules out the real cause. Drop-in — no migrations, nothing to re-index.## What's Newdiff --git a/assets/releases/ver1-5-13.md b/assets/releases/ver1-5-13.mdnew file mode 100644index 000000000..3d31b33d8--- /dev/null+++ b/assets/releases/ver1-5-13.md@@ -0,0 +1,58 @@+# DeepTutor v1.5.13 Release Notes++**Release Date:** 2026.08.17++[v1.5.12](ver1-5-12.md) was about where an answer's material comes from. This one is mostly about Book — the surface that turns that material into something you *read* rather than something you chat with. A book could be generated but not really used: the page froze while it was being written, the progress it claimed to track was never written down, and what you got could not leave the app. That gap is the bulk of this release. The home screen also stops asking you to start from a blank composer. Drop-in — no migrations, nothing to re-index.++## What's New++### Watch a book being written, then finish it and take it with you++Compilation outlives the request that started it: `confirm_spine` returns as soon as the page shells exist, while the work it queued runs for minutes. The event bus was owned by that request and closed with it, so every subsequent event was dropped and "watch your book being written" degraded into a frozen page. The stream is now owned per *book* by the process, so it survives the request, a refresh, and a reconnect.++Reading progress is now actually recorded. `visited_page_ids` and `bookmarked_page_ids` had been declared but never written for the life of the feature; visited pages, bookmarks, and quiz attempts now roll up into a completion score and a list of weak chapters.++And a book can leave the app: **export to a self-contained Markdown document**. Every block type gets a text projection, and inherently visual blocks (a rendered animation, an interactive widget) degrade to their description plus a pointer instead of vanishing silently. Non-ASCII titles survive the download — a Chinese or accented book name used to fail the request outright.++### Know what a book costs before you approve it — and don't pay twice++Confirming a spine kicks off dozens of LLM calls and many minutes of work. The editor now shows a live per-chapter estimate derived from the Section Architect's own templates, so the number cannot drift from what actually gets generated, and it stays accurate while you add, remove, or retype chapters.++Two scheduling defects that were invisible in production are fixed: the same page could be compiled twice concurrently — billed twice, one result silently discarded — and a book would grind on through a provider outage until every chapter was half-generated. The source sweep is bounded too. Ungated, eight knowledge bases against a dozen queries fired roughly a hundred concurrent provider calls; the cap is now allocated round-robin, so it isn't spent entirely on the first few bases.++### Connected knowledge bases stop silently contributing nothing++A connected KB — an Obsidian vault, a remote LightRAG or IMA library, a subagent CLI — has no local index, so `rag_search` returns nothing for it. Book generation swept them anyway, and the empty result was indistinguishable from a source with no relevant content: attach your vault, and nothing ever told you it contributed zero. Retrieval now tells indexed bases and connected pointers apart and routes each accordingly.++### Three places to start, drawn from what you were actually doing++The home composer now offers three starter suggestions built from your memory — the L3 synthesis plus your last several activities across surfaces. They propose a specific thing to understand rather than a way to revisit history, and they're sized per language so they don't overflow. A new `recall` memory read backs them, and snapshot stamps are read without loading entity content.++### Mastery paths follow the conversation++A path outlives any one chat, and a chat may work several paths in sequence. Moving a live turn between paths now happens in one place — lease, session preference, and live turn changed together, release before acquire — so a rejected handoff leaves the learner where they were instead of half-moved. Path state and turn recovery are hardened, teaching content stays visible, qualitative reviews are scheduled, and deleting a session cleans up its path.++### Tencent IMA credentials move up to the account++IMA credentials used to live only on each KB. They now also resolve at the account level from **Knowledge → the IMA engine page**, the way PageIndex's key does, with the per-KB pair still winning when it is complete. Existing bindings keep working untouched, and rotating the account key updates every KB that relies on it. Read-only IMA connections and source-text retrieval are fixed alongside.++### Assorted++- **EPUB is a supported knowledge-base format**, and **Docling can parse remotely** against a Docling Serve server (`mode=remote`) with no local install or model downloads.+- **Generated code is parsed before it reaches you.** A truncated snippet used to ship with nothing marking it unchecked.+- **The Overview chapter stays singular.** Re-confirming a spine grew a second one each time, and the page was rebuilt wholesale — the one path that bypassed `edited_by_user` protection. Its wording is also no longer hard-coded to Chinese-or-English while the picker offers eleven languages.+- **Quiz blocks read the question pipeline directly** instead of a legacy facade that discarded progress from the slowest block.+- **Knowledge:** large uploads stream through the web layer, document parsing runs off the event loop, docstore probes are cached and deduped in `kb list`, and GraphRAG model/embedding compatibility is hardened.+- **Partners:** data is isolated per user, an invalid channel config no longer takes the others down, the tool list follows the global chat toggles, and a partner reconnects after its tab goes inactive.+- **Models & providers:** the model catalog and provider transport recover instead of staying broken, catalog secrets are protected in the settings API, GPT-5 agentic tools use the Responses API, provider stream-failure boundaries survive, and completed turn message IDs persist across reconnects.+- **Runtime:** the active virtualenv is visible inside the bwrap sandbox, invalid homes and placeholder OpenAI keys are rejected, Windows `.cmd` shims resolve before a CLI is spawned, console exception tracebacks are preserved, and `mcp` installs by default so the PageIndex MCP server connects.++## Upgrade Notes++`pip install -U deeptutor`; Docker users pull `ghcr.io/hkuds/deeptutor:latest`. No schema changes, no re-index, no migration.++- **Books compiled before this release have no recorded progress.** Completion scores and weak chapters start accumulating from your next read; nothing is backfilled and no existing page is rewritten.+- **A book that was mid-compile when you upgrade should be resumed**, not left. The event stream is now owned per book, so reopening it reattaches to the live compile rather than showing a frozen page.+- **`settings/ima.json` is new** and optional. Existing per-KB IMA credentials keep working exactly as before — the account-level pair only fills in for KBs that don't carry their own.++**Full Changelog**: https://github.com/HKUDS/DeepTutor/compare/v1.5.12...v1.5.13diff --git a/deeptutor/__version__.py b/deeptutor/__version__.pyindex 1e37d1330..a34051a30 100644--- a/deeptutor/__version__.py+++ b/deeptutor/__version__.py@@ -6,6 +6,6 @@ before publishing to PyPI; the web sidebar badge and CLI banner read from thisfile directly."""-__version__ = "1.5.12"+__version__ = "1.5.13"__all__ = ("__version__",)diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.pyindex 2677ed4cc..2c232f5b7 100644--- a/deeptutor/agents/chat/agentic_pipeline.py+++ b/deeptutor/agents/chat/agentic_pipeline.py@@ -863,6 +863,35 @@ class AgenticChatPipeline:trace_id_prefix="chat-loop",)+ async def _notify_pause_hooks(+ self,+ context: UnifiedContext,+ hook_name: str,+ *args: Any,+ **kwargs: Any,+ ) -> None:+ """Tell the active loop capabilities about an ``ask_user`` boundary.++ These hooks record side state (a mastery path commits the question's+ awaiting/answered transitions here) — they do not produce the reply.+ So one failing is a bookkeeping problem, not a reason to throw away a+ turn the learner is in the middle of: log it and keep the conversation+ alive, rather than surfacing a traceback where a question should be.+ """+ for capability in self._active_loop_capabilities(context):+ hook = getattr(capability, hook_name, None)+ if not callable(hook):+ continue+ try:+ await hook(*args, **kwargs)+ except Exception:+ logger.warning(+ "Loop capability %s failed in %s",+ getattr(capability, "name", type(capability).__name__),+ hook_name,+ exc_info=True,+ )+async def _await_user_reply_and_resolve(self,*,@@ -871,10 +900,7 @@ class AgenticChatPipeline:dispatch: DispatchOutcome,) -> bool:ask_user = (dispatch.pause_payload or {}).get("ask_user") or {}- for capability in self._active_loop_capabilities(context):- hook = getattr(capability, "on_user_pause", None)- if callable(hook):- await hook(context, ask_user)+ await self._notify_pause_hooks(context, "on_user_pause", context, ask_user)waiter = context.metadata.get("wait_for_user_reply")if not callable(waiter):await self._emit_terminator_final_response(@@ -891,15 +917,14 @@ class AgenticChatPipeline:if raw_reply is None:return Falsereply_text, answers = _normalise_user_reply(raw_reply)- for capability in self._active_loop_capabilities(context):- hook = getattr(capability, "on_user_resume", None)- if callable(hook):- await hook(- context,- ask_user,- reply_text=reply_text,- answers=answers,- )+ await self._notify_pause_hooks(+ context,+ "on_user_resume",+ context,+ ask_user,+ reply_text=reply_text,+ answers=answers,+ )body_text = _format_user_reply_body(reply_text,answers,diff --git a/deeptutor/api/routers/attachments.py b/deeptutor/api/routers/attachments.pyindex 262b77009..a892fc567 100644--- a/deeptutor/api/routers/attachments.py+++ b/deeptutor/api/routers/attachments.py@@ -19,11 +19,11 @@ from __future__ import annotationsimport loggingimport mimetypes-from urllib.parse import quotefrom fastapi import APIRouter, HTTPExceptionfrom fastapi.responses import FileResponse+from deeptutor.api.utils.http_headers import content_dispositionfrom deeptutor.services.storage import (LocalDiskAttachmentStore,get_attachment_store,@@ -34,19 +34,7 @@ logger = logging.getLogger(__name__)router = APIRouter()-def _content_disposition(filename: str, *, disposition: str = "inline") -> str:- """Build a Content-Disposition header that survives non-ASCII filenames.-- HTTP/1.1 headers are latin-1, so dropping a Chinese / accented filename- straight into ``filename="..."`` blows up with UnicodeEncodeError. RFC- 6266 / RFC 5987 cover this: emit ``filename*=UTF-8''<percent-encoded>``- plus an ASCII fallback on ``filename=`` for legacy clients.- """- ascii_fallback = filename.encode("ascii", errors="replace").decode("ascii")- # Quotes / backslashes break the simple-quoted-string form; collapse them.- ascii_fallback = ascii_fallback.replace('"', "_").replace("\\", "_")- encoded = quote(filename, safe="")- return f"{disposition}; filename=\"{ascii_fallback}\"; filename*=UTF-8''{encoded}"+_content_disposition = content_disposition@router.get("/{session_id}/{attachment_id}/{filename:path}")diff --git a/deeptutor/api/routers/book.py b/deeptutor/api/routers/book.pyindex d7a21c00c..66dc1799e 100644--- a/deeptutor/api/routers/book.py+++ b/deeptutor/api/routers/book.py@@ -12,18 +12,20 @@ import asyncioimport loggingfrom typing import Any-from fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnect+from fastapi import APIRouter, HTTPException, Response, WebSocket, WebSocketDisconnectfrom pydantic import BaseModel, Field+from deeptutor.api.utils.http_headers import content_dispositionfrom deeptutor.book import (BlockType,BookProposal,Spine,get_book_engine,)+from deeptutor.book.estimate import chapter_basis+from deeptutor.book.export import export_filename, render_book_markdownfrom deeptutor.book.models import ContentTypefrom deeptutor.book.streaming import SOURCE as BOOK_SOURCE-from deeptutor.core.stream import StreamEventTypefrom deeptutor.core.stream_bus import StreamBusrouter = APIRouter()@@ -44,6 +46,7 @@ class CreateBookRequest(BaseModel):question_categories: list[int] = Field(default_factory=list)question_entries: list[int] = Field(default_factory=list)language: str = Field(default="en")+ depth: str = Field(default="standard")class ConfirmProposalRequest(BaseModel):@@ -114,8 +117,22 @@ class QuizAttemptRequest(BaseModel):block_id: strquestion_id: str = ""user_answer: str = ""- is_correct: bool = False- request_remediation: bool = False+ # ``None`` = revealed but not graded (a written answer the reader skipped+ # self-assessing). Distinct from ``False``, which means they got it wrong.+ is_correct: bool | None = None+++class UpdateBlockRequest(BaseModel):+ book_id: str+ page_id: str+ block_id: str+ title: str | None = None+ body: str | None = None+++class ProgressRequest(BaseModel):+ book_id: str+ page_id: strclass SupplementRequest(BaseModel):@@ -135,6 +152,10 @@ class RebuildBookRequest(BaseModel):auto_compile: bool = True+class ResumeBookRequest(BaseModel):+ book_id: str++# ─────────────────────────────────────────────────────────────────────────────# REST endpoints# ─────────────────────────────────────────────────────────────────────────────@@ -145,25 +166,77 @@ async def health_check() -> dict[str, str]:return {"status": "healthy", "service": "book"}[email protected]("/estimate-basis")+async def estimate_basis(depth: str = "standard") -> dict[str, Any]:+ """Per-chapter generation cost, keyed by content type.++ The spine editor sums this over whatever chapters currently exist, so the+ estimate stays live while the user edits without a request per keystroke —+ and stays honest, because the numbers come from the same templates the+ architect plans from.+ """+ return {"depth": depth, "basis": chapter_basis(depth)}++@router.get("/books")async def list_books() -> dict[str, Any]:engine = get_book_engine()- return {"books": [b.model_dump(mode="json") for b in engine.list_books()]}++ def _collect() -> list[dict[str, Any]]:+ books: list[dict[str, Any]] = []+ for book in engine.list_books():+ data = book.model_dump(mode="json")+ # Lets the library card say "continue reading" and show how far in+ # the reader is, instead of treating every book as untouched.+ data["reading"] = engine.reading_summary(book)+ books.append(data)+ return books++ # One manifest read per book plus one progress read per book — off-loop.+ return {"books": await asyncio.to_thread(_collect)}+++def _page_summary(page) -> dict[str, Any]:+ """Page metadata without block payloads.++ A compiled page carries its full rendered content — SVG, Mermaid, prose —+ so a book's blocks run to hundreds of kilobytes. Views that only need the+ chapter list (sidebar, library, progress) ask for summaries instead.+ """+ data = page.model_dump(mode="json")+ blocks = data.pop("blocks", []) or []+ data["block_count"] = len(blocks)+ data["blocks"] = []+ return data@router.get("/books/{book_id}")-async def get_book(book_id: str) -> dict[str, Any]:+async def get_book(book_id: str, include_blocks: bool = True) -> dict[str, Any]:engine = get_book_engine()book = engine.load_book(book_id)if book is None:raise HTTPException(status_code=404, detail="Book not found")- spine = engine.load_spine(book_id)- pages = engine.list_pages(book_id)- progress = engine.load_progress(book_id)++ # Opening a book is the correctly-scoped moment to notice that its+ # compilation died with a previous process and pick it back up.+ await engine.maybe_resume_on_open(book_id)+ book = engine.load_book(book_id) or book++ def _read() -> tuple[Any, list[Any], Any]:+ return (+ engine.load_spine(book_id),+ engine.list_pages(book_id),+ engine.load_progress(book_id),+ )++ # A compiled book is hundreds of KB across one file per page.+ spine, pages, progress = await asyncio.to_thread(_read)return {"book": book.model_dump(mode="json"),"spine": spine.model_dump(mode="json") if spine else None,- "pages": [p.model_dump(mode="json") for p in pages],+ "pages": [+ (p.model_dump(mode="json") if include_blocks else _page_summary(p)) for p in pages+ ],"progress": progress.model_dump(mode="json"),}@@ -211,6 +284,7 @@ async def create_book(req: CreateBookRequest) -> dict[str, Any]:question_categories=req.question_categories,question_entries=req.question_entries,language=req.language,+ depth=req.depth,)except Exception as exc: # noqa: BLE001logger.error(f"create_book failed: {exc}", exc_info=True)@@ -412,6 +486,63 @@ async def quiz_attempt(req: QuizAttemptRequest) -> dict[str, Any]:return {"progress": progress.model_dump(mode="json")}[email protected]("/books/update-block")+async def update_block(req: UpdateBlockRequest) -> dict[str, Any]:+ """Edit a block's prose in place.++ Scoped deliberately narrow — title and body only. Fixing a typo shouldn't+ require regenerating a whole block and hoping for a better roll, but a book+ is not a document editor either; substantial rewrites belong in Co-Writer.+ """+ engine = get_book_engine()+ block = await engine.update_block(+ book_id=req.book_id,+ page_id=req.page_id,+ block_id=req.block_id,+ title=req.title,+ body=req.body,+ )+ if block is None:+ raise HTTPException(status_code=404, detail="Block not found or not editable")+ return {"block": block.model_dump(mode="json")}++[email protected]("/books/progress/visit")+async def mark_visited(req: ProgressRequest) -> dict[str, Any]:+ """Remember the reader's position so the book can be resumed later."""+ engine = get_book_engine()+ progress = engine.mark_page_visited(book_id=req.book_id, page_id=req.page_id)+ return {"progress": progress.model_dump(mode="json")}++[email protected]("/books/progress/bookmark")+async def toggle_bookmark(req: ProgressRequest) -> dict[str, Any]:+ engine = get_book_engine()+ progress = engine.toggle_page_bookmark(book_id=req.book_id, page_id=req.page_id)+ return {"progress": progress.model_dump(mode="json")}++[email protected]("/books/{book_id}/export")+async def export_book(book_id: str) -> Response:+ """Download the whole book as a single Markdown file."""+ engine = get_book_engine()+ book = engine.load_book(book_id)+ if book is None:+ raise HTTPException(status_code=404, detail="Book not found")+ markdown = await asyncio.to_thread(+ lambda: render_book_markdown(book, engine.load_spine(book_id), engine.list_pages(book_id))+ )+ return Response(+ content=markdown,+ media_type="text/markdown; charset=utf-8",+ headers={+ "Content-Disposition": content_disposition(+ export_filename(book), disposition="attachment"+ )+ },+ )++@router.get("/books/{book_id}/health")async def book_health(book_id: str) -> dict[str, Any]:engine = get_book_engine()@@ -459,6 +590,20 @@ async def set_page_chat_session(req: PageChatSessionRequest) -> dict[str, Any]:return {"book": book.model_dump(mode="json")}[email protected]("/books/resume")+async def resume_book(req: ResumeBookRequest) -> dict[str, Any]:+ """Re-queue unfinished pages without discarding what already compiled."""+ engine = get_book_engine()+ try:+ pages = await engine.resume_book(book_id=req.book_id)+ except ValueError as exc:+ raise HTTPException(status_code=404, detail=str(exc))+ except Exception as exc: # noqa: BLE001+ logger.error(f"resume_book failed: {exc}", exc_info=True)+ raise HTTPException(status_code=500, detail=str(exc))+ return {"pages": [p.model_dump(mode="json") for p in pages]}++@router.post("/books/rebuild")async def rebuild_book(req: RebuildBookRequest) -> dict[str, Any]:engine = get_book_engine()@@ -487,19 +632,73 @@ def _serialize_event(event) -> dict[str, Any]:}+class _SocketFanout:+ """Forwards several buses into one socket, at most one task per bus.++ A client watching a book needs events from two places: the book's+ long-lived stream (background compilation) and, while a book is still being+ created, a connection-scoped stream (no book id exists yet). Both are+ attached here; neither producer needs to know a socket is listening.++ Attaching is idempotent — re-subscribing to a book already being forwarded+ is a no-op rather than a second, duplicating reader.+ """++ def __init__(self, send) -> None:+ self._send = send+ self._tasks: dict[int, asyncio.Task[None]] = {}++ def attach(self, bus: StreamBus) -> None:+ key = id(bus)+ existing = self._tasks.get(key)+ if existing is not None and not existing.done():+ return+ self._tasks[key] = asyncio.create_task(self._forward(bus))++ async def _forward(self, bus: StreamBus) -> None:+ async for event in bus.subscribe():+ if event.source != BOOK_SOURCE:+ continue+ await self._send(_serialize_event(event))++ async def close(self) -> None:+ for task in self._tasks.values():+ task.cancel()+ for task in self._tasks.values():+ try:+ await task+ except (asyncio.CancelledError, Exception):+ pass+ self._tasks.clear()++@router.websocket("/ws")async def book_websocket(ws: WebSocket) -> None:"""Streaming endpoint.- Client message protocol::+ Two kinds of client message:++ **Subscribe** — attach this socket to a book's long-lived stream. Recent+ history is replayed on attach, so a reader who refreshes mid-compilation+ catches up instead of watching a frozen page::++ {"type": "subscribe", "book_id": "..."}++ **Actions** — run an engine operation and reply with a single result::- {"type": "create", ...CreateBookRequest fields}+ {"type": "create", ...CreateBookRequest fields}{"type": "confirm_proposal", "book_id": "...", "proposal": {...}}{"type": "confirm_spine", "book_id": "...", "spine": {...}, "auto_compile": true}- {"type": "compile_page", "book_id": "...", "page_id": "..."}- {"type": "regenerate_block", "book_id": "...", "page_id": "...", "block_id": "...", "params_override": {}}+ {"type": "compile_page", "book_id": "...", "page_id": "...", "force": false}+ {"type": "regenerate_block", "book_id": "...", "page_id": "...", "block_id": "..."}++ Actions publish into the book's own stream (see :mod:`deeptutor.book.event_hub`),+ so their progress reaches *every* subscriber, and work they leave running in+ the background keeps streaming long after the action has replied. The socket+ only ever closes streams it created itself."""from deeptutor.api.routers.auth import ws_auth_failed, ws_require_auth+ from deeptutor.book.event_hub import get_book_busfrom deeptutor.multi_user.context import reset_current_useruser_token = await ws_require_auth(ws)@@ -518,20 +717,11 @@ async def book_websocket(ws: WebSocket) -> None:except Exception:closed = True- async def stream_into_socket(bus: StreamBus) -> asyncio.Task:- async def _forward() -> None:- async for event in bus.subscribe():- if event.source != BOOK_SOURCE:- continue- await send(_serialize_event(event))- if event.type == StreamEventType.STAGE_END and event.stage in {- "ideation",- "spine",- "compilation",- }:- pass # keep streaming – multiple stages per task-- return asyncio.create_task(_forward())+ fanout = _SocketFanout(send)+ # Book creation has no book id to stream into yet, so ideation events go+ # through a connection-scoped bus. It is the only bus this socket owns.+ creation_bus = StreamBus()+ fanout.attach(creation_bus)try:engine = get_book_engine()@@ -549,11 +739,21 @@ async def book_websocket(ws: WebSocket) -> None:await send({"type": "error", "content": "Missing 'type' field"})continue- bus = StreamBus()- forward_task = await stream_into_socket(bus)+ book_id = str(data.get("book_id") or "").strip()+ if book_id:+ if engine.load_book(book_id) is None:+ await send({"type": "error", "content": f"Book not found: {book_id}"})+ continue+ fanout.attach(get_book_bus(book_id))try:- if msg_type == "create":+ if msg_type == "subscribe":+ if not book_id:+ await send({"type": "error", "content": "subscribe requires book_id"})+ else:+ await send({"type": "subscribed", "book_id": book_id})++ elif msg_type == "create":book, proposal = await engine.create_book(user_intent=str(data.get("user_intent") or ""),chat_session_id=str(data.get("chat_session_id") or ""),@@ -565,8 +765,11 @@ async def book_websocket(ws: WebSocket) -> None:],question_entries=[int(e) for e in (data.get("question_entries") or [])],language=str(data.get("language") or "en"),- stream=bus,+ depth=str(data.get("depth") or "standard"),+ stream=creation_bus,)+ # From here on this book has a stream of its own.+ fanout.attach(get_book_bus(book.id))await send({"type": "create_result",@@ -580,9 +783,8 @@ async def book_websocket(ws: WebSocket) -> None:if data.get("proposal"):edited = BookProposal.model_validate(data["proposal"])book, spine = await engine.confirm_proposal(- book_id=str(data.get("book_id") or ""),+ book_id=book_id,edited_proposal=edited,- stream=bus,)await send({@@ -597,10 +799,9 @@ async def book_websocket(ws: WebSocket) -> None:if data.get("spine"):edited_spine = Spine.model_validate(data["spine"])pages = await engine.confirm_spine(- book_id=str(data.get("book_id") or ""),+ book_id=book_id,edited_spine=edited_spine,auto_compile=bool(data.get("auto_compile", True)),- stream=bus,)await send({@@ -611,9 +812,8 @@ async def book_websocket(ws: WebSocket) -> None:elif msg_type == "compile_page":page = await engine.compile_page(- book_id=str(data.get("book_id") or ""),+ book_id=book_id,page_id=str(data.get("page_id") or ""),- stream=bus,force=bool(data.get("force", False)),)await send(@@ -625,11 +825,10 @@ async def book_websocket(ws: WebSocket) -> None:elif msg_type == "regenerate_block":block = await engine.regenerate_block(- book_id=str(data.get("book_id") or ""),+ book_id=book_id,page_id=str(data.get("page_id") or ""),block_id=str(data.get("block_id") or ""),params_override=data.get("params_override"),- stream=bus,)await send({@@ -644,13 +843,6 @@ async def book_websocket(ws: WebSocket) -> None:except Exception as exc:logger.error(f"book ws action {msg_type} failed: {exc}", exc_info=True)await send({"type": "error", "content": str(exc)})- finally:- await bus.close()- forward_task.cancel()- try:- await forward_task- except (asyncio.CancelledError, Exception):- passexcept WebSocketDisconnect:pass@@ -658,6 +850,8 @@ async def book_websocket(ws: WebSocket) -> None:logger.error(f"Book WS connection error: {exc}", exc_info=True)finally:closed = True+ await fanout.close()+ await creation_bus.close()try:await ws.close()except Exception:diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.pyindex a71cdeaac..6c771987e 100644--- a/deeptutor/api/routers/knowledge.py+++ b/deeptutor/api/routers/knowledge.py@@ -73,7 +73,11 @@ from deeptutor.services.rag.pipelines.ima.client import (ImaClient,ImaRateLimitError,)-from deeptutor.services.rag.pipelines.ima.config import ImaConfig+from deeptutor.services.rag.pipelines.ima.config import (+ ImaConfig,+ ImaCredentials,+ get_account_credentials,+)from deeptutor.utils.document_extractor import (MAX_EXTRACTED_CHARS_PER_DOC,DocumentExtractionError,@@ -1186,6 +1190,62 @@ async def update_pageindex_pipeline_config(payload: PageIndexConfigUpdate):raise HTTPException(status_code=500, detail=str(e))+class ImaConfigUpdate(BaseModel):+ # Same tri-state as PageIndex for the secret half of the pair: omit/None+ # keeps the stored key, "" clears it, any other value replaces it. The+ # Client ID is not a secret and round-trips in the clear.+ client_id: str | None = None+ api_key: str | None = None+++def _ima_config_payload() -> dict:+ """Account-level IMA credential state for the UI, with the key redacted."""+ from deeptutor.services.config import get_runtime_settings_service++ settings = get_runtime_settings_service().load_ima()+ client_id = str(settings.get("client_id") or "")+ api_key_set = bool(settings.get("api_key"))+ return {+ "client_id": client_id,+ "api_key_set": api_key_set,+ "configured": bool(client_id) and api_key_set,+ }++[email protected]("/rag-pipelines/ima/config")+async def get_ima_pipeline_config():+ """Read the account-level IMA credentials (key redacted to a boolean)."""+ try:+ return _ima_config_payload()+ except Exception as e:+ logger.error(f"Error reading IMA config: {e}")+ raise HTTPException(status_code=500, detail=str(e))++[email protected]("/rag-pipelines/ima/config")+async def update_ima_pipeline_config(payload: ImaConfigUpdate):+ """Persist the account-level IMA Client ID / API key."""+ try:+ from deeptutor.services.config import get_runtime_settings_service++ service = get_runtime_settings_service()+ current = service.load_ima(include_process_overrides=False)++ client_id = current.get("client_id", "")+ if payload.client_id is not None:+ client_id = payload.client_id.strip()++ api_key = current.get("api_key", "")+ if payload.api_key is not None:+ api_key = payload.api_key.strip()++ service.save_ima({"client_id": client_id, "api_key": api_key})+ return _ima_config_payload()+ except Exception as e:+ logger.error(f"Error updating IMA config: {e}")+ raise HTTPException(status_code=500, detail=str(e))++class LlamaIndexConfigUpdate(BaseModel):"""Partial update for the LlamaIndex engine knobs (omitted fields kept)."""@@ -1781,8 +1841,10 @@ async def connect_lightrag_server_route(payload: ConnectLightRagServerRequest):class ListImaRequest(BaseModel):- client_id: str- api_key: str+ # Empty means "use the account-level credentials from the engine settings",+ # so the connect flow never has to re-send what is already stored.+ client_id: str = ""+ api_key: str = ""cursor: str = ""limit: int = Field(default=20, ge=1, le=20)@@ -1799,15 +1861,33 @@ class ListImaResponse(BaseModel):is_end: bool+def _resolve_ima_credentials(client_id: str, api_key: str) -> ImaCredentials:+ """A request's credentials, falling back to the account-level pair.++ A request that supplies only one half is not silently completed from the+ account pair: mixing two accounts' halves would fail at IMA with a confusing+ verdict.+ """+ supplied = ImaCredentials(client_id=(client_id or "").strip(), api_key=(api_key or "").strip())+ if supplied.client_id or supplied.api_key:+ return supplied+ return get_account_credentials()++@router.post("/list-ima", response_model=ListImaResponse)async def list_ima_route(payload: ListImaRequest):"""List IMA knowledge bases without storing or echoing credentials."""- client_id = payload.client_id.strip()- api_key = payload.api_key.strip()- if not client_id or not api_key:+ credentials = _resolve_ima_credentials(payload.client_id, payload.api_key)+ if not credentials.complete:raise HTTPException(status_code=400, detail="Client ID and API key are required.")- client = ImaClient(ImaConfig(client_id=client_id, api_key=api_key, knowledge_base_id=""))+ client = ImaClient(+ ImaConfig(+ client_id=credentials.client_id,+ api_key=credentials.api_key,+ knowledge_base_id="",+ )+ )try:return await client.search_knowledge_bases(query="",@@ -1825,15 +1905,15 @@ async def list_ima_route(payload: ListImaRequest):class ProbeImaRequest(BaseModel):- client_id: str- api_key: str+ client_id: str = ""+ api_key: str = ""knowledge_base_id: strclass ConnectImaRequest(BaseModel):name: str- client_id: str- api_key: str+ client_id: str = ""+ api_key: str = ""knowledge_base_id: str@@ -1847,9 +1927,10 @@ async def probe_ima_route(payload: ProbeImaRequest):"""from deeptutor.services.rag.pipelines.ima.probe import probe_knowledge_base+ credentials = _resolve_ima_credentials(payload.client_id, payload.api_key)result = await probe_knowledge_base(- payload.client_id,- payload.api_key,+ credentials.client_id,+ credentials.api_key,payload.knowledge_base_id,)return result.to_dict()@@ -1862,6 +1943,9 @@ async def connect_ima_route(payload: ConnectImaRequest):Re-probes server-side (never trusts the client's verdict), then registers apointer (``type: ima``). Retrieval is offloaded to IMA's ``search_knowledge``OpenAPI — no copy, no local index.++ Credentials the request omits come from the account-level settings and are+ *not* copied onto the KB, so rotating them there keeps this KB working."""from deeptutor.services.rag.pipelines.ima.probe import probe_knowledge_base@@ -1869,9 +1953,14 @@ async def connect_ima_route(payload: ConnectImaRequest):if not name:raise HTTPException(status_code=400, detail="Knowledge base name is required.")+ overrides = ImaCredentials(+ client_id=payload.client_id.strip(),+ api_key=payload.api_key.strip(),+ )+ credentials = _resolve_ima_credentials(payload.client_id, payload.api_key)result = await probe_knowledge_base(- payload.client_id,- payload.api_key,+ credentials.client_id,+ credentials.api_key,payload.knowledge_base_id,)if not result.ok:@@ -1884,8 +1973,8 @@ async def connect_ima_route(payload: ConnectImaRequest):manager = get_kb_manager()entry = manager.register_ima_kb(name,- payload.client_id,- payload.api_key,+ overrides.client_id,+ overrides.api_key,payload.knowledge_base_id,description=result.description or "",)diff --git a/deeptutor/api/routers/mastery_path.py b/deeptutor/api/routers/mastery_path.pyindex 506ef42d9..68c75a3ab 100644--- a/deeptutor/api/routers/mastery_path.py+++ b/deeptutor/api/routers/mastery_path.py@@ -195,6 +195,35 @@ async def get_progress_map(book_id: str):}[email protected]("/progress/{book_id}/objectives/{kp_id}")+async def get_objective_report(book_id: str, kp_id: str):+ """The evidence behind one objective: attempts, schedule, errors, prompts.++ ``policy.objective_report`` is pure over the aggregate, so the questions+ themselves — which live in the durable interaction log, not the aggregate —+ are joined on here, redacted of their answer keys.+ """+ _validate_book_id(book_id)+ store = LearningStore()+ progress = await asyncio.to_thread(store.load, book_id)+ if progress is None:+ raise HTTPException(status_code=404, detail="Progress not found")+ report = learning_policy.objective_report(progress, kp_id)+ if report is None:+ raise HTTPException(status_code=404, detail="Objective not found")++ from deeptutor.learning.pending import public_pending_question++ interactions = await asyncio.to_thread(store.list_interactions, book_id)+ prompts = {+ interaction.interaction_id: public_pending_question(interaction.question).prompt+ for interaction in interactions+ }+ for attempt in report["attempts"]:+ attempt["prompt"] = prompts.get(attempt["question_id"], "")+ return {"book_id": book_id, "path_revision": progress.version, "objective": report}++@router.get("/progress/{book_id}/events")async def get_progress_events(book_id: str, after_revision: int = 0):"""Ordered, redacted domain events for reconnect and incremental UI sync."""@@ -285,6 +314,24 @@ async def delete_progress(book_id: str):return {"status": "ok"}[email protected]("/progress/{book_id}/skip-question")+async def skip_pending_question(book_id: str):+ """Drop an outstanding question the learner can no longer answer.++ The narrow escape hatch for a path stalled on ``answer_pending``; unlike+ ``redo`` it keeps every mastery level and review the learner has earned.+ """+ _validate_book_id(book_id)+ store = LearningStore()+ if not await asyncio.to_thread(store.exists, book_id):+ raise HTTPException(status_code=404, detail="Progress not found")+ async with _exclusive_path_mutation(book_id):+ progress, skipped = await asyncio.to_thread(+ LearningService(store).abandon_active_question, book_id+ )+ return {"status": "ok", "skipped": skipped, "path_revision": progress.version}++@router.post("/progress/{book_id}/redo")async def redo_progress(book_id: str):_validate_book_id(book_id)diff --git a/deeptutor/api/utils/http_headers.py b/deeptutor/api/utils/http_headers.pynew file mode 100644index 000000000..06f5a3596--- /dev/null+++ b/deeptutor/api/utils/http_headers.py@@ -0,0 +1,27 @@+"""Shared HTTP header builders.++Small, boring, and easy to get wrong in ways that only show up for non-English+users — so they live in one place rather than once per router.+"""++from __future__ import annotations++from urllib.parse import quote+++def content_disposition(filename: str, *, disposition: str = "inline") -> str:+ """Build a Content-Disposition header that survives non-ASCII filenames.++ HTTP/1.1 headers are latin-1, so dropping a Chinese / accented filename+ straight into ``filename="..."`` blows up with UnicodeEncodeError. RFC+ 6266 / RFC 5987 cover this: emit ``filename*=UTF-8''<percent-encoded>``+ plus an ASCII fallback on ``filename=`` for legacy clients.+ """+ ascii_fallback = filename.encode("ascii", errors="replace").decode("ascii")+ # Quotes / backslashes break the simple-quoted-string form; collapse them.+ ascii_fallback = ascii_fallback.replace('"', "_").replace("\\", "_")+ encoded = quote(filename, safe="")+ return f"{disposition}; filename=\"{ascii_fallback}\"; filename*=UTF-8''{encoded}"+++__all__ = ["content_disposition"]diff --git a/deeptutor/book/agents/ideation_agent.py b/deeptutor/book/agents/ideation_agent.pyindex 305f38419..149431cb7 100644--- a/deeptutor/book/agents/ideation_agent.py+++ b/deeptutor/book/agents/ideation_agent.py@@ -26,7 +26,11 @@ class IdeationAgent(BaseAgent):base_url: str | None = None,api_version: str | None = None,language: str = "en",- binding: str = "openai",+ # None, not "openai": BaseAgent falls back to the configured+ # provider only when this is falsy. Hard-coding it forced every+ # user onto the OpenAI wire format. Matches the pattern in+ # deeptutor/agents/research/pipeline.py:403.+ binding: str | None = None,) -> None:super().__init__(module_name="book",diff --git a/deeptutor/book/agents/page_planner.py b/deeptutor/book/agents/page_planner.pyindex 782e707cf..500f27f03 100644--- a/deeptutor/book/agents/page_planner.py+++ b/deeptutor/book/agents/page_planner.py@@ -44,6 +44,7 @@ from ..models import (Chapter,ContentType,ExplorationReport,+ depth_scale,)logger = logging.getLogger(__name__)@@ -168,8 +169,17 @@ def _build_block(block_type: BlockType,params: dict[str, Any],chapter: Chapter,+ *,+ depth: str | None = None,) -> Block:transition_in = params.pop("transition_in", "")+ # Every plan — static template or LLM-authored — funnels through here, so+ # this is the single place the reader's brief/standard/deep choice has to+ # be applied. Templates used to hard-code ~3,600 words per chapter for+ # everyone.+ target = params.get("target_words")+ if isinstance(target, (int, float)):+ params["target_words"] = max(120, round(float(target) * depth_scale(depth)))full_params: dict[str, Any] = {"chapter_title": chapter.title,"chapter_summary": chapter.summary,@@ -192,9 +202,10 @@ def _static_plan(chapter: Chapter,*,phase: int,+ depth: str | None = None,) -> list[Block]:template = _TEMPLATES_V2.get(chapter.content_type) or _TEMPLATES_V2[ContentType.THEORY]- return [_build_block(bt, dict(params), chapter) for bt, params in template]+ return [_build_block(bt, dict(params), chapter, depth=depth) for bt, params in template]# ─────────────────────────────────────────────────────────────────────────────@@ -269,9 +280,9 @@ class SectionArchitect:self.llm_enabled = llm_enabled# ── Sync (legacy) ────────────────────────────────────────────────- def plan_blocks(self, chapter: Chapter) -> list[Block]:+ def plan_blocks(self, chapter: Chapter, *, depth: str | None = None) -> list[Block]:"""Static-template plan. Always succeeds."""- return _static_plan(chapter, phase=self.phase)+ return _static_plan(chapter, phase=self.phase, depth=depth)# ── Async (LLM-first) ────────────────────────────────────────────async def plan_blocks_async(@@ -280,9 +291,10 @@ class SectionArchitect:*,exploration: ExplorationReport | None = None,language: str = "en",+ depth: str | None = None,) -> list[Block]:if not self.llm_enabled:- return self.plan_blocks(chapter)+ return self.plan_blocks(chapter, depth=depth)try:system_prompt, user_template = _architect_prompts(language)@@ -301,15 +313,15 @@ class SectionArchitect:)except Exception as exc:logger.warning(f"SectionArchitect LLM failed → fallback static: {exc}")- return self.plan_blocks(chapter)+ return self.plan_blocks(chapter, depth=depth)payload = parse_json_response(raw, logger_instance=logger, fallback={})if not isinstance(payload, dict):- return self.plan_blocks(chapter)+ return self.plan_blocks(chapter, depth=depth)items = payload.get("blocks")if not isinstance(items, list) or not items:- return self.plan_blocks(chapter)+ return self.plan_blocks(chapter, depth=depth)blocks: list[Block] = []for raw_item in items[:12]:@@ -328,10 +340,10 @@ class SectionArchitect:params["transition_in"] = str(raw_item["transition_in"])[:240]if raw_item.get("focus"):params["focus"] = str(raw_item["focus"])[:240]- blocks.append(_build_block(block_type, params, chapter))+ blocks.append(_build_block(block_type, params, chapter, depth=depth))if not blocks:- return self.plan_blocks(chapter)+ return self.plan_blocks(chapter, depth=depth)# Coverage guarantee: ensure at least one SECTION block, otherwise we# silently lose chapter prose. Inject one at the front if missing.@@ -342,6 +354,7 @@ class SectionArchitect:BlockType.SECTION,{"role": "core", "target_words": 1700},chapter,+ depth=depth,),)diff --git a/deeptutor/book/agents/source_explorer.py b/deeptutor/book/agents/source_explorer.pyindex 5c039b17d..45de2669c 100644--- a/deeptutor/book/agents/source_explorer.py+++ b/deeptutor/book/agents/source_explorer.py@@ -45,6 +45,54 @@ from ..models import (logger = logging.getLogger(__name__)+# The sweep runs one retrieval per (knowledge base x query) pair, and each is a+# vector search plus — on most backends — an LLM synthesis call. Left ungated,+# eight KBs against a dozen queries fired ~100 concurrent provider calls.+RETRIEVAL_CONCURRENCY = 6+MAX_RETRIEVAL_CALLS = 48+++def _balanced_slice(chunks: list[SourceChunk], *, limit: int) -> list[SourceChunk]:+ """Pick ``limit`` chunks with every source represented.++ Ranking is only meaningful *within* one engine, so we rank inside each+ source and then take round-robin across them. A global sort by ``score``+ handed the whole slice to whichever backend happened to emit the largest+ numbers, which silently dropped notebooks, chat excerpts and any KB on a+ different scoring scale out of the synthesis input entirely.+ """+ if len(chunks) <= limit:+ return list(chunks)++ by_source: dict[str, list[SourceChunk]] = {}+ for chunk in chunks:+ by_source.setdefault(f"{chunk.source}/{chunk.kb_name or ''}", []).append(chunk)+ for group in by_source.values():+ group.sort(key=lambda c: -c.score)++ picked: list[SourceChunk] = []+ groups = list(by_source.values())+ depth = 0+ while len(picked) < limit and any(depth < len(g) for g in groups):+ for group in groups:+ if depth < len(group):+ picked.append(group[depth])+ if len(picked) == limit:+ break+ depth += 1+ return picked+++# Retrieval queries should follow the *sources*, not the book. Say so explicitly+# rather than leaving the model to guess from the prompt's own language.+_QUERY_LANGUAGE_HINT = (+ "\n\n[Query language] Write each query in the language the source material is "+ "most likely written in — usually the language of the user's intent or the "+ "knowledge base itself. Where a concept has a widely used English term "+ "(model names, algorithms, APIs), include it verbatim. These queries are "+ "matched against documents, never shown to the reader."+)+def _clip(text: str, limit: int) -> str:text = (text or "").strip()@@ -103,7 +151,11 @@ class SourceExplorer(BaseAgent):base_url: str | None = None,api_version: str | None = None,language: str = "en",- binding: str = "openai",+ # None, not "openai": BaseAgent falls back to the configured+ # provider only when this is falsy. Hard-coding it forced every+ # user onto the OpenAI wire format. Matches the pattern in+ # deeptutor/agents/research/pipeline.py:403.+ binding: str | None = None,*,max_queries: int = 8,chunks_per_query: int = 4,@@ -118,6 +170,7 @@ class SourceExplorer(BaseAgent):binding=binding,)self.max_queries = max_queries+ self.skipped_knowledge_bases: list[str] = []self.chunks_per_query = chunks_per_query# ------------------------------------------------------------------ #@@ -164,6 +217,16 @@ class SourceExplorer(BaseAgent):coverage=coverage,)+ # Connected KBs contributed nothing because nothing could read them.+ # Say so in the report rather than letting an empty contribution look+ # like a source with no relevant content.+ if self.skipped_knowledge_bases:+ notes = [+ *notes,+ "Not swept (no local index — these need their own capability): "+ + ", ".join(self.skipped_knowledge_bases),+ ]+return ExplorationReport(book_id=book_id,queries=queries,@@ -184,10 +247,12 @@ class SourceExplorer(BaseAgent):proposal: BookProposal,inputs: BookInputs,) -> list[str]:- from ..blocks._language import language_directive-system_prompt = self.get_prompt("queries_system") or _FALLBACK_QUERIES_SYSTEM- system_prompt = system_prompt.rstrip() + language_directive(self.language)+ # Deliberately no language directive here. These strings are matched+ # against document text, not shown to anyone: pinning them to the book's+ # language starves retrieval whenever the sources are written in a+ # different one. The summary below *is* reader-facing and does get it.+ system_prompt = system_prompt.rstrip() + _QUERY_LANGUAGE_HINTuser_template = self.get_prompt("queries_user") or _FALLBACK_QUERIES_USERintent = (inputs.user_intent or proposal.description or "").strip() or "(empty)"@@ -264,6 +329,31 @@ class SourceExplorer(BaseAgent):# Step 2 — parallel RAG retrieval# ------------------------------------------------------------------ #+ @staticmethod+ def partition_knowledge_bases(kb_list: list[str]) -> tuple[list[str], list[str]]:+ """Split *kb_list* into (retrievable, connected).++ Connected KBs are pointers — an Obsidian vault, a subagent CLI, a remote+ LightRAG or IMA library — with no local index for ``rag_search`` to hit.+ Sweeping them anyway returned nothing and looked identical to a source+ that simply had no relevant content, so the reader never learned their+ vault contributed zero. Reaching them properly means driving each+ capability, which is a separate piece of work; naming them is the+ honest interim.+ """+ retrievable: list[str] = []+ connected: list[str] = []+ for kb in kb_list:+ try:+ from deeptutor.knowledge.kb_types import is_connected_kb+ from deeptutor.multi_user.knowledge_access import resolve_kb_metadata++ meta = resolve_kb_metadata(kb)+ except Exception: # noqa: BLE001 - unresolvable → treat as ordinary+ meta = None+ (connected if meta and is_connected_kb(meta) else retrievable).append(kb)+ return retrievable, connected+async def _retrieve_kb_chunks(self,queries: list[str],@@ -275,6 +365,15 @@ class SourceExplorer(BaseAgent):logger.warning(f"rag_tool unavailable: {exc}")return []+ kb_list, connected = self.partition_knowledge_bases(kb_list)+ if connected:+ self.skipped_knowledge_bases = list(connected)+ logger.info(+ "source exploration skipped %d connected KB(s) with no local index: %s",+ len(connected),+ ", ".join(connected),+ )+async def _one_query(kb: str, query: str) -> list[SourceChunk]:try:result = await rag_search(query=query, kb_name=kb)@@ -333,10 +432,34 @@ class SourceExplorer(BaseAgent):)return out- coros = [_one_query(kb, q) for kb in kb_list for q in queries]- if not coros:+ # Query-major, not KB-major: the pair list gets trimmed below, and+ # trimming a KB-major list would starve the last knowledge bases of+ # every query. Interleaving keeps coverage even when the budget bites.+ pairs = [(kb, q) for q in queries for kb in kb_list]+ if not pairs:return []- gathered = await asyncio.gather(*coros, return_exceptions=False)++ dropped = 0+ if len(pairs) > MAX_RETRIEVAL_CALLS:+ dropped = len(pairs) - MAX_RETRIEVAL_CALLS+ pairs = pairs[:MAX_RETRIEVAL_CALLS]+ logger.info(+ f"source exploration capped at {MAX_RETRIEVAL_CALLS} retrievals "+ f"({len(kb_list)} KBs x {len(queries)} queries); {dropped} skipped"+ )++ # Every pair is a retrieval plus, on most backends, an LLM synthesis+ # call. Firing all of them at once trips provider rate limits and+ # spikes memory; a gate keeps the sweep fast without the stampede.+ gate = asyncio.Semaphore(RETRIEVAL_CONCURRENCY)++ async def _guarded(kb: str, query: str) -> list[SourceChunk]:+ async with gate:+ return await _one_query(kb, query)++ gathered = await asyncio.gather(+ *(_guarded(kb, q) for kb, q in pairs), return_exceptions=False+ )chunks: list[SourceChunk] = []for batch in gathered:chunks.extend(batch)@@ -440,8 +563,11 @@ class SourceExplorer(BaseAgent):system_prompt = system_prompt.rstrip() + language_directive(self.language)user_template = self.get_prompt("summary_user") or _FALLBACK_SUMMARY_USER- # Send only the most informative slice to the synthesiser.- slice_chunks = sorted(chunks, key=lambda c: -c.score)[:24]+ # Send only the most informative slice to the synthesiser — but pick it+ # per source, not by a global sort. Scores come from different engines+ # (cosine, BM25, a remote service's own scale) and are not comparable,+ # so ranking them together let one KB's numbers crowd out every other.+ slice_chunks = _balanced_slice(chunks, limit=24)chunks_block = "\n".join(f"- [{c.source}/{c.kb_name or 'n/a'}] (q={c.query!r}) {_clip(c.text, 320)}"for c in slice_chunksdiff --git a/deeptutor/book/agents/spine_agent.py b/deeptutor/book/agents/spine_agent.pyindex 0fcdf1c82..51848c79b 100644--- a/deeptutor/book/agents/spine_agent.py+++ b/deeptutor/book/agents/spine_agent.py@@ -33,7 +33,11 @@ class SpineAgent(BaseAgent):base_url: str | None = None,api_version: str | None = None,language: str = "en",- binding: str = "openai",+ # None, not "openai": BaseAgent falls back to the configured+ # provider only when this is falsy. Hard-coding it forced every+ # user onto the OpenAI wire format. Matches the pattern in+ # deeptutor/agents/research/pipeline.py:403.+ binding: str | None = None,) -> None:super().__init__(module_name="book",diff --git a/deeptutor/book/agents/spine_synthesizer.py b/deeptutor/book/agents/spine_synthesizer.pyindex fd8619254..4d0d7810f 100644--- a/deeptutor/book/agents/spine_synthesizer.py+++ b/deeptutor/book/agents/spine_synthesizer.py@@ -88,7 +88,11 @@ class SpineSynthesizer(BaseAgent):base_url: str | None = None,api_version: str | None = None,language: str = "en",- binding: str = "openai",+ # None, not "openai": BaseAgent falls back to the configured+ # provider only when this is falsy. Hard-coding it forced every+ # user onto the OpenAI wire format. Matches the pattern in+ # deeptutor/agents/research/pipeline.py:403.+ binding: str | None = None,*,max_rounds: int = 2,) -> None:diff --git a/deeptutor/book/blocks/_rag_helpers.py b/deeptutor/book/blocks/_rag_helpers.pyindex b711fc72d..a7428e963 100644--- a/deeptutor/book/blocks/_rag_helpers.py+++ b/deeptutor/book/blocks/_rag_helpers.py@@ -98,6 +98,19 @@ async def optional_rag_lookup(*, query: str, ctx) -> RagLookup:if not isinstance(result, dict):return RagLookup()+ # RAGService reports failure in-band: it fills `answer` with an error+ # message ("RAG search failed.", "needs re-index", …) and flags it with+ # `error_type` / `needs_reindex`. Reading `answer` unconditionally fed that+ # message into the generator as if it were retrieved evidence, so a broken+ # index quietly became source material in the finished book.+ if result.get("error_type") or result.get("needs_reindex"):+ logger.debug(+ f"RAG lookup unusable ({ctx.primary_kb}): "+ f"error_type={result.get('error_type')!r} "+ f"needs_reindex={bool(result.get('needs_reindex'))}"+ )+ return RagLookup()+answer = str(result.get("answer") or result.get("content") or "").strip()sources = result.get("sources")return RagLookup(diff --git a/deeptutor/book/blocks/animation.py b/deeptutor/book/blocks/animation.pyindex c132f9eb3..6e41de15a 100644--- a/deeptutor/book/blocks/animation.py+++ b/deeptutor/book/blocks/animation.py@@ -16,6 +16,7 @@ import loggingfrom typing import Anyfrom ..models import BlockType, SourceAnchor+from ._prompts import get_book_prompt, load_book_promptsfrom .base import BlockContext, BlockGenerator, GenerationFailurelogger = logging.getLogger(__name__)@@ -41,21 +42,28 @@ class AnimationGenerator(BlockGenerator):focus = str(params.get("focus") or "")quality = str(params.get("quality") or "medium")style_hint = str(params.get("style_hint") or "")+ prompts = load_book_prompts("animation", ctx.language)history_lines: list[str] = []if chapter_summary:- history_lines.append(f"Chapter summary: {chapter_summary}")+ history_lines.append(+ get_book_prompt(prompts, "context_summary")+ .strip()+ .format(chapter_summary=chapter_summary)+ )if objectives:- history_lines.append("Learning objectives:")+ history_lines.append(get_book_prompt(prompts, "context_objectives").strip())for obj in objectives:history_lines.append(f"- {obj}")history_context = "\n".join(history_lines)- focus_clause = f" focusing on {focus}" if focus else ""+ focus_clause = (+ get_book_prompt(prompts, "focus_clause").rstrip().format(focus=focus) if focus else ""+ )user_input = (- f"Create a short Manim animation that walks through the core "- f'derivation of "{chapter_title}"{focus_clause}. Aim for a '- "clear, step-by-step explanation a learner can follow."+ get_book_prompt(prompts, "brief")+ .strip()+ .format(chapter_title=chapter_title, focus_clause=focus_clause))try:diff --git a/deeptutor/book/blocks/code.py b/deeptutor/book/blocks/code.pyindex d2da71522..3b15f7ee2 100644--- a/deeptutor/book/blocks/code.py+++ b/deeptutor/book/blocks/code.py@@ -18,6 +18,47 @@ from ._prompts import get_book_prompt, load_book_promptsfrom .base import BlockContext, BlockGenerator, GenerationFailure+def _check_python(code: str) -> str | None:+ import ast++ try:+ ast.parse(code)+ except SyntaxError as exc:+ return f"line {exc.lineno}: {exc.msg}"+ return None+++def _check_json(code: str) -> str | None:+ import json++ try:+ json.loads(code)+ except ValueError as exc:+ return str(exc)+ return None+++# Languages we can validate for free, in-process, with no side effects. Parsing+# only — never execution: a generated snippet may open files or hit the network,+# and the point is to catch truncation and malformed output, not to run it.+_CHECKABLE = {+ "python": _check_python,+ "py": _check_python,+ "json": _check_json,+}+++def _syntax_error(code: str, language: str) -> str | None:+ """Return a human-readable syntax error, or None if it parses / is unchecked."""+ checker = _CHECKABLE.get((language or "").strip().lower())+ if checker is None:+ return None+ try:+ return checker(code)+ except Exception: # noqa: BLE001 - a checker must never break generation+ return None++class CodeGenerator(BlockGenerator):block_type = BlockType.CODE@@ -53,15 +94,25 @@ class CodeGenerator(BlockGenerator):raise GenerationFailure("LLM did not return any code.")if "<think" in code.lower() or "</think" in code.lower():raise GenerationFailure("prompt leak detected in generated code.")++ code_language = str(data.get("language") or language).strip() or language+ syntax_error = _syntax_error(code, code_language)+ if syntax_error:+ # A truncated or malformed snippet is worse than none: the reader+ # copies it, it fails, and nothing said it was never checked. Fail+ # the block so the compiler's retry path gets a second attempt.+ raise GenerationFailure(f"generated code does not parse: {syntax_error}")++ metadata = data.get("_metadata") if isinstance(data.get("_metadata"), dict) else {}return ({- "language": str(data.get("language") or language).strip() or language,+ "language": code_language,"code": code,"explanation": str(data.get("explanation") or "").strip(),"intent": intent,},[],- data.get("_metadata") if isinstance(data.get("_metadata"), dict) else {},+ {**metadata, "syntax_checked": _CHECKABLE.get(code_language.lower()) is not None},)diff --git a/deeptutor/book/blocks/figure.py b/deeptutor/book/blocks/figure.pyindex 4aec7740c..c7d89bd90 100644--- a/deeptutor/book/blocks/figure.py+++ b/deeptutor/book/blocks/figure.py@@ -17,6 +17,7 @@ import loggingfrom typing import Anyfrom ..models import BlockType, SourceAnchor+from ._prompts import get_book_prompt, load_book_promptsfrom .base import BlockContext, BlockGenerator, GenerationFailurelogger = logging.getLogger(__name__)@@ -34,21 +35,32 @@ class FigureGenerator(BlockGenerator):objectives = params.get("objectives") or ctx.chapter.learning_objectivesvariant = str(params.get("variant") or "diagram")focus = str(params.get("focus") or "")+ prompts = load_book_prompts("figure", ctx.language)history_lines: list[str] = []if chapter_summary:- history_lines.append(f"Chapter summary: {chapter_summary}")+ history_lines.append(+ get_book_prompt(prompts, "context_summary")+ .strip()+ .format(chapter_summary=chapter_summary)+ )if objectives:- history_lines.append("Learning objectives:")+ history_lines.append(get_book_prompt(prompts, "context_objectives").strip())for obj in objectives:history_lines.append(f"- {obj}")history_context = "\n".join(history_lines)- focus_clause = f" focusing on {focus}" if focus else ""+ focus_clause = (+ get_book_prompt(prompts, "focus_clause").rstrip().format(focus=focus) if focus else ""+ )user_input = (- f"Create a {variant} figure for the chapter "- f'"{chapter_title}"{focus_clause}. The figure should help a '- "learner build intuition about the core relationships covered above."+ get_book_prompt(prompts, "brief")+ .strip()+ .format(+ variant=variant,+ chapter_title=chapter_title,+ focus_clause=focus_clause,+ ))try:diff --git a/deeptutor/book/blocks/interactive.py b/deeptutor/book/blocks/interactive.pyindex c0e98e245..be11612e3 100644--- a/deeptutor/book/blocks/interactive.py+++ b/deeptutor/book/blocks/interactive.py@@ -17,6 +17,7 @@ import loggingfrom typing import Anyfrom ..models import BlockType, SourceAnchor+from ._prompts import get_book_prompt, load_book_promptsfrom .base import BlockContext, BlockGenerator, GenerationFailurelogger = logging.getLogger(__name__)@@ -34,22 +35,32 @@ class InteractiveGenerator(BlockGenerator):objectives = params.get("objectives") or ctx.chapter.learning_objectivesfocus = str(params.get("focus") or "")interaction = str(params.get("interaction") or "interactive")+ prompts = load_book_prompts("interactive", ctx.language)history_lines: list[str] = []if chapter_summary:- history_lines.append(f"Chapter summary: {chapter_summary}")+ history_lines.append(+ get_book_prompt(prompts, "context_summary")+ .strip()+ .format(chapter_summary=chapter_summary)+ )if objectives:- history_lines.append("Learning objectives:")+ history_lines.append(get_book_prompt(prompts, "context_objectives").strip())for obj in objectives:history_lines.append(f"- {obj}")history_context = "\n".join(history_lines)- focus_clause = f" focusing on {focus}" if focus else ""+ focus_clause = (+ get_book_prompt(prompts, "focus_clause").rstrip().format(focus=focus) if focus else ""+ )user_input = (- f"Build an {interaction} HTML page for the chapter "- f'"{chapter_title}"{focus_clause}. The page should let the learner '- "manipulate state, drag/click controls, or step through a guided "- "demo to internalise the concept."+ get_book_prompt(prompts, "brief")+ .strip()+ .format(+ interaction=interaction,+ chapter_title=chapter_title,+ focus_clause=focus_clause,+ ))try:diff --git a/deeptutor/book/blocks/quiz.py b/deeptutor/book/blocks/quiz.pyindex 197f1409a..f24d78dba 100644--- a/deeptutor/book/blocks/quiz.py+++ b/deeptutor/book/blocks/quiz.py@@ -33,20 +33,36 @@ class QuizGenerator(BlockGenerator):topic = f"{topic}\n\n[Chapter context: {extra_context}]"question_types = [question_type] if question_type else []+ # Straight to QuestionPipeline. AgentCoordinator is a documented legacy+ # facade ("New code should prefer ... QuestionPipeline directly") kept+ # for older WebSocket routes, and going through it cost us something+ # real: it builds a throwaway StreamBus, so every progress event from+ # the slowest block in the book was discarded. Publishing to the book's+ # own stream means the reader sees the quiz being written.try:- from deeptutor.agents.question.coordinator import AgentCoordinator+ from deeptutor.agents.question.pipeline import QuestionPipeline+ from deeptutor.core.context import UnifiedContext- coordinator = AgentCoordinator(- kb_name=ctx.primary_kb,- language=ctx.language,- enable_idea_rag=ctx.rag_enabled and bool(ctx.primary_kb),- )- summary = await coordinator.generate_from_topic(- user_topic=topic,- num_questions=num_questions,+ from ..event_hub import get_book_bus++ # Mirrors the facade's `_active_kb_name`: no KB when RAG is off.+ effective_kb = ctx.primary_kb if (ctx.rag_enabled and ctx.primary_kb) else None+ pipeline = QuestionPipeline(language=ctx.language, kb_name=effective_kb)+ result = await pipeline.run(+ context=UnifiedContext(+ session_id=f"book-{ctx.book_id}",+ user_message=topic,+ active_capability="deep_question",+ knowledge_bases=[effective_kb] if effective_kb else [],+ language=ctx.language,+ ),+ user_message=topic,+ num_questions=max(1, int(num_questions or 1)),difficulty=difficulty,question_types=question_types,+ stream=get_book_bus(ctx.book_id),)+ summary = dict(result.get("summary") or {})except Exception as exc:logger.warning(f"QuizGenerator failed: {exc}", exc_info=True)raise GenerationFailure(f"quiz generation failed: {exc}") from exc@@ -72,8 +88,18 @@ class QuizGenerator(BlockGenerator):return []out: list[dict[str, Any]] = []for item in results:- if not isinstance(item, dict) or not item.get("success"):+ if not isinstance(item, dict):continue+ # The legacy facade derived `success` from the absence of an error+ # before handing the summary over; reading the pipeline directly,+ # we apply the same rule here.+ if "success" in item:+ if not item["success"]:+ continue+ else:+ meta = item.get("metadata") if isinstance(item.get("metadata"), dict) else {}+ if meta.get("error"):+ continueqa = item.get("qa_pair") or {}if not isinstance(qa, dict):continuediff --git a/deeptutor/book/blocks/section.py b/deeptutor/book/blocks/section.pyindex 6dcc651be..42294f036 100644--- a/deeptutor/book/blocks/section.py+++ b/deeptutor/book/blocks/section.py@@ -34,6 +34,20 @@ from .base import BlockContext, BlockGenerator, GenerationFailurelogger = logging.getLogger(__name__)+def _subsection_token_budget(target_words: int) -> int:+ """Token ceiling that actually fits *target_words*.++ A flat cap silently truncated the deeper settings: asking for 1.6x the prose+ and leaving the ceiling at 1200 tokens produced a section that stops+ mid-sentence. Budget generously — the model stops when it is done, so a+ high ceiling costs nothing on shorter sections, while too low a one is+ unrecoverable. CJK needs more tokens per word than English, hence the+ deliberately loose ratio.+ """+ words = max(1, int(target_words or 0))+ return max(1200, min(8000, int(words * 3.0) + 400))++_DEFAULT_SUBSECTION_WORDS = 320@@ -289,7 +303,7 @@ class SectionGenerator(BlockGenerator):body = await llm_text(user_prompt=user_prompt,system_prompt=get_book_prompt(prompts, "subsection_system"),- max_tokens=1200,+ max_tokens=_subsection_token_budget(target_words),temperature=0.5,language=ctx.language,)diff --git a/deeptutor/book/compiler.py b/deeptutor/book/compiler.pyindex 73cb63b3e..a9d604efb 100644--- a/deeptutor/book/compiler.py+++ b/deeptutor/book/compiler.py@@ -42,6 +42,41 @@ from .streaming import STAGE_BLOCK, STAGE_COMPILATION, STAGE_PAGE_PLAN, BookStrelogger = logging.getLogger(__name__)+# Failure kinds (from ``blocks.base._classify_failure``) that say something is+# wrong with the *provider account* rather than with this particular block —+# a bad API key, an exhausted quota, an outage. One is worth retrying; a page+# made entirely of them means the next page will fail the same way.+SYSTEMIC_FAILURE_KINDS = frozenset({"rate_limit", "provider_error", "timeout"})+++def systemic_failure_reason(page: Page) -> str:+ """Why *page* looks like a provider/account failure — ``""`` if it doesn't.++ Lets the engine's breaker tell "this chapter didn't work" apart from+ "nothing is going to work until the user fixes their setup", and hands back+ a reason concrete enough to show the reader ("rate_limit: 429 …") instead+ of a bare page-level tally.+ """+ failed = [b for b in page.blocks if b.status == BlockStatus.ERROR]+ if not failed:+ return ""++ systemic = [+ b+ for b in failed+ if str((b.metadata or {}).get("failure", {}).get("kind", "")) in SYSTEMIC_FAILURE_KINDS+ ]+ # A single flaky block is normal; a page that is *mostly* provider errors+ # means the next page will hit the same wall.+ if len(systemic) * 2 < len(failed):+ return ""++ failure = (systemic[0].metadata or {}).get("failure", {})+ kind = str(failure.get("kind") or "provider_error")+ message = str(failure.get("message") or "").strip()+ return f"{kind}: {message}" if message else kind++@dataclassclass CompilerOptions:"""Knobs that influence how a page is compiled."""@@ -65,6 +100,17 @@ class CompilerOptions:architect_llm_enabled: bool = True"""When True, ``SectionArchitect`` may use the LLM layer to plan blocks."""+ block_retry_attempts: int = 1+ """Extra attempts for a block whose failure metadata says ``retryable``.++ Transient provider hiccups (a 429, a stalled response) are the single most+ common reason a block dies, and one backed-off retry recovers most of them+ — the difference between a chapter with a hole in it and a whole one.+ """++ block_retry_backoff_seconds: float = 2.0+ """Base delay before a retry; doubles per attempt."""+class BookCompiler:"""Compile a single page (or list of pages) end-to-end."""@@ -94,6 +140,7 @@ class BookCompiler:stream: BookStream,knowledge_bases: list[str] | None = None,language: str = "en",+ depth: str | None = None,exploration: ExplorationReport | None = None,) -> Page:"""Plan (if needed) and generate every block on *page*."""@@ -112,7 +159,13 @@ class BookCompiler:logger.debug(f"load_exploration({book_id}) skipped: {exc}")await self._plan_if_needed(- book_id, chapter, page, stream, language=language, exploration=exploration+ book_id,+ chapter,+ page,+ stream,+ language=language,+ depth=depth,+ exploration=exploration,)page.status = PageStatus.GENERATING@@ -219,9 +272,7 @@ class BookCompiler:block.error = f"No generator registered for block type {block.type.value}"logger.warning(block.error)else:- t0 = time.time()- await generator.generate(ctx)- block.metadata.setdefault("generation_ms", int((time.time() - t0) * 1000))+ await self._generate_with_retry(generator, ctx, block)if block.status == BlockStatus.READY:await self._attach_bridge_text(@@ -248,6 +299,34 @@ class BookCompiler:stage=STAGE_BLOCK,)+ async def _generate_with_retry(self, generator, ctx: BlockContext, block: Block) -> None:+ """Run *generator*, retrying once (backed off) on a retryable failure.++ ``BlockGenerator.generate`` never raises — it records the outcome on the+ block, tagging failures with a ``kind`` and a ``retryable`` flag. This+ is the only place that acts on that flag; without it the classification+ was computed and then thrown away.+ """+ attempts = max(0, self.options.block_retry_attempts) + 1+ for attempt in range(attempts):+ t0 = time.time()+ await generator.generate(ctx)+ block.metadata.setdefault("generation_ms", int((time.time() - t0) * 1000))++ if block.status != BlockStatus.ERROR:+ return+ failure = (block.metadata or {}).get("failure") or {}+ if not failure.get("retryable") or attempt == attempts - 1:+ return++ delay = self.options.block_retry_backoff_seconds * (2**attempt)+ logger.info(+ f"block {block.id} ({block.type.value}) failed with "+ f"{failure.get('kind')}; retrying in {delay:.1f}s"+ )+ await asyncio.sleep(delay)+ block.metadata["retry_attempts"] = attempt + 1+# ── Bridge text attachment ─────────────────────────────────────────async def attach_bridge_text(@@ -310,6 +389,7 @@ class BookCompiler:stream: BookStream,*,language: str = "en",+ depth: str | None = None,exploration: ExplorationReport | None = None,) -> None:if page.blocks:@@ -323,7 +403,7 @@ class BookCompiler:)planned = await self.architect.plan_blocks_async(- chapter, exploration=exploration, language=language+ chapter, exploration=exploration, language=language, depth=depth)page.blocks = plannedif not page.content_type:diff --git a/deeptutor/book/engine.py b/deeptutor/book/engine.pyindex 350f124b6..38a36f84e 100644--- a/deeptutor/book/engine.py+++ b/deeptutor/book/engine.py@@ -15,39 +15,53 @@ Lifecycleconfirm_proposal(...) → Spine (Stage 2, requires user confirm)confirm_spine(...) → page shells + queued compilationcompile_page(book, page) → Page (Stage 3-4, drives BookCompiler)- list_books(), load_book(), delete_book(), resume_book()+ resume_book(...) → re-queue unfinished pages, keeping what exists+ rebuild_book(...) → discard every page and regenerate from the spine+ list_books(), load_book(), delete_book()Compilation queue------------------For each book a per-book ``asyncio.Queue`` schedules pages with priority:-- Highest priority: page the user just opened (handled inline).-- Background: remaining unfinished pages, processed by a single worker.+Each book gets a ``_BookRuntime``: an ``asyncio.Queue`` of pending pages, one+background worker, and an **in-flight table** keyed by page id. Every path that+can compile a page — the reader opening one, the worker reaching one, a forced+regenerate — goes through :meth:`BookEngine.compile_page`, which consults that+table so concurrent requests for the same page join a single run instead of+racing into duplicate generations.-The engine emits all progress over a ``StreamBus`` (wrapped by ``BookStream``)-which the WebSocket router fans out to clients.+The worker trips a breaker (``CONSECUTIVE_PAGE_FAILURE_LIMIT``) when pages fail+for provider-level reasons, pausing the book rather than grinding the remaining+chapters into half-generated debris.++Progress is published to the book's long-lived stream in :mod:`.event_hub`,+never to a request-scoped bus — background compilation must keep streaming+after the call that queued it has returned."""from __future__ import annotationsimport asynciofrom dataclasses import dataclass, field+from functools import partialimport loggingimport timefrom typing import Anyfrom deeptutor.core.stream_bus import StreamBus+from . import progress as progress_opsfrom .agents.ideation_agent import IdeationAgentfrom .agents.source_explorer import SourceExplorerfrom .agents.spine_synthesizer import SpineSynthesizer-from .compiler import BookCompiler, CompilerOptions+from .compiler import BookCompiler, CompilerOptions, systemic_failure_reason+from .event_hub import close_book_bus, get_book_busfrom .inputs import IdeationContext, build_book_inputsfrom .models import (Block,BlockStatus,BlockType,Book,+ BookDepth,BookInputs,BookProposal,BookStatus,@@ -58,9 +72,9 @@ from .models import (PageLink,PageStatus,Progress,- QuizAttempt,Spine,)+from .overview_copy import overview_copyfrom .storage import BookStorage, get_book_storagefrom .streaming import (STAGE_COMPILATION,@@ -81,15 +95,118 @@ logger = logging.getLogger(__name__)# ─────────────────────────────────────────────────────────────────────────────+# A page that fails *entirely* for provider-level reasons (quota exhausted,+# credentials revoked, provider down) will be followed by more of the same, so+# the queue trips a breaker instead of grinding the rest of the book into+# half-generated pages. Ungenerated pages are an asset; half-generated ones are+# debris the user has to clean up.+CONSECUTIVE_PAGE_FAILURE_LIMIT = 2+++# Statuses that mean "this page still has work owed to it". PARTIAL is+# deliberately absent: the compiler already ran every block and some failed for+# good, so re-queueing it on each open would re-spend the same model calls+# forever without changing the outcome. Force-regenerate is the way back in.+_UNFINISHED_PAGE_STATUSES = frozenset(+ {+ PageStatus.PENDING,+ PageStatus.PLANNING,+ PageStatus.GENERATING,+ PageStatus.ERROR,+ }+)+++# Blocks whose content is a single run of prose the reader can correct in+# place. Everything else carries structured payloads — a section's subsections,+# a quiz's questions, a figure's source — where a plain text box would either+# destroy the structure or edit a field nothing renders. Those stay on+# regenerate.+_EDITABLE_BLOCK_TYPES = frozenset({BlockType.TEXT, BlockType.USER_NOTE, BlockType.CALLOUT})+++def _body_key(block: Block) -> str:+ """Which payload key holds a block's prose.++ ``TEXT`` blocks are inconsistent by history: the generator writes ``body``+ while the deterministic overview blocks write ``content``. Respect whatever+ the block already uses so an edit lands where the renderer reads.+ """+ if block.type == BlockType.TEXT and "content" in (block.payload or {}):+ return "content"+ return "body"+++def _prune_concept_graph(spine: Spine) -> int:+ """Drop graph nodes whose chapter no longer exists, and dangling edges.++ The concept graph is built once, before the reader ever opens the spine+ editor, and is never rebuilt. Deleting a chapter therefore left its concept+ on the Overview page's map — the book's own front page contradicting its+ table of contents. Pruning is deterministic and costs no model call; the+ remaining graph is still the one that was synthesised, just without the+ parts the reader removed.++ Returns the number of nodes dropped.+ """+ graph = spine.concept_graph+ if not graph.nodes:+ return 0++ live_chapters = {c.id for c in spine.chapters}+ kept = [n for n in graph.nodes if not n.chapter_id or n.chapter_id in live_chapters]+ dropped = len(graph.nodes) - len(kept)+ if not dropped:+ return 0++ kept_ids = {n.id for n in kept}+ graph.nodes = kept+ graph.edges = [e for e in graph.edges if e.src in kept_ids and e.dst in kept_ids]+ return dropped+++def _is_auto_overview(chapter: Chapter) -> bool:+ """Whether *chapter* is the engine-injected overview.++ Checks both markers: ``content_type`` survives a round trip through the+ typed model, while the ``auto_overview`` extra survives a chapter whose+ content type was changed by hand in the spine editor.+ """+ return (+ chapter.content_type == ContentType.OVERVIEW+ or (chapter.__pydantic_extra__ or {}).get("auto_overview") is True+ )+++def _coerce_depth(value: str | BookDepth | None) -> BookDepth:+ """Accept anything the API layer might pass; fall back to STANDARD."""+ if isinstance(value, BookDepth):+ return value+ try:+ return BookDepth(str(value or "").strip().lower())+ except ValueError:+ return BookDepth.STANDARD++@dataclassclass _BookRuntime:- """In-process per-book scheduling state."""+ """In-process per-book **scheduling** state.++ Deliberately owns no event stream: streams live in :mod:`.event_hub` and+ outlive any single request, so background compilation keeps broadcasting+ after the call that queued it has returned.+ """queue: asyncio.Queue[str] = field(default_factory=asyncio.Queue)queued: set[str] = field(default_factory=set)+ # page_id → the task currently compiling it. The single source of truth for+ # "is this page already being built", shared by the foreground+ # ``compile_page`` path and the background worker so they can never race+ # into compiling the same page twice.+ in_flight: dict[str, asyncio.Task[Page]] = field(default_factory=dict)worker: asyncio.Task[None] | None = Nonelock: asyncio.Lock = field(default_factory=asyncio.Lock)- stream: BookStream | None = None # default stream for background work+ consecutive_page_failures: int = 0# ─────────────────────────────────────────────────────────────────────────────@@ -128,6 +245,29 @@ class BookEngine:def load_book(self, book_id: str) -> Book | None:return self.storage.load_book(book_id)+ def reading_summary(self, book: Book) -> dict[str, Any]:+ """How far the reader has got, cheap enough to compute for a whole shelf.++ Reads only ``progress.json`` and the page count already on the manifest+ — deliberately no ``list_pages``, which would turn drawing the library+ into one directory scan per book.+ """+ progress = self.storage.load_progress(book.id)+ total = max(0, book.page_count)+ if progress is None:+ return {+ "current_page_id": "",+ "visited_pages": 0,+ "total_pages": total,+ "percent": 0,+ }+ return {+ "current_page_id": progress.current_page_id,+ "visited_pages": len(set(progress.visited_page_ids)),+ "total_pages": total,+ "percent": round(progress_ops.completion_ratio(progress, total) * 100),+ }+def load_spine(self, book_id: str) -> Spine | None:return self.storage.load_spine(book_id)@@ -146,8 +286,15 @@ class BookEngine:def delete_book(self, book_id: str) -> bool:runtime = self._runtimes.pop(book_id, None)- if runtime and runtime.worker and not runtime.worker.done():- runtime.worker.cancel()+ if runtime is not None:+ if runtime.worker and not runtime.worker.done():+ runtime.worker.cancel()+ for task in runtime.in_flight.values():+ if not task.done():+ task.cancel()+ # The book's event stream is the one thing that outlives its requests,+ # so deletion is the only place allowed to close it.+ close_book_bus(book_id)return self.storage.delete_book(book_id)def set_page_chat_session(self, *, book_id: str, page_id: str, session_id: str) -> Book | None:@@ -176,10 +323,18 @@ class BookEngine:@staticmethoddef _reset_page_for_force_compile(page: Page) -> None:- """Reset generated block outputs while preserving user-authored notes."""+ """Reset generated block outputs while preserving anything user-authored.++ Notes and hand-edited prose survive a forced regenerate. A reader who+ corrected a sentence and then hit "regenerate page" should not silently+ lose their correction — the two actions have nothing to do with each+ other from their point of view.+ """for block in page.blocks:if block.type == BlockType.USER_NOTE:continue+ if (block.metadata or {}).get("edited_by_user"):+ continuepreserved_metadata = {key: valuefor key, value in (block.metadata or {}).items()@@ -208,6 +363,7 @@ class BookEngine:question_categories: list[int] | None = None,question_entries: list[int] | None = None,language: str = "en",+ depth: str = BookDepth.STANDARD.value,stream: StreamBus | None = None,) -> tuple[Book, BookProposal]:"""Capture inputs, run IdeationAgent, persist DRAFT book + proposal."""@@ -240,6 +396,7 @@ class BookEngine:proposal=proposal,knowledge_bases=book_inputs.knowledge_bases,language=language,+ depth=_coerce_depth(depth),chapter_count=proposal.estimated_chapters,)# Capture baseline KB fingerprints immediately so subsequent drift@@ -295,7 +452,7 @@ class BookEngine:book.title = edited_proposal.title or book.titlebook.description = edited_proposal.description or book.description- bus = stream or StreamBus()+ bus = stream or get_book_bus(book_id)bstream = BookStream(bus)proposal = book.proposal or BookProposal(title=book.title)@@ -321,6 +478,12 @@ class BookEngine:inputs=inputs,)self.storage.save_exploration(book.id, exploration)+ if (book.metadata or {}).get("exploration_failed"):+ book.metadata = {+ k: v+ for k, v in book.metadata.items()+ if k not in ("exploration_failed", "exploration_error")+ }await bstream.book_event("exploration_ready",{@@ -335,8 +498,20 @@ class BookEngine:except Exception as exc:logger.warning(f"SourceExplorer failed for {book.id}: {exc}")exploration = None- await bstream.progress(- "Source exploration unavailable — falling back to proposal-only spine.",+ book.metadata = {+ **(book.metadata or {}),+ "exploration_failed": True,+ "exploration_error": str(exc)[:400],+ }+ self.storage.save_book(book)+ self.storage.append_log(+ book_id,+ f"source exploration failed, spine built from the proposal alone: {exc}",+ op="exploration_failed",+ )+ await bstream.book_event(+ "exploration_failed",+ {"book_id": book.id, "reason": str(exc)[:400]},stage=STAGE_EXPLORATION,)@@ -402,52 +577,45 @@ class BookEngine:*,stream: StreamBus | None,) -> Spine:- """Insert an Overview chapter at position 0 (idempotent)."""- # Idempotent guard — already injected?- first = spine.chapters[0] if spine.chapters else None- already = bool(- first- and (- first.content_type == ContentType.OVERVIEW- or (first.__pydantic_extra__ or {}).get("auto_overview") is True- )- )- if already:+ """Ensure exactly one Overview chapter, first in the spine (idempotent).++ Identity, not position, decides whether one already exists. Keying the+ guard on ``chapters[0]`` meant any caller that handed the spine back+ with the overview elsewhere in the list — the spine editor re-appends+ hidden chapters after the user's own — silently got a second one on+ every re-confirm, each with its own page.+ """+ existing = [c for c in spine.chapters if _is_auto_overview(c)]+ if existing:+ keep, *duplicates = existing+ if duplicates:+ logger.warning(+ f"book {book.id}: dropping {len(duplicates)} duplicate overview chapter(s)"+ )+ dropped = {id(c) for c in duplicates}+ spine.chapters = [c for c in spine.chapters if id(c) not in dropped]+ # Re-seat it at the front and renumber, so a spine that came back+ # out of order still reads correctly.+ spine.chapters = [keep, *[c for c in spine.chapters if c is not keep]]+ for index, chapter in enumerate(spine.chapters):+ chapter.order = indexreturn spine- overview_title = "本书导览" if book.language == "zh" else "How to read this book"- objectives = (- [- "了解整本书的章节脉络",- "掌握各章之间的概念依赖关系",- "选择最合适的阅读顺序",- ]- if book.language == "zh"- else [- "See the full chapter map at a glance",- "Understand how concepts depend on each other",- "Pick the reading path that fits your goals",- ]- )+ copy = overview_copy(book.language)overview = Chapter(- title=overview_title,- learning_objectives=objectives,+ title=copy["chapter_title"],+ learning_objectives=list(copy["objectives"]),content_type=ContentType.OVERVIEW,- summary=(- "Auto-generated overview of the book's concept graph and chapter index."- if book.language != "zh"- else "自动生成的概念图与章节索引,作为本书的入口。"- ),+ summary=copy["chapter_summary"],order=0,)# Mark for idempotency on subsequent runs.overview.__pydantic_extra__ = overview.__pydantic_extra__ or {}overview.__pydantic_extra__["auto_overview"] = True- # Re-number existing chapters down by one.- for ch in spine.chapters:- ch.order = ch.order + 1spine.chapters = [overview, *spine.chapters]+ for index, chapter in enumerate(spine.chapters):+ chapter.order = indexreturn spineasync def _materialize_overview_page(@@ -469,7 +637,7 @@ class BookEngine:if overview_page is None or overview_page.status == PageStatus.READY:return- zh = book.language == "zh"+ copy = overview_copy(book.language)chapter_index = [{"id": ch.id,@@ -485,29 +653,17 @@ class BookEngine:]# 1) Intro text block (pre-rendered, status=READY)- intro_md = (- (- f"# {book.title or '本书'}\n\n"- f"{(book.proposal.description if book.proposal else '') or ''}\n\n"- f"下方的概念图展示了本书 {len(spine.concept_graph.nodes)} 个核心概念以及"- f"它们之间的依赖关系;再下方是 {len(chapter_index)} 个章节的入口。"- f"你可以按从上到下的顺序阅读,也可以根据自己的兴趣或先验知识选择切入点。"- )- if zh- else (- f"# {book.title or 'This book'}\n\n"- f"{(book.proposal.description if book.proposal else '') or ''}\n\n"- f"The diagram below maps the {len(spine.concept_graph.nodes)} core "- f"concepts in this book and how they depend on each other. The "- f"chapter index that follows lists all {len(chapter_index)} "- f"chapters — read top-to-bottom for the recommended path, or jump "- f"straight to whatever you're most curious about."- )+ description = (book.proposal.description if book.proposal else "") or ""+ intro_md = f"# {book.title or copy['untitled_book']}\n\n{description}\n\n" + copy[+ "intro_body"+ ].format(+ concepts=len(spine.concept_graph.nodes),+ chapters=len(chapter_index),)intro_block = Block(type=BlockType.TEXT,status=BlockStatus.READY,- title=("如何阅读这本书" if zh else "How to read this book"),+ title=copy["intro_title"],params={"role": "overview_intro"},payload={"content": intro_md, "format": "markdown"},)@@ -518,7 +674,7 @@ class BookEngine:graph_block = Block(type=BlockType.CONCEPT_GRAPH,status=BlockStatus.READY,- title=("概念图" if zh else "Concept map"),+ title=copy["concept_map_title"],params={"concept_graph": spine.concept_graph.model_dump(),"chapter_index": chapter_index,@@ -550,32 +706,54 @@ class BookEngine:if entry.get("summary"):line += f" — {entry['summary']}"index_lines.append(line)- index_md = ("## 章节索引\n\n" if zh else "## Chapter index\n\n") + "\n".join(index_lines)+ index_md = copy["chapter_index_heading"] + "\n\n" + "\n".join(index_lines)index_block = Block(type=BlockType.TEXT,status=BlockStatus.READY,- title=("章节索引" if zh else "Chapter index"),+ title=copy["chapter_index_title"],params={"role": "chapter_index"},payload={"content": index_md, "format": "markdown"},)- overview_page.blocks = [intro_block, graph_block, index_block]+ # This page is rebuilt from scratch every time the spine changes, which+ # is the one place ``edited_by_user`` protection cannot reach — the+ # blocks are replaced wholesale rather than reset. Carry the reader's+ # own content across: a hand-edited deterministic block wins over its+ # freshly rendered replacement, and notes are appended.+ edited_by_role: dict[str, Block] = {}+ notes: list[Block] = []+ for existing in overview_page.blocks:+ if existing.type == BlockType.USER_NOTE:+ notes.append(existing)+ elif (existing.metadata or {}).get("edited_by_user"):+ role = str((existing.params or {}).get("role") or existing.type.value)+ edited_by_role[role] = existing++ def _keep(block: Block, role: str) -> Block:+ return edited_by_role.get(role, block)++ overview_page.blocks = [+ _keep(intro_block, "overview_intro"),+ _keep(graph_block, BlockType.CONCEPT_GRAPH.value),+ _keep(index_block, "chapter_index"),+ *notes,+ ]overview_page.status = PageStatus.READYoverview_page.content_type = ContentType.OVERVIEWself.storage.save_page(overview_page)- if stream is not None:- bstream = BookStream(stream)- await bstream.book_event(- "overview_ready",- {- "book_id": book.id,- "page_id": overview_page.id,- "node_count": len(spine.concept_graph.nodes),- "chapter_count": len(chapter_index),- },- stage=STAGE_OVERVIEW,- )+ # Publish to the book's own stream. Guarding on ``stream is not None``+ # silently dropped this event once callers stopped passing a bus.+ await BookStream(stream or get_book_bus(book.id)).book_event(+ "overview_ready",+ {+ "book_id": book.id,+ "page_id": overview_page.id,+ "node_count": len(spine.concept_graph.nodes),+ "chapter_count": len(chapter_index),+ },+ stage=STAGE_OVERVIEW,+ )# ── Stage 3: confirm spine + create page shells ─────────────────────@@ -605,6 +783,15 @@ class BookEngine:spine.book_id = book_idself.storage.save_spine(spine)+ # Chapters the reader deleted must not survive on the concept map.+ dropped = _prune_concept_graph(spine)+ if dropped:+ self.storage.append_log(+ book_id,+ f"pruned {dropped} concept-graph node(s) for deleted chapters",+ op="confirm_spine",+ )+# ── Inject Overview chapter (idempotent) ─────────────────────spine = await self._ensure_overview_chapter(spine, book, stream=stream)self.storage.save_spine(spine)@@ -626,13 +813,32 @@ class BookEngine:self.storage.save_page(page)chapter.page_ids = [page.id]self.storage.save_spine(spine)+ elif (+ page.order != chapter.order+ or page.title != chapter.title+ or page.content_type != chapter.content_type+ ):+ # A re-confirm after editing the spine has to carry the edits+ # onto pages that already exist, or reordering and renaming+ # chapters changes nothing the reader can see: pages are sorted+ # by ``order`` (storage.list_pages) and titled from the page.+ page.order = chapter.order+ page.title = chapter.title+ page.content_type = chapter.content_type+ page.learning_objectives = list(chapter.learning_objectives)+ page.updated_at = time.time()+ self.storage.save_page(page)pages.append(page)+ pages.sort(key=lambda p: (p.order, p.created_at))# Build the Overview page eagerly (no LLM, no queue).await self._materialize_overview_page(spine, pages, book, stream=stream)book.page_count = len(pages)- book.status = BookStatus.COMPILING if auto_compile else BookStatus.SPINE_READY+ book.status = BookStatus.COMPILING+ metadata = {k: v for k, v in (book.metadata or {}).items() if k != "pause_reason"}+ metadata["lazy_compile"] = not auto_compile+ book.metadata = metadataself.storage.save_book(book)self.storage.append_log(book_id,@@ -641,9 +847,119 @@ class BookEngine:)if auto_compile:- await self._enqueue_pending_pages(book_id, pages, stream=stream)+ await self._enqueue_pending_pages(book_id, pages)return pages+ async def _halt_compilation(self, book_id: str) -> None:+ """Stop this book's worker and drain its queue, leaving disk untouched."""+ runtime = self._runtimes.get(book_id)+ if runtime is None:+ return+ async with runtime.lock:+ if runtime.worker is not None and not runtime.worker.done():+ runtime.worker.cancel()+ runtime.worker = None+ for task in runtime.in_flight.values():+ if not task.done():+ task.cancel()+ runtime.in_flight.clear()+ runtime.queued.clear()+ runtime.consecutive_page_failures = 0+ while not runtime.queue.empty():+ try:+ runtime.queue.get_nowait()+ except asyncio.QueueEmpty:+ break++ async def resume_book(+ self,+ *,+ book_id: str,+ stream: StreamBus | None = None,+ ) -> list[Page]:+ """Re-queue every page that never finished, keeping what already exists.++ The non-destructive counterpart to :meth:`rebuild_book`. Three things+ need it and previously had only "delete everything and start over":++ - a process restart (per-book runtimes live in memory only),+ - a paused book once the user has topped up their quota,+ - a page stranded in ``PLANNING``/``GENERATING`` by a crash.++ Pages that are already ``READY`` are left exactly as they are, so+ resuming costs only the work that is genuinely missing.+ """+ book = self.storage.load_book(book_id)+ if book is None:+ raise ValueError(f"Book {book_id} not found")+ if self.storage.load_spine(book_id) is None:+ raise ValueError(f"No spine for book {book_id}")++ # A page left mid-flight by a crash would otherwise be skipped by the+ # queue's "already generating" checks forever.+ pages = self.storage.list_pages(book_id)+ for page in pages:+ if page.status in (PageStatus.PLANNING, PageStatus.GENERATING):+ page.status = PageStatus.PENDING+ page.updated_at = time.time()+ self.storage.save_page(page)++ pending = [p for p in pages if p.status in _UNFINISHED_PAGE_STATUSES]+ if not pending:+ await self._maybe_finalize_book(book_id)+ return pages++ book.status = BookStatus.COMPILING+ book.metadata = {k: v for k, v in (book.metadata or {}).items() if k != "pause_reason"}+ book.updated_at = time.time()+ self.storage.save_book(book)+ self.storage.append_log(+ book_id, f"resume requested ({len(pending)} unfinished pages)", op="resume"+ )++ await self._enqueue_pending_pages(book_id, pending)+ return self.storage.list_pages(book_id)++ async def maybe_resume_on_open(self, book_id: str) -> bool:+ """Restart stalled compilation when the reader opens a book.++ ``PathService`` resolves per current user, so a process-wide sweep at+ startup cannot even enumerate other users' books. Opening a book is the+ natural, correctly-scoped trigger instead: it runs as that user and+ only touches the book they actually care about.++ Deliberately does *not* resume a ``PAUSED`` book — that one stopped for+ a reason the user has to clear first, and silently retrying would burn+ the quota they just ran out of. Returns whether work was queued.+ """+ book = self.storage.load_book(book_id)+ if book is None or book.status != BookStatus.COMPILING:+ return False++ if (book.metadata or {}).get("lazy_compile"):+ # The reader asked for chapters to be built as they open them.+ # Resuming would queue the whole book and defeat that choice.+ return False++ runtime = self._runtimes.get(book_id)+ if runtime is not None:+ # Liveness, not queue depth. A queue with items in it and no worker+ # draining them is exactly the state that needs rescuing — reading+ # ``queued`` as proof of progress left such a book wedged at+ # COMPILING for the life of the process.+ if runtime.in_flight:+ return False+ if runtime.worker is not None and not runtime.worker.done():+ return False+ try:+ await self.resume_book(book_id=book_id)+ except ValueError:+ return False+ except Exception: # noqa: BLE001+ logger.warning(f"auto-resume failed for {book_id}", exc_info=True)+ return False+ return True+async def rebuild_book(self,*,@@ -657,18 +973,7 @@ class BookEngine:if book is None or spine is None:raise ValueError(f"Cannot rebuild book – missing book/spine ({book_id})")- runtime = self._runtimes.get(book_id)- if runtime is not None:- async with runtime.lock:- if runtime.worker is not None and not runtime.worker.done():- runtime.worker.cancel()- runtime.worker = None- runtime.queued.clear()- while not runtime.queue.empty():- try:- runtime.queue.get_nowait()- except asyncio.QueueEmpty:- break+ await self._halt_compilation(book_id)for page in self.storage.list_pages(book_id):self.storage.delete_page(book_id, page.id)@@ -704,7 +1009,71 @@ class BookEngine:stream: StreamBus | None = None,force: bool = False,) -> Page:- """Drive the compiler for one page (used when a user opens it)."""+ """Compile one page, coalescing concurrent requests for the same page.++ Three call sites can ask for the same page at once — the user opening+ it, the background worker reaching it, and a forced regenerate. Without+ coalescing they each run a full plan-and-generate pass, pay for it, and+ then race to persist, so the loser's output is silently discarded.++ A plain request *joins* the run already in flight. A forced one waits+ for that run to finish and then starts a clean pass, so a regenerate+ never interleaves with the generation it is meant to replace.+ """+ runtime = await self._get_or_create_runtime(book_id)++ while True:+ async with runtime.lock:+ running = runtime.in_flight.get(page_id)+ if running is None or running.done():+ task = asyncio.create_task(+ self._compile_page_now(+ book_id=book_id,+ page_id=page_id,+ stream=stream,+ force=force,+ )+ )+ runtime.in_flight[page_id] = task+ task.add_done_callback(partial(self._release_in_flight, runtime, page_id))+ break+ if not force:+ task = running+ break+ joined = running+ # Outside the lock: let the in-flight pass finish, then loop round+ # and claim the slot for the forced rebuild. ``asyncio.wait`` never+ # re-raises, which is what we want — we only care that it ended.+ await asyncio.wait({joined})++ # Shielded: awaiting a task propagates the awaiter's cancellation *into*+ # that task, so one caller going away — a closed WebSocket, a client+ # that navigated on — would otherwise kill a run that other awaiters and+ # the background worker are relying on. Compilation persists its own+ # output, so it is always right to let it finish; the ways to genuinely+ # stop it (``_halt_compilation``, ``delete_book``) cancel the task+ # directly.+ return await asyncio.shield(task)++ @staticmethod+ def _release_in_flight(runtime: _BookRuntime, page_id: str, task: asyncio.Task[Page]) -> None:+ """Drop *page_id* from the in-flight table once *task* settles.++ Keyed on identity so a task that has already been replaced by a forced+ rebuild cannot evict its successor.+ """+ if runtime.in_flight.get(page_id) is task:+ runtime.in_flight.pop(page_id, None)++ async def _compile_page_now(+ self,+ *,+ book_id: str,+ page_id: str,+ stream: StreamBus | None = None,+ force: bool = False,+ ) -> Page:+ """Drive the compiler for one page. Always run via :meth:`compile_page`."""book = self.storage.load_book(book_id)spine = self.storage.load_spine(book_id)page = self.storage.load_page(book_id, page_id)@@ -735,7 +1104,7 @@ class BookEngine:if chapter is None:raise ValueError(f"Page {page_id} references unknown chapter {page.chapter_id}")- bus = stream or StreamBus()+ bus = stream or get_book_bus(book_id)bstream = BookStream(bus)try:@@ -747,6 +1116,7 @@ class BookEngine:stream=bstream,knowledge_bases=book.knowledge_bases,language=book.language,+ depth=book.depth.value,)except Exception as exc:self._mark_page_error(page, exc, prefix="Compilation failed")@@ -770,34 +1140,35 @@ class BookEngine:# ── Background compilation queue ─────────────────────────────────────- async def _enqueue_pending_pages(- self,- book_id: str,- pages: list[Page],- *,- stream: StreamBus | None = None,- ) -> None:- runtime = await self._get_or_create_runtime(book_id, stream)- async with runtime.lock:- for page in pages:- if page.status == PageStatus.READY:- continue- if page.id in runtime.queued:- continue- runtime.queued.add(page.id)- await runtime.queue.put(page.id)- self._ensure_worker(book_id)-- async def _get_or_create_runtime(self, book_id: str, stream: StreamBus | None) -> _BookRuntime:+ async def _enqueue_pending_pages(self, book_id: str, pages: list[Page]) -> None:+ while True:+ runtime = await self._get_or_create_runtime(book_id)+ async with runtime.lock:+ # An idle worker retires its runtime under the same two locks in+ # the same order. If it did so between our lookup and this+ # acquisition, we would be queueing into an orphan that nothing+ # drains — take the live runtime and try again.+ async with self._global_lock:+ if self._runtimes.get(book_id) is not runtime:+ continue++ runtime.consecutive_page_failures = 0+ for page in pages:+ if page.status == PageStatus.READY:+ continue+ if page.id in runtime.queued:+ continue+ runtime.queued.add(page.id)+ await runtime.queue.put(page.id)+ self._ensure_worker(book_id)+ return++ async def _get_or_create_runtime(self, book_id: str) -> _BookRuntime:async with self._global_lock:runtime = self._runtimes.get(book_id)if runtime is None:runtime = _BookRuntime()self._runtimes[book_id] = runtime- if stream is not None and runtime.stream is None:- runtime.stream = BookStream(stream)- elif runtime.stream is None:- runtime.stream = BookStream(StreamBus())return runtimedef _mark_page_error(self, page: Page | None, exc: Exception, *, prefix: str) -> None:@@ -834,15 +1205,24 @@ class BookEngine:runtime = self._runtimes.get(book_id)if runtime is None:return- bstream = runtime.stream or BookStream(StreamBus())++ # A task inherits the context it was created in, and this one is created+ # inside whichever request happened to enqueue first. That request may+ # have installed a scoped LLM config (a per-run model pick); without+ # clearing it, every chapter this worker compiles for the rest of its+ # life would silently use that one request's model. Background+ # compilation belongs to the book, not to the call that started it, so+ # it runs against the user's current configuration.+ from deeptutor.services.llm.config import set_scoped_llm_config++ set_scoped_llm_config(None)while True:try:page_id = await asyncio.wait_for(runtime.queue.get(), timeout=2.0)except asyncio.TimeoutError:async with runtime.lock:- if runtime.queue.empty():+ if runtime.queue.empty() and not runtime.in_flight:runtime.worker = None- runtime.stream = Noneasync with self._global_lock:if self._runtimes.get(book_id) is runtime:self._runtimes.pop(book_id, None)@@ -857,25 +1237,16 @@ class BookEngine:# the UnboundLocalError would kill this worker task) nor stale from# a previous iteration (the wrong page would be flipped to ERROR).page = None+ tripped = Falsetry:- book = self.storage.load_book(book_id)- spine = self.storage.load_spine(book_id)page = self.storage.load_page(book_id, page_id)- if book is None or spine is None or page is None:+ if page is None or page.status == PageStatus.READY:continue- if page.status == PageStatus.READY:- continue- chapter = spine.chapter_by_id(page.chapter_id)- if chapter is None:- continue- await self.compiler.compile_page(- book_id=book_id,- chapter=chapter,- page=page,- stream=bstream,- knowledge_bases=book.knowledge_bases,- language=book.language,- )+ # Go through the coalescing entry point rather than straight to+ # the compiler: if the reader just opened this very page, both+ # requests must land on one run instead of two.+ compiled = await self.compile_page(book_id=book_id, page_id=page_id)+ tripped = await self._record_page_outcome(runtime, book_id, compiled)except asyncio.CancelledError:raiseexcept Exception as exc:@@ -895,13 +1266,67 @@ class BookEngine:logger.warning(f"Failed to append compile-error log for {book_id}", exc_info=True)+ tripped = await self._record_page_failure(runtime, book_id, str(exc))finally:runtime.queued.discard(page_id)- try:- await self._maybe_finalize_book(book_id)- except Exception:- logger.warning(f"finalize check failed for {book_id}", exc_info=True)+ if tripped:+ runtime.worker = None+ return++ # ── Compilation breaker ─────────────────────────────────────────────++ async def _record_page_outcome(self, runtime: _BookRuntime, book_id: str, page: Page) -> bool:+ """Feed a finished background page into the breaker.++ Returns ``True`` when the breaker tripped and the queue was drained.+ """+ reason = systemic_failure_reason(page) if page.status == PageStatus.ERROR else ""+ if not reason:+ # Any page that produced *something* proves the provider is alive.+ runtime.consecutive_page_failures = 0+ return False+ return await self._record_page_failure(runtime, book_id, reason)++ async def _record_page_failure(self, runtime: _BookRuntime, book_id: str, reason: str) -> bool:+ runtime.consecutive_page_failures += 1+ if runtime.consecutive_page_failures < CONSECUTIVE_PAGE_FAILURE_LIMIT:+ return False+ await self._pause_compilation(runtime, book_id, reason)+ return True++ async def _pause_compilation(self, runtime: _BookRuntime, book_id: str, reason: str) -> None:+ """Stop compiling this book and tell the reader why.++ Whatever is already on disk is kept: pausing leaves untouched pages+ ``PENDING`` so ``resume_book`` can pick them up verbatim once the user+ has fixed their quota or credentials.+ """+ async with runtime.lock:+ runtime.queued.clear()+ while not runtime.queue.empty():+ try:+ runtime.queue.get_nowait()+ except asyncio.QueueEmpty:+ break++ book = self.storage.load_book(book_id)+ if book is not None:+ book.status = BookStatus.PAUSED+ book.metadata = {**(book.metadata or {}), "pause_reason": reason}+ book.updated_at = time.time()+ self.storage.save_book(book)+ self.storage.append_log(+ book_id,+ f"compilation paused after {runtime.consecutive_page_failures} "+ f"consecutive provider failures: {reason}",+ op="paused",+ )+ await BookStream(get_book_bus(book_id)).book_event(+ "compilation_paused",+ {"book_id": book_id, "reason": reason},+ stage=STAGE_COMPILATION,+ )async def _maybe_finalize_book(self, book_id: str) -> None:book = self.storage.load_book(book_id)@@ -910,11 +1335,23 @@ class BookEngine:pages = self.storage.list_pages(book_id)if not pages:return- if all(p.status == PageStatus.READY for p in pages):+ if not any(p.status in _UNFINISHED_PAGE_STATUSES for p in pages):+ # Every page has settled — READY, or PARTIAL with blocks that will+ # not come back. The book is as done as it is going to get.if book.status != BookStatus.READY:book.status = BookStatus.READY+ book.metadata = {+ k: v for k, v in (book.metadata or {}).items() if k != "pause_reason"+ }self.storage.save_book(book)self.storage.append_log(book_id, "all pages ready → status=READY", op="finalize")+ # Without this the reader never learns the book finished:+ # the last page event fires while the book is still COMPILING.+ await BookStream(get_book_bus(book_id)).book_event(+ "book_ready",+ {"book_id": book_id, "page_count": len(pages)},+ stage=STAGE_COMPILATION,+ )# ── Block-level controls (Phase 1: regenerate single block) ─────────@@ -942,7 +1379,7 @@ class BookEngine:if params_override:block.params = {**block.params, **params_override}- bus = stream or StreamBus()+ bus = stream or get_book_bus(book_id)bstream = BookStream(bus)from .blocks.base import BlockContext, get_block_registry@@ -972,6 +1409,11 @@ class BookEngine:async with bstream.stage(STAGE_COMPILATION):await generator.generate(ctx)+ # The content is machine-written again, so the reader's edit is+ # gone; leaving the flag set would make force-regenerate skip this+ # block for the rest of the book's life.+ if block.metadata:+ block.metadata.pop("edited_by_user", None)if block.status.value == "ready":await self.compiler.attach_bridge_text(block,@@ -1065,7 +1507,7 @@ class BookEngine:if self.storage.load_book(book_id)else [],)- bus = stream or StreamBus()+ bus = stream or get_book_bus(book_id)bstream = BookStream(bus)async with bstream.stage(STAGE_COMPILATION):await generator.generate(ctx)@@ -1086,6 +1528,52 @@ class BookEngine:)return block+ async def update_block(+ self,+ *,+ book_id: str,+ page_id: str,+ block_id: str,+ title: str | None = None,+ body: str | None = None,+ ) -> Block | None:+ """Edit a block's prose in place, marking it as the reader's own.++ Deliberately limited to title and body. The point is to let someone fix+ a wrong sentence or write a margin note without gambling on a whole+ regeneration — not to turn the reader into a block-payload editor.++ The ``edited_by_user`` mark matters: :meth:`_reset_page_for_force_compile`+ honours it, so a later "regenerate this page" cannot quietly delete+ something the reader wrote.+ """+ page = self.storage.load_page(book_id, page_id)+ if page is None:+ return None+ block = page.block_by_id(block_id)+ if block is None or block.type not in _EDITABLE_BLOCK_TYPES:+ return None++ if title is not None:+ block.title = title+ if body is not None:+ block.payload = {+ **block.payload,+ _body_key(block): body,+ "format": "markdown",+ }+ block.status = BlockStatus.READY+ block.error = ""+ block.metadata = {**(block.metadata or {}), "edited_by_user": True}+ block.updated_at = time.time()++ self.compiler._finalize_page_status(page)+ self.storage.save_page(page)+ self.storage.append_log(+ book_id, f"edited {block.type.value} block {block_id}", op="edit_block"+ )+ return block+async def delete_block(self, *, book_id: str, page_id: str, block_id: str) -> bool:page = self.storage.load_page(book_id, page_id)if page is None:@@ -1180,6 +1668,12 @@ class BookEngine:summary=f"Sub-chapter spawned from {parent.title}.",order=len(spine.chapters),)+ # The compiler needs a chapter to plan against, but this one is not part+ # of the book's structure: the spine editor hides it and a rebuild must+ # not resurrect it as a top-level chapter. Same marker pattern as+ # ``auto_overview``.+ chapter.__pydantic_extra__ = chapter.__pydantic_extra__ or {}+ chapter.__pydantic_extra__["deep_dive"] = Truespine.chapters.append(chapter)self.storage.save_spine(spine)@@ -1198,11 +1692,25 @@ class BookEngine:self.storage.save_spine(spine)# Add link from parent → sub+ book.page_count = len(self.storage.list_pages(book_id))+ book.updated_at = time.time()+ self.storage.save_book(book)+parent.links.append(PageLink(target_page_id=sub.id, relation="deepens", label=topic))if block_id:block = parent.block_by_id(block_id)if block is not None:- block.metadata = {**block.metadata, "deep_dive_page_id": sub.id}+ # Keyed by topic: one card offers several, and each can be+ # expanded independently. The old scalar recorded only the+ # first and disabled the others.+ pages_by_topic = dict(block.metadata.get("deep_dive_pages") or {})+ pages_by_topic[topic] = sub.id+ block.metadata = {+ **block.metadata,+ "deep_dive_pages": pages_by_topic,+ # Kept for books written before this change.+ "deep_dive_page_id": block.metadata.get("deep_dive_page_id") or sub.id,+ }self.storage.save_page(parent)# Compile the new page now (blocking, so caller gets ready content)@@ -1216,6 +1724,9 @@ class BookEngine:# ── Quiz attempts (Phase 3) ────────────────────────────────────────+ def _page_to_chapter(self, book_id: str) -> dict[str, str]:+ return {p.id: p.chapter_id for p in self.storage.list_pages(book_id) if p.chapter_id}+async def record_quiz_attempt(self,*,@@ -1224,24 +1735,32 @@ class BookEngine:block_id: str,question_id: str,user_answer: str,- is_correct: bool,+ is_correct: bool | None,) -> Progress:- progress = self.load_progress(book_id)- progress.quiz_attempts.append(- QuizAttempt(- block_id=block_id,- page_id=page_id,- question_id=question_id,- user_answer=user_answer,- is_correct=is_correct,- )+ progress = progress_ops.record_attempt(+ self.load_progress(book_id),+ page_id=page_id,+ block_id=block_id,+ question_id=question_id,+ user_answer=user_answer,+ is_correct=is_correct,+ page_to_chapter=self._page_to_chapter(book_id),)- if not is_correct:- page = self.storage.load_page(book_id, page_id)- if page and page.chapter_id and page.chapter_id not in progress.weak_chapters:- progress.weak_chapters.append(page.chapter_id)- else:- progress.score += 1+ self.storage.save_progress(progress)+ return progress++ # ── Reading position / bookmarks ────────────────────────────────────++ def mark_page_visited(self, *, book_id: str, page_id: str) -> Progress:+ """Remember where the reader is, so they can pick the book back up."""+ progress = self.load_progress(book_id)+ if progress_ops.mark_visited(progress, page_id):+ self.storage.save_progress(progress)+ return progress++ def toggle_page_bookmark(self, *, book_id: str, page_id: str) -> Progress:+ progress = self.load_progress(book_id)+ progress_ops.toggle_bookmark(progress, page_id)self.storage.save_progress(progress)return progress@@ -1253,26 +1772,50 @@ class BookEngine:topic: str,stream: StreamBus | None = None,) -> Block | None:- """Append an extra TEXT + QUIZ block when the user struggles."""+ """Append a pitfall callout + worked explanation + an easier quiz.++ Idempotent per topic: asking twice returns the existing remediation+ rather than stacking a second copy onto the page. Three generated+ blocks per request is expensive enough that a double-click, a retry, or+ a second reader hitting the same wall must not pay for it twice.+ """+ page = self.storage.load_page(book_id, page_id)+ if page is None:+ return None++ clean_topic = (topic or "").strip()+ existing = next(+ (+ block+ for block in page.blocks+ if block.params.get("role") == "remediation"+ and str(block.params.get("topic") or "").strip() == clean_topic+ ),+ None,+ )+ if existing is not None:+ return existing+await self.insert_block(book_id=book_id,page_id=page_id,block_type=BlockType.CALLOUT,- params={"variant": "common_pitfall", "topic": topic},+ params={"variant": "common_pitfall", "topic": clean_topic},stream=stream,)+ # The marker block the idempotency check above looks for.await self.insert_block(book_id=book_id,page_id=page_id,block_type=BlockType.TEXT,- params={"role": "remediation", "topic": topic},+ params={"role": "remediation", "topic": clean_topic},stream=stream,)return await self.insert_block(book_id=book_id,page_id=page_id,block_type=BlockType.QUIZ,- params={"num_questions": 2, "difficulty": "easy", "topic": topic},+ params={"num_questions": 2, "difficulty": "easy", "topic": clean_topic},stream=stream,)diff --git a/deeptutor/book/estimate.py b/deeptutor/book/estimate.pynew file mode 100644index 000000000..9700f200c--- /dev/null+++ b/deeptutor/book/estimate.py@@ -0,0 +1,62 @@+"""+Generation estimates+====================++What a book will cost to build, derived from the Section Architect's own+templates so the number cannot drift away from what actually gets generated.++Confirming a spine kicks off dozens of LLM calls and many minutes of work. The+reader deserves to know roughly what they are approving *before* they approve+it — and, having approved it, to recognise the shape of what comes back.++The API exposes the per-chapter *basis* rather than a single total, so the+editor can keep the estimate live while chapters are being added, removed, or+retyped without a round trip per keystroke.+"""++from __future__ import annotations++from .agents.page_planner import _TEMPLATES_V2+from .models import BlockType, ContentType, depth_scale++# Rough throughput of one block, end to end (prompt + generation + persist).+# Prose blocks dominate; the small structured ones are far quicker.+_SECONDS_PER_PROSE_BLOCK = 45.0+_SECONDS_PER_SUPPORT_BLOCK = 15.0++_PROSE_TYPES = frozenset({BlockType.SECTION, BlockType.TEXT})+++def chapter_basis(depth: str | None = None) -> dict[str, dict[str, float]]:+ """Per-content-type cost of one chapter at *depth*.++ Returns ``{content_type: {"blocks": n, "words": n, "seconds": n}}``.+ """+ scale = depth_scale(depth)+ basis: dict[str, dict[str, float]] = {}++ for content_type, template in _TEMPLATES_V2.items():+ words = 0.0+ seconds = 0.0+ for block_type, params in template:+ target = params.get("target_words")+ if isinstance(target, (int, float)):+ words += float(target) * scale+ seconds += (+ _SECONDS_PER_PROSE_BLOCK+ if block_type in _PROSE_TYPES+ else _SECONDS_PER_SUPPORT_BLOCK+ )+ basis[content_type.value] = {+ "blocks": float(len(template)),+ "words": round(words),+ "seconds": round(seconds),+ }++ # The overview chapter is rendered deterministically from the spine — no+ # LLM, no wait. Reporting it as free is the honest answer.+ basis[ContentType.OVERVIEW.value] = {"blocks": 3.0, "words": 0.0, "seconds": 0.0}+ return basis+++__all__ = ["chapter_basis"]diff --git a/deeptutor/book/event_hub.py b/deeptutor/book/event_hub.pynew file mode 100644index 000000000..0257aac52--- /dev/null+++ b/deeptutor/book/event_hub.py@@ -0,0 +1,78 @@+"""+Book event hub+==============++One long-lived event stream **per book**, owned by the process rather than by+whichever request happened to start the work.++Why this exists+---------------++The Book Engine's unit of work is a *book*, not a request: ``confirm_spine``+returns as soon as the page shells exist, while the compilation it queued keeps+running for minutes afterwards. A bus that is created per request and closed in+the router's ``finally`` therefore drops every background event on the floor —+``StreamBus.emit()`` silently no-ops once the bus is closed, so the whole+"watch your book being written" experience degrades into a frozen page.++The hub inverts the ownership:++- **Producers** (engine, compiler, background worker) publish into+ ``get_book_bus(book_id)``. They never create or close a bus.+- **Consumers** (WebSocket clients) subscribe to that same bus and may come and+ go freely. ``StreamBus.subscribe()`` replays recent history, so a client that+ reconnects mid-compilation catches up instead of waiting for the next event.+- A bus is closed exactly once — when the book is deleted.++Because REST handlers publish into the same place as WebSocket handlers, a book+compiled via REST still streams to anyone watching over WebSocket.+"""++from __future__ import annotations++from deeptutor.core.stream_bus import StreamBus++from .streaming import BookStream++# Enough to replay the tail of an in-flight stage to a reconnecting client+# (a page emits ~2 events per block), without pinning a whole book's event+# log in memory for the lifetime of the process.+BOOK_EVENT_HISTORY_LIMIT = 400++_buses: dict[str, StreamBus] = {}+++def get_book_bus(book_id: str) -> StreamBus:+ """Return the long-lived bus for *book_id*, creating it on first use.++ Safe to call from any coroutine: there is no ``await`` between the lookup+ and the insert, so concurrent callers cannot race into two buses.+ """+ bus = _buses.get(book_id)+ if bus is None:+ bus = StreamBus(max_history=BOOK_EVENT_HISTORY_LIMIT)+ _buses[book_id] = bus+ return bus+++def get_book_stream(book_id: str) -> BookStream:+ """``get_book_bus`` wrapped in the Book-specific emit helpers."""+ return BookStream(get_book_bus(book_id))+++def close_book_bus(book_id: str) -> None:+ """Close and forget the bus for *book_id* (called when a book is deleted).++ Synchronous on purpose — book deletion runs from sync engine and CLI paths.+ """+ bus = _buses.pop(book_id, None)+ if bus is not None:+ bus.mark_closed()+++__all__ = [+ "BOOK_EVENT_HISTORY_LIMIT",+ "get_book_bus",+ "get_book_stream",+ "close_book_bus",+]diff --git a/deeptutor/book/export.py b/deeptutor/book/export.pynew file mode 100644index 000000000..f9df1e8f6--- /dev/null+++ b/deeptutor/book/export.py@@ -0,0 +1,305 @@+"""+Markdown export+===============++Render a compiled book as one self-contained Markdown document.++A generated book that can only be read inside the app it was generated in is+half a deliverable. Markdown is the format that travels: it opens in an editor,+converts to PDF or EPUB with any of the usual tools, and diffs in git.++Every block type gets a text projection. Blocks whose value is inherently+visual (a rendered video, an interactive widget) degrade to their description+plus a pointer rather than being dropped silently — a reader scanning the export+should be able to tell that something was there.+"""++from __future__ import annotations++import re+from typing import Any++from .models import Block, BlockStatus, BlockType, Book, Page, Spine++_SAFE_FILENAME = re.compile(r"[^\w.-]+")++# Structural labels the export adds around generated content. The book's own+# prose is already in its language; these must follow, or a Chinese book exports+# with English scaffolding. Keyed by the same language codes the prompt layer+# uses (deeptutor/services/prompt/language.py), falling back to English.+_LABELS: dict[str, dict[str, str]] = {+ "en": {+ "takeaway": "Key takeaway",+ "answer": "Answer",+ "front": "Front",+ "back": "Back",+ "sources": "Sources",+ "chapters": "Chapters",+ "note": "Note",+ "untitled_book": "Untitled book",+ "untitled_chapter": "Untitled chapter",+ "not_generated": "(This chapter has not been generated yet.)",+ "omitted": "({kind} omitted — it has no text representation.)",+ },+ "zh": {+ "takeaway": "要点",+ "answer": "答案",+ "front": "正面",+ "back": "背面",+ "sources": "来源",+ "chapters": "章节",+ "note": "提示",+ "untitled_book": "未命名书籍",+ "untitled_chapter": "未命名章节",+ "not_generated": "(本章尚未生成。)",+ "omitted": "({kind} 无法用文本表示,已省略。)",+ },+}+++def _labels(language: str | None) -> dict[str, str]:+ code = (language or "en").strip().lower()+ return _LABELS.get(code) or _LABELS.get(code.split("-", 1)[0]) or _LABELS["en"]+++def export_filename(book: Book) -> str:+ """A filesystem- and header-safe ``.md`` name for *book*."""+ stem = _SAFE_FILENAME.sub("-", (book.title or "book").strip()).strip("-")+ return f"{stem or 'book'}.md"+++def _payload_text(payload: dict[str, Any], *keys: str) -> str:+ """First non-empty string among *keys*."""+ for key in keys:+ value = payload.get(key)+ if isinstance(value, str) and value.strip():+ return value.strip()+ return ""+++def _render_section(payload: dict[str, Any], labels: dict[str, str]) -> str:+ parts: list[str] = []+ intro = _payload_text(payload, "intro")+ if intro:+ parts.append(intro)++ subsections = payload.get("subsections")+ if isinstance(subsections, list):+ for sub in subsections:+ if not isinstance(sub, dict):+ continue+ heading = _payload_text(sub, "heading")+ body = _payload_text(sub, "body")+ if heading:+ parts.append(f"### {heading}")+ if body:+ parts.append(body)++ body = _payload_text(payload, "body")+ if body and not subsections:+ parts.append(body)++ takeaway = _payload_text(payload, "key_takeaway")+ if takeaway:+ parts.append(f"> **{labels['takeaway']}** — {takeaway}")+ return "\n\n".join(parts)+++def _render_quiz(payload: dict[str, Any], labels: dict[str, str]) -> str:+ questions = payload.get("questions")+ if not isinstance(questions, list) or not questions:+ return ""+ parts: list[str] = []+ for index, question in enumerate(questions, start=1):+ if not isinstance(question, dict):+ continue+ parts.append(f"**{index}. {_payload_text(question, 'question')}**")+ options = question.get("options")+ if isinstance(options, dict) and options:+ parts.append(+ "\n".join(f"- **{key.upper()}.** {value}" for key, value in options.items())+ )+ answer = _payload_text(question, "correct_answer")+ if answer:+ parts.append(+ f"<details><summary>{labels['answer']}</summary>\n\n{answer}\n\n</details>"+ )+ explanation = _payload_text(question, "explanation")+ if explanation:+ parts.append(f"_{explanation}_")+ return "\n\n".join(parts)+++def _render_flash_cards(payload: dict[str, Any], labels: dict[str, str]) -> str:+ cards = payload.get("cards")+ if not isinstance(cards, list) or not cards:+ return ""+ rows = [f"| {labels['front']} | {labels['back']} |", "| --- | --- |"]+ for card in cards:+ if not isinstance(card, dict):+ continue+ front = _payload_text(card, "front").replace("|", "\\|")+ back = _payload_text(card, "back").replace("|", "\\|")+ rows.append(f"| {front} | {back} |")+ return "\n".join(rows) if len(rows) > 2 else ""+++def _render_timeline(payload: dict[str, Any]) -> str:+ events = payload.get("events")+ if not isinstance(events, list) or not events:+ return ""+ lines: list[str] = []+ for event in events:+ if not isinstance(event, dict):+ continue+ date = _payload_text(event, "date")+ title = _payload_text(event, "title")+ description = _payload_text(event, "description")+ head = " — ".join(part for part in (date, title) if part)+ lines.append(f"- **{head}**" + (f" \n {description}" if description else ""))+ return "\n".join(lines)+++def _render_code(payload: dict[str, Any]) -> str:+ code = _payload_text(payload, "code")+ if not code:+ return ""+ language = _payload_text(payload, "language")+ parts = [f"```{language}\n{code}\n```"]+ explanation = _payload_text(payload, "explanation")+ if explanation:+ parts.append(explanation)+ return "\n\n".join(parts)+++def _render_visual(payload: dict[str, Any], kind: str, labels: dict[str, str]) -> str:+ """Figures, interactives and animations — keep whatever text survives."""+ parts: list[str] = []+ description = _payload_text(payload, "description", "summary")+ if description:+ parts.append(description)++ code = payload.get("code")+ if isinstance(code, dict):+ content = _payload_text(code, "content")+ language = _payload_text(code, "language")+ if content:+ parts.append(f"```{language}\n{content}\n```")+ elif _payload_text(payload, "mermaid"):+ parts.append(f"```mermaid\n{_payload_text(payload, 'mermaid')}\n```")++ video = _payload_text(payload, "video_url")+ if video:+ parts.append(f"[▶ {kind}]({video})")++ if not parts:+ parts.append("_" + labels["omitted"].format(kind=kind) + "_")+ return "\n\n".join(parts)+++def _render_deep_dive(payload: dict[str, Any]) -> str:+ """Suggested follow-up topics.++ The generator emits ``{"topic", "rationale"}`` dicts — never bare strings —+ so a string-only filter matched nothing and dropped the block entirely.+ """+ suggestions = payload.get("suggestions")+ if not isinstance(suggestions, list):+ return ""+ lines: list[str] = []+ for item in suggestions:+ if isinstance(item, str) and item.strip():+ lines.append(f"- {item.strip()}")+ elif isinstance(item, dict):+ topic = _payload_text(item, "topic")+ rationale = _payload_text(item, "rationale")+ if not topic:+ continue+ lines.append(f"- **{topic}**" + (f" — {rationale}" if rationale else ""))+ return "\n".join(lines)+++def render_block(block: Block, language: str = "en") -> str:+ """Markdown for one block, or ``""`` when it has nothing to contribute."""+ if block.status != BlockStatus.READY:+ return ""++ payload = block.payload or {}+ labels = _labels(language)+ bridge = _payload_text(payload, "bridge_text")++ if block.type in (BlockType.TEXT, BlockType.USER_NOTE):+ body = _payload_text(payload, "body", "content")+ elif block.type == BlockType.SECTION:+ body = _render_section(payload, labels)+ elif block.type == BlockType.CALLOUT:+ label = _payload_text(payload, "label")+ text = _payload_text(payload, "body")+ body = f"> **{label or labels['note']}** — {text}" if text else ""+ elif block.type == BlockType.QUIZ:+ body = _render_quiz(payload, labels)+ elif block.type == BlockType.FLASH_CARDS:+ body = _render_flash_cards(payload, labels)+ elif block.type == BlockType.TIMELINE:+ body = _render_timeline(payload)+ elif block.type == BlockType.CODE:+ body = _render_code(payload)+ elif block.type in (BlockType.FIGURE, BlockType.CONCEPT_GRAPH):+ body = _render_visual(payload, "figure", labels)+ elif block.type == BlockType.INTERACTIVE:+ body = _render_visual(payload, "interactive widget", labels)+ elif block.type == BlockType.ANIMATION:+ body = _render_visual(payload, "animation", labels)+ elif block.type == BlockType.DEEP_DIVE:+ body = _render_deep_dive(payload)+ else:+ body = _payload_text(payload, "body", "content")++ if not body:+ return ""++ parts: list[str] = []+ if bridge:+ parts.append(bridge)+ # The overview intro already opens with its own H1.+ if block.title and block.type not in (BlockType.TEXT, BlockType.SECTION):+ parts.append(f"#### {block.title}")+ parts.append(body)+ return "\n\n".join(parts)+++def render_book_markdown(book: Book, spine: Spine | None, pages: list[Page]) -> str:+ """The whole book as one Markdown document."""+ labels = _labels(book.language)+ out: list[str] = [f"# {book.title or labels['untitled_book']}"]++ if book.description:+ out.append(f"*{book.description}*")++ meta: list[str] = []+ if book.knowledge_bases:+ meta.append(f"**{labels['sources']}:** {', '.join(book.knowledge_bases)}")+ if spine and spine.chapters:+ meta.append(f"**{labels['chapters']}:** {len(spine.chapters)}")+ if meta:+ out.append(" · ".join(meta))++ out.append("---")++ for page in sorted(pages, key=lambda p: (p.order, p.created_at)):+ out.append(f"## {page.title or labels['untitled_chapter']}")++ if page.learning_objectives:+ out.append("\n".join(f"- {objective}" for objective in page.learning_objectives))++ rendered = [render_block(block, book.language) for block in page.blocks]+ body = [chunk for chunk in rendered if chunk]+ if body:+ out.extend(body)+ else:+ out.append(f"_{labels['not_generated']}_")++ return "\n\n".join(out).rstrip() + "\n"+++__all__ = ["render_block", "render_book_markdown", "export_filename"]diff --git a/deeptutor/book/kb_health.py b/deeptutor/book/kb_health.pyindex 2972777c6..8484b5ab1 100644--- a/deeptutor/book/kb_health.py+++ b/deeptutor/book/kb_health.py@@ -21,6 +21,24 @@ import refrom deeptutor.knowledge.manager import KnowledgeBaseManager++def _current_manager() -> KnowledgeBaseManager:+ """The KB manager rooted at the *current user's* knowledge bases.++ Constructing ``KnowledgeBaseManager()`` directly picks up its CWD-relative+ default root, which under multi-user points at the wrong workspace (and+ under any deployment where the process CWD isn't the data dir, at nothing).+ ``current_kb_manager`` resolves through PathService like the knowledge and+ subagent routers do.+ """+ try:+ from deeptutor.multi_user.knowledge_access import current_kb_manager++ return current_kb_manager()+ except Exception: # noqa: BLE001 - single-user / bare-SDK fallback+ return KnowledgeBaseManager()++from .models import Bookfrom .storage import BookStorage, get_book_storage@@ -46,7 +64,7 @@ def fingerprint_kb(kb_name: str, manager: KnowledgeBaseManager | None = None) ->Returns ``""`` when the KB does not exist (so callers can detect deletion)."""- mgr = manager or KnowledgeBaseManager()+ mgr = manager or _current_manager()if kb_name not in mgr.list_knowledge_bases():return ""base_dir: Path = mgr.base_dir / kb_name / "raw"@@ -68,7 +86,7 @@ def fingerprint_kb(kb_name: str, manager: KnowledgeBaseManager | None = None) ->def fingerprint_kbs(kb_names: list[str], manager: KnowledgeBaseManager | None = None) -> dict[str, str]:- mgr = manager or KnowledgeBaseManager()+ mgr = manager or _current_manager()return {name: fingerprint_kb(name, manager=mgr) for name in kb_names}diff --git a/deeptutor/book/models.py b/deeptutor/book/models.pyindex 1b1ae4094..3edf333ef 100644--- a/deeptutor/book/models.py+++ b/deeptutor/book/models.py@@ -30,6 +30,10 @@ class BookStatus(str, Enum):DRAFT = "draft" # ideation only, no spine yetSPINE_READY = "spine_ready" # spine confirmed, compilation pendingCOMPILING = "compiling"+ # Compilation stopped itself after repeated provider-level failures (quota+ # exhausted, credentials revoked, provider down). Everything generated so+ # far is intact; ``resume_book`` continues from here.+ PAUSED = "paused"READY = "ready"ERROR = "error"ARCHIVED = "archived"@@ -79,6 +83,35 @@ class BlockType(str, Enum):PROGRESS_DASHBOARD = "progress_dashboard"+class BookDepth(str, Enum):+ """How much prose the reader wants per chapter.++ Scales the ``target_words`` baked into the Section Architect's templates,+ which were previously fixed — a reference book and a weekend primer got the+ same 3,600 words per chapter.+ """++ BRIEF = "brief"+ STANDARD = "standard"+ DEEP = "deep"+++#: Multiplier applied to every template's ``target_words``.+DEPTH_WORD_SCALE: dict[BookDepth, float] = {+ BookDepth.BRIEF: 0.5,+ BookDepth.STANDARD: 1.0,+ BookDepth.DEEP: 1.6,+}+++def depth_scale(depth: str | None) -> float:+ """Word-count multiplier for *depth*, tolerant of unknown values."""+ try:+ return DEPTH_WORD_SCALE[BookDepth(str(depth or "standard"))]+ except (ValueError, KeyError):+ return 1.0++class ContentType(str, Enum):"""Hint that drives Page Planner template selection."""@@ -399,7 +432,10 @@ class QuizAttempt(BaseModel):page_id: strquestion_id: str = ""user_answer: str = ""- is_correct: bool = False+ # ``None`` = revealed but ungraded. Written answers can only be graded by+ # the reader, and folding "not graded" into "wrong" would both understate+ # their score and mark the chapter weak on nothing but a reveal.+ is_correct: bool | None = Nonetimestamp: float = Field(default_factory=_now)@@ -435,6 +471,7 @@ class Book(BaseModel):proposal: BookProposal | None = Noneknowledge_bases: list[str] = Field(default_factory=list)language: str = "en"+ depth: BookDepth = BookDepth.STANDARDpage_count: int = 0chapter_count: int = 0created_at: float = Field(default_factory=_now)@@ -448,6 +485,9 @@ class Book(BaseModel):__all__ = ["BookStatus",+ "BookDepth",+ "DEPTH_WORD_SCALE",+ "depth_scale","PageStatus","BlockStatus","BlockType",diff --git a/deeptutor/book/overview_copy.py b/deeptutor/book/overview_copy.pynew file mode 100644index 000000000..d95129f22--- /dev/null+++ b/deeptutor/book/overview_copy.py@@ -0,0 +1,104 @@+"""Reader-facing copy for the engine-injected Overview chapter.++This one page is built **deterministically** — no LLM call — so its wording+cannot come from the model the way every other block's does. It used to live as+``"中文" if book.language == "zh" else "English"`` conditionals scattered through+``engine.py``, which meant the language picker could offer eleven languages+while the book's own front page only ever spoke two.++Collecting it here does not by itself translate the page, but it turns "add a+language" from an edit across two functions into one entry in this table, and+it makes the gap visible instead of implicit: anything not listed falls back to+English, and :func:`missing_languages` reports what is still owed.+"""++from __future__ import annotations++from typing import Any++# Keys every entry must define. Kept explicit so a partial translation fails+# loudly in tests rather than rendering a stray English string mid-page.+REQUIRED_KEYS = frozenset(+ {+ "chapter_title",+ "chapter_summary",+ "objectives",+ "intro_title",+ "intro_body",+ "untitled_book",+ "concept_map_title",+ "chapter_index_title",+ "chapter_index_heading",+ }+)++_COPY: dict[str, dict[str, Any]] = {+ "en": {+ "chapter_title": "How to read this book",+ "chapter_summary": (+ "Auto-generated overview of the book's concept graph and chapter index."+ ),+ "objectives": [+ "See the full chapter map at a glance",+ "Understand how concepts depend on each other",+ "Pick the reading path that fits your goals",+ ],+ "intro_title": "How to read this book",+ "intro_body": (+ "The diagram below maps the {concepts} core concepts in this book and "+ "how they depend on each other. The chapter index that follows lists "+ "all {chapters} chapters — read top-to-bottom for the recommended "+ "path, or jump straight to whatever you're most curious about."+ ),+ "untitled_book": "This book",+ "concept_map_title": "Concept map",+ "chapter_index_title": "Chapter index",+ "chapter_index_heading": "## Chapter index",+ },+ "zh": {+ "chapter_title": "本书导览",+ "chapter_summary": "自动生成的概念图与章节索引,作为本书的入口。",+ "objectives": [+ "了解整本书的章节脉络",+ "掌握各章之间的概念依赖关系",+ "选择最合适的阅读顺序",+ ],+ "intro_title": "如何阅读这本书",+ "intro_body": (+ "下方的概念图展示了本书 {concepts} 个核心概念以及它们之间的依赖关系;"+ "再下方是 {chapters} 个章节的入口。"+ "你可以按从上到下的顺序阅读,也可以根据自己的兴趣或先验知识选择切入点。"+ ),+ "untitled_book": "本书",+ "concept_map_title": "概念图",+ "chapter_index_title": "章节索引",+ "chapter_index_heading": "## 章节索引",+ },+}+++def overview_copy(language: str | None) -> dict[str, Any]:+ """Copy for *language*, falling back to English (then to the base tag).++ ``zh-tw`` finds no exact entry, tries ``zh``, and only then falls back —+ matching how the prompt layer resolves language tags.+ """+ code = (language or "en").strip().lower()+ return _COPY.get(code) or _COPY.get(code.split("-", 1)[0]) or _COPY["en"]+++def missing_languages(supported: list[str]) -> list[str]:+ """Which of *supported* still render the Overview page in English.++ Not a failure — the page stays readable — but a book generated in a+ language listed here has an English front page in front of prose that is+ not English. Used by tests to keep the gap honest and countable.+ """+ return [+ code+ for code in supported+ if code.strip().lower() not in _COPY and code.strip().lower().split("-", 1)[0] not in _COPY+ ]+++__all__ = ["REQUIRED_KEYS", "missing_languages", "overview_copy"]diff --git a/deeptutor/book/progress.py b/deeptutor/book/progress.pynew file mode 100644index 000000000..a91e55c35--- /dev/null+++ b/deeptutor/book/progress.py@@ -0,0 +1,136 @@+"""+Reading progress+================++Where the reader is in a book, what they have bookmarked, and how they did on+its quizzes.++Pure functions over a :class:`Progress` value — no storage, no engine, no IO.+Two reasons:++- The engine stays a scheduler. Progress is a different concern with different+ rules, and mixing them is what left ``visited_page_ids`` and+ ``bookmarked_page_ids`` declared but never written for the whole life of the+ feature.+- Immersive reading tracks the same three things (position, bookmarks,+ comprehension checks) in its own silo. When those merge, this is the layer+ that generalises, and it can be tested without a filesystem.++Derived, not accumulated+------------------------++``score`` and ``weak_chapters`` are recomputed from the **latest** attempt per+question rather than incremented as attempts arrive. Accumulating meant+re-answering a question you already knew inflated your score, and a chapter+stayed "weak" forever once you had missed anything in it — a progress display+that only ever ratchets one way tells the reader nothing.+"""++from __future__ import annotations++from .models import Progress, QuizAttempt+++def _question_key(attempt: QuizAttempt) -> tuple[str, str]:+ return (attempt.block_id, attempt.question_id)+++def latest_attempts(progress: Progress) -> dict[tuple[str, str], QuizAttempt]:+ """The most recent attempt per question, keyed by (block, question)."""+ latest: dict[tuple[str, str], QuizAttempt] = {}+ for attempt in progress.quiz_attempts:+ key = _question_key(attempt)+ current = latest.get(key)+ if current is None or attempt.timestamp >= current.timestamp:+ latest[key] = attempt+ return latest+++def recompute_score(progress: Progress) -> int:+ """Number of distinct questions currently answered correctly."""+ return sum(1 for a in latest_attempts(progress).values() if a.is_correct is True)+++def recompute_weak_chapters(progress: Progress, page_to_chapter: dict[str, str]) -> list[str]:+ """Chapters holding at least one question whose latest answer was wrong.++ A chapter drops off this list as soon as the reader gets its questions+ right — being wrong once should not brand a chapter permanently.+ """+ weak: set[str] = set()+ for attempt in latest_attempts(progress).values():+ if attempt.is_correct is not False:+ continue+ chapter_id = page_to_chapter.get(attempt.page_id, "")+ if chapter_id:+ weak.add(chapter_id)+ return sorted(weak)+++def record_attempt(+ progress: Progress,+ *,+ page_id: str,+ block_id: str,+ question_id: str,+ user_answer: str,+ is_correct: bool | None,+ page_to_chapter: dict[str, str],+) -> Progress:+ """Append an attempt and refresh everything derived from the set."""+ progress.quiz_attempts.append(+ QuizAttempt(+ block_id=block_id,+ page_id=page_id,+ question_id=question_id,+ user_answer=user_answer,+ is_correct=is_correct,+ )+ )+ progress.score = recompute_score(progress)+ progress.weak_chapters = recompute_weak_chapters(progress, page_to_chapter)+ return progress+++def mark_visited(progress: Progress, page_id: str) -> bool:+ """Record that the reader opened *page_id*. True when anything changed.++ The caller uses the return value to skip a disk write on the common case:+ re-reading a page you have already seen.+ """+ changed = False+ if progress.current_page_id != page_id:+ progress.current_page_id = page_id+ changed = True+ if page_id not in progress.visited_page_ids:+ progress.visited_page_ids.append(page_id)+ changed = True+ return changed+++def toggle_bookmark(progress: Progress, page_id: str) -> bool:+ """Flip *page_id*'s bookmark. Returns whether it is bookmarked now."""+ if page_id in progress.bookmarked_page_ids:+ progress.bookmarked_page_ids.remove(page_id)+ return False+ progress.bookmarked_page_ids.append(page_id)+ return True+++def completion_ratio(progress: Progress, total_pages: int) -> float:+ """Fraction of the book visited, clamped to [0, 1]."""+ if total_pages <= 0:+ return 0.0+ seen = len({p for p in progress.visited_page_ids})+ return min(1.0, seen / total_pages)+++__all__ = [+ "latest_attempts",+ "recompute_score",+ "recompute_weak_chapters",+ "record_attempt",+ "mark_visited",+ "toggle_bookmark",+ "completion_ratio",+]diff --git a/deeptutor/book/prompts/en/animation.yaml b/deeptutor/book/prompts/en/animation.yamlnew file mode 100644index 000000000..12bf4ddfe--- /dev/null+++ b/deeptutor/book/prompts/en/animation.yaml@@ -0,0 +1,10 @@+# Reader-facing brief handed to the shared visualize / animation pipeline.+# Lives here rather than in Python so it follows the book's language like+# every other block's prompt does.+brief: "Create a short Manim animation that walks through the core derivation of \"{chapter_title}\"{focus_clause}. Aim for a clear, step-by-step explanation a learner can follow."++# Quoted on purpose — the English clause needs its leading space.+focus_clause: " focusing on {focus}"++context_summary: "Chapter summary: {chapter_summary}"+context_objectives: "Learning objectives:"diff --git a/deeptutor/book/prompts/en/figure.yaml b/deeptutor/book/prompts/en/figure.yamlnew file mode 100644index 000000000..b5d2177ae--- /dev/null+++ b/deeptutor/book/prompts/en/figure.yaml@@ -0,0 +1,10 @@+# Reader-facing brief handed to the shared visualize / animation pipeline.+# Lives here rather than in Python so it follows the book's language like+# every other block's prompt does.+brief: "Create a {variant} figure for the chapter \"{chapter_title}\"{focus_clause}. The figure should help a learner build intuition about the core relationships covered above."++# Quoted on purpose — the English clause needs its leading space.+focus_clause: " focusing on {focus}"++context_summary: "Chapter summary: {chapter_summary}"+context_objectives: "Learning objectives:"diff --git a/deeptutor/book/prompts/en/interactive.yaml b/deeptutor/book/prompts/en/interactive.yamlnew file mode 100644index 000000000..0d967cb3a--- /dev/null+++ b/deeptutor/book/prompts/en/interactive.yaml@@ -0,0 +1,10 @@+# Reader-facing brief handed to the shared visualize / animation pipeline.+# Lives here rather than in Python so it follows the book's language like+# every other block's prompt does.+brief: "Build an {interaction} HTML page for the chapter \"{chapter_title}\"{focus_clause}. The page should let the learner manipulate state, drag/click controls, or step through a guided demo to internalise the concept."++# Quoted on purpose — the English clause needs its leading space.+focus_clause: " focusing on {focus}"++context_summary: "Chapter summary: {chapter_summary}"+context_objectives: "Learning objectives:"diff --git a/deeptutor/book/prompts/zh/animation.yaml b/deeptutor/book/prompts/zh/animation.yamlnew file mode 100644index 000000000..9afa24e55--- /dev/null+++ b/deeptutor/book/prompts/zh/animation.yaml@@ -0,0 +1,10 @@+# Reader-facing brief handed to the shared visualize / animation pipeline.+# Lives here rather than in Python so it follows the book's language like+# every other block's prompt does.+brief: "创建一段简短的 Manim 动画,逐步讲解\"{chapter_title}\"的核心推导{focus_clause}。目标是让学习者能够跟上的、清晰的分步讲解。"++# Quoted on purpose — the English clause needs its leading space.+focus_clause: ",聚焦于{focus}"++context_summary: "章节摘要:{chapter_summary}"+context_objectives: "学习目标:"diff --git a/deeptutor/book/prompts/zh/figure.yaml b/deeptutor/book/prompts/zh/figure.yamlnew file mode 100644index 000000000..ae48cc1e0--- /dev/null+++ b/deeptutor/book/prompts/zh/figure.yaml@@ -0,0 +1,10 @@+# Reader-facing brief handed to the shared visualize / animation pipeline.+# Lives here rather than in Python so it follows the book's language like+# every other block's prompt does.+brief: "为章节\"{chapter_title}\"创建一张{variant}图示{focus_clause}。这张图应当帮助学习者建立对上述核心关系的直觉理解。"++# Quoted on purpose — the English clause needs its leading space.+focus_clause: ",聚焦于{focus}"++context_summary: "章节摘要:{chapter_summary}"+context_objectives: "学习目标:"diff --git a/deeptutor/book/prompts/zh/interactive.yaml b/deeptutor/book/prompts/zh/interactive.yamlnew file mode 100644index 000000000..91dfbcc6d--- /dev/null+++ b/deeptutor/book/prompts/zh/interactive.yaml@@ -0,0 +1,10 @@+# Reader-facing brief handed to the shared visualize / animation pipeline.+# Lives here rather than in Python so it follows the book's language like+# every other block's prompt does.+brief: "为章节\"{chapter_title}\"构建一个{interaction}式 HTML 页面{focus_clause}。页面应当让学习者能够操作状态、拖拽或点击控件,或跟随引导式演示逐步理解该概念。"++# Quoted on purpose — the English clause needs its leading space.+focus_clause: ",聚焦于{focus}"++context_summary: "章节摘要:{chapter_summary}"+context_objectives: "学习目标:"diff --git a/deeptutor/book/storage.py b/deeptutor/book/storage.pyindex ec6dddb69..5c62bb418 100644--- a/deeptutor/book/storage.py+++ b/deeptutor/book/storage.py@@ -25,6 +25,7 @@ from datetime import datetime, timezoneimport jsonimport loggingfrom pathlib import Path+import reimport shutilfrom typing import Any@@ -46,6 +47,24 @@ def _atomic_write_json(path: Path, payload: Any) -> None:_atomic_write_text(path, text)+_SAFE_ID = re.compile(r"[^A-Za-z0-9_-]")+++def _safe_book_id(book_id: str) -> str:+ """Reduce a caller-supplied id to something that cannot escape its root.++ Book ids arrive in request bodies and are used verbatim as directory names.+ Ids the engine mints are ``bk_<hex>``; anything containing a separator or a+ dot segment is either a bug or an attempt to walk out of the workspace, and+ neither should reach the filesystem. Mirrors the containment rule in+ ``services/storage/attachment_store.py``.+ """+ cleaned = _SAFE_ID.sub("", (book_id or "").strip())+ if not cleaned:+ raise ValueError(f"Invalid book id: {book_id!r}")+ return cleaned++def _read_json(path: Path) -> Any | None:if not path.exists():return None@@ -75,10 +94,10 @@ class BookStorage:# ── Path helpers ─────────────────────────────────────────────────────def book_root(self, book_id: str) -> Path:- return self.path_service.get_book_root(book_id)+ return self.path_service.get_book_root(_safe_book_id(book_id))def ensure_book_root(self, book_id: str) -> Path:- return self.path_service.ensure_book_root(book_id)+ return self.path_service.ensure_book_root(_safe_book_id(book_id))def list_book_ids(self) -> list[str]:root = self.path_service.get_book_dir()diff --git a/deeptutor/capabilities/mastery/binding.py b/deeptutor/capabilities/mastery/binding.pynew file mode 100644index 000000000..85442f989--- /dev/null+++ b/deeptutor/capabilities/mastery/binding.py@@ -0,0 +1,151 @@+"""Moving a live turn from one mastery path to another.++A conversation and a path have independent lifetimes: a path outlives any one+chat, and a chat may work several paths in sequence. The binding between them+is therefore not a property of the session — it is state that has to be changed+in three places at once, and this module is the only thing allowed to change+it:++* **the lease** — exclusion is per path, so leaving one and entering another is+ a handoff, not two independent operations. Released by *turn*, since the path+ a turn began on is not the path it may end on.+* **the session preference** — what the next turn resumes on.+* **the live turn** — what the rest of *this* turn's tool calls operate on,+ applied through a caller-supplied binder so nothing here needs to know what a+ turn context is.++Order matters: release before acquire (one lease row per turn), and persist+only after the acquire succeeds, so a rejected handoff leaves the learner+exactly where they were.+"""++from __future__ import annotations++import asyncio+from collections.abc import Callable+import contextlib+import logging++from deeptutor.learning.identity import sanitize_mastery_path_id++logger = logging.getLogger(__name__)++# Rebinds the running turn to a path id. Injected by the loop capability, which+# is the only layer that holds the turn context.+PathBinder = Callable[[str], None]+++class PathBindingError(RuntimeError):+ """The requested path cannot be entered."""+++async def rebind_active_path(+ *,+ path_id: str,+ session_id: str,+ turn_id: str,+ bind_turn: PathBinder | None,+ require_existing: bool = True,+) -> str:+ """Move this turn (and the conversation) onto ``path_id``.++ Returns the resolved path id. Raises :class:`PathBindingError` when the+ target does not exist or is busy in another conversation.+ """+ from deeptutor.learning.storage import (+ LearningStore,+ PathLeaseConflictError,+ )++ target = sanitize_mastery_path_id(path_id)+ store = LearningStore()+ if require_existing and not await asyncio.to_thread(store.exists, target):+ raise PathBindingError(+ f"No mastery path {path_id!r} exists. Call mastery_paths for the "+ "ids you can switch to, or mastery_build to create one here."+ )++ # One lease row per turn: the old one has to go before the new one can be+ # taken, and both are scoped to this turn so a concurrent conversation on+ # either path is never disturbed.+ released = await asyncio.to_thread(store.release_leases_for_turn, turn_id)+ try:+ await asyncio.to_thread(store.acquire_path_lease, target, session_id, turn_id)+ except PathLeaseConflictError as exc:+ # Put the learner back where they were rather than stranding the turn+ # with no lease at all.+ if released and released != target:+ with contextlib.suppress(Exception):+ await asyncio.to_thread(store.acquire_path_lease, released, session_id, turn_id)+ raise PathBindingError(+ f"Mastery path {target!r} is being tutored in another conversation "+ f"right now (session {exc.lease.session_id!r}). Try again once that "+ "turn finishes."+ ) from exc++ _apply(bind_turn, target)+ await _remember_on_session(session_id, target)+ return target+++async def leave_active_path(+ *,+ session_id: str,+ turn_id: str,+ bind_turn: PathBinder | None,+) -> str:+ """Detach the conversation from any named path.++ The conversation falls back to the scratch path it owns itself — the same+ binding a mastery chat that was never pointed at a path would get — so the+ learner can start something new here without disturbing the course they+ stepped away from.+ """+ from deeptutor.learning.storage import LearningStore++ scratch = sanitize_mastery_path_id(session_id or "default")+ resolved = await rebind_active_path(+ path_id=scratch,+ session_id=session_id,+ turn_id=turn_id,+ bind_turn=bind_turn,+ require_existing=False,+ )+ if session_id:+ # Mark the conversation as the scratch path's owner, the same way an+ # unbound mastery turn resolves it, so deleting the conversation takes+ # the scratch path with it instead of leaving an empty orphan behind.+ # Ownership is sticky in the store, so this can only ever add it.+ await asyncio.to_thread(LearningStore().bind_session, resolved, session_id, owns_path=True)+ # Clear the stored association so the next turn resolves the fallback for+ # itself rather than being pinned to a scratch id that may be renamed.+ await _remember_on_session(session_id, "")+ return resolved+++def _apply(bind_turn: PathBinder | None, path_id: str) -> None:+ if bind_turn is not None:+ bind_turn(path_id)+++async def _remember_on_session(session_id: str, path_id: str) -> None:+ """Persist the association so the next turn resumes on the same path.++ Best-effort: the handoff itself has already happened, and a conversation+ that forgets its path merely falls back to its own scratch path next turn.+ """+ if not session_id:+ return+ try:+ from deeptutor.services.session import get_session_store++ await get_session_store().update_session_preferences(+ session_id, {"mastery_path_id": path_id}+ )+ except Exception:+ logger.warning(+ "Failed to persist mastery path %r on session %s", path_id, session_id, exc_info=True+ )+++__all__ = ["PathBindingError", "leave_active_path", "rebind_active_path"]diff --git a/deeptutor/capabilities/mastery/capability.py b/deeptutor/capabilities/mastery/capability.pyindex 123951b89..c71af3e04 100644--- a/deeptutor/capabilities/mastery/capability.py+++ b/deeptutor/capabilities/mastery/capability.py@@ -2,11 +2,14 @@There is no bespoke state machine here anymore. The chat agent loop IS thetutor: this capability only marks the turn as mastery mode and resolves the-active path id, then runs the standard agentic chat pipeline. The pipeline-mounts the mastery tools (``mastery_status`` / ``mastery_quiz`` /-``mastery_grade`` / ``mastery_assess`` / ``mastery_build``) and injects the-tutor playbook; the pure engine in :mod:`deeptutor.learning` owns the hard,-per-type mastery gate and the spaced-repetition arithmetic.+*initial* active path id, then runs the standard agentic chat pipeline. The+pipeline mounts the mastery tools — the gate tools (``mastery_status`` /+``mastery_quiz`` / ``mastery_grade`` / ``mastery_assess`` / ``mastery_build``)+and the binding tools (``mastery_paths`` / ``mastery_switch`` /+``mastery_leave``), through which the tutor can move the conversation between+paths mid-turn — and injects the tutor playbook; the pure engine in+:mod:`deeptutor.learning` owns the hard, per-type mastery gate and the+spaced-repetition arithmetic.Design axiom (shared with chat): the intelligence lives at the loop's exit —the model decides what to teach and how to question — while the gate that@@ -90,14 +93,10 @@ class MasteryPathCapability(BaseCapability):try:await pipeline.run(context, stream)finally:+ # Released by turn: ``mastery_switch`` may have moved this turn onto+ # a different path since the lease was taken.with contextlib.suppress(Exception):- await asyncio.shield(- asyncio.to_thread(- store.release_path_lease,- binding.path_id,- turn_id=turn_id,- )- )+ await asyncio.shield(asyncio.to_thread(store.release_leases_for_turn, turn_id))__all__ = ["MasteryPathCapability", "resolve_mastery_path_id"]diff --git a/deeptutor/capabilities/mastery/loop.py b/deeptutor/capabilities/mastery/loop.pyindex 0e44bc402..cdf31854c 100644--- a/deeptutor/capabilities/mastery/loop.py+++ b/deeptutor/capabilities/mastery/loop.py@@ -1,10 +1,23 @@-"""Mastery path loop-capability hooks."""+"""Mastery path loop-capability hooks.++The pause/resume hooks commit against **the path's one open interaction**, not+against the question id printed on the ``ask_user`` card. The engine allows a+single open question per path, so that interaction is unambiguous — while the+card's id is only as trustworthy as the round it was built in: a model may emit+``mastery_quiz`` and ``ask_user`` in the *same* round, and every tool call in a+round has its arguments bound before any of them runs. In that case nothing is+persisted yet when ``ask_user`` is bound, so the card keeps the model's own id+and ``_bind_pending_ask_user_args`` has nothing to rebind it to. Treating that+id as authoritative used to abort the whole turn on a mismatch.+"""from __future__ import annotationsimport asyncio+from collections.abc import Callablefrom importlib import resourcesimport logging+import refrom typing import Anyfrom deeptutor.capabilities.mastery.tools import MASTERY_TOOL_NAMES@@ -13,6 +26,59 @@ from deeptutor.core.context import UnifiedContextlogger = logging.getLogger(__name__)+# Tools that may move the turn onto a different path, and so need a handle on+# the live binding rather than just the path id it started with.+_PATH_BINDING_TOOLS = frozenset({"mastery_switch", "mastery_leave"})+++# The generic ask_user contract asks the model to mark a suggested choice with+# a "(Recommended)" suffix — good for a preference card, disastrous on a quiz,+# where the model attaches it to the answer it wants picked. Mastery cards are+# assessments, so the marker is stripped structurally rather than merely+# forbidden in the prompt.+_RECOMMENDATION_SUFFIX = re.compile(+ r"[\s ]*[((]\s*(?:推荐|建议|recommended|recommend)\s*[))][\s ]*$",+ re.IGNORECASE,+)+++def _without_recommendation(text: Any) -> Any:+ if not isinstance(text, str):+ return text+ return _RECOMMENDATION_SUFFIX.sub("", text).strip()+++def _strip_answer_hints(kwargs: dict[str, Any]) -> dict[str, Any]:+ """Remove "recommended" markers from every option on an ask_user card."""+ questions = kwargs.get("questions")+ if not isinstance(questions, list):+ return kwargs+ cleaned_questions: list[Any] = []+ for question in questions:+ if not isinstance(question, dict):+ cleaned_questions.append(question)+ continue+ options = question.get("options")+ if not isinstance(options, list):+ cleaned_questions.append(question)+ continue+ cleaned_questions.append(+ {+ **question,+ "options": [+ {+ **option,+ "label": _without_recommendation(option.get("label")),+ "description": _without_recommendation(option.get("description")),+ }+ if isinstance(option, dict)+ else _without_recommendation(option)+ for option in options+ ],+ }+ )+ return {**kwargs, "questions": cleaned_questions}+def _bind_pending_ask_user_args(kwargs: dict[str, Any], path_id: str) -> dict[str, Any]:"""Replace model-authored quiz display data with persisted public state.@@ -80,12 +146,20 @@ class MasteryLoopCapability:return kwargspath_id = str(context.metadata.get("mastery_path_id") or "").strip()if tool_name == "ask_user":- return _bind_pending_ask_user_args(kwargs, path_id)+ # Strip hints last, so a card rebound from persisted state is+ # cleaned too — the persisted options were model-authored as well.+ return _strip_answer_hints(_bind_pending_ask_user_args(kwargs, path_id))if tool_name in MASTERY_TOOL_NAMES:updated = dict(kwargs)updated["_mastery_path_id"] = path_idupdated["_session_id"] = str(context.session_id or "").strip()updated["_turn_id"] = str(context.metadata.get("turn_id") or "").strip()+ if tool_name in _PATH_BINDING_TOOLS:+ # The narrowest possible handle on the turn: "point it at this+ # path". A tool that can switch paths has to change what the+ # rest of the turn operates on, and this keeps the tool from+ # needing to know a turn context exists.+ updated["_bind_active_path"] = _path_binder(context)return updatedreturn kwargs@@ -99,16 +173,15 @@ class MasteryLoopCapability:ask_user: dict[str, Any],) -> None:"""Commit ``awaiting_input`` before the runtime begins waiting."""+ _ = ask_userpath_id = str(context.metadata.get("mastery_path_id") or "").strip()- question_id = _first_question_id(ask_user)- if not path_id or not question_id:+ if not path_id:returnfrom deeptutor.learning.service import LearningServiceawait asyncio.to_thread(LearningService().mark_question_awaiting,path_id,- interaction_id=question_id,session_id=str(context.session_id or ""),turn_id=str(context.metadata.get("turn_id") or ""),)@@ -123,26 +196,47 @@ class MasteryLoopCapability:) -> None:"""Commit the learner answer before giving it back to the LLM."""path_id = str(context.metadata.get("mastery_path_id") or "").strip()- question_id = _first_question_id(ask_user)- if not path_id or not question_id:+ if not path_id:return- answer = reply_text- for entry in answers or []:- if entry.get("questionId") == question_id:- answer = entry.get("text", "")- breakfrom deeptutor.learning.service import LearningServiceawait asyncio.to_thread(LearningService().record_question_answer,path_id,- answer,- interaction_id=question_id,+ _answer_from_reply(ask_user, reply_text=reply_text, answers=answers),session_id=str(context.session_id or ""),turn_id=str(context.metadata.get("turn_id") or ""),)+def _path_binder(context: UnifiedContext) -> Callable[[str], None]:+ """Return the callback that repoints ``context`` at another path."""++ def bind(path_id: str) -> None:+ context.metadata["mastery_path_id"] = path_id++ return bind+++def _answer_from_reply(+ ask_user: dict[str, Any],+ *,+ reply_text: str,+ answers: list[dict[str, str]] | None,+) -> str:+ """The learner's reply to the card, by the id the card was rendered with.++ That id is a *display* concern — the frontend echoes back whatever it was+ shown — and is deliberately not used to pick the interaction to commit+ against (see the module docstring).+ """+ card_question_id = _first_question_id(ask_user)+ for entry in answers or []:+ if entry.get("questionId") == card_question_id:+ return entry.get("text", "")+ return reply_text++def _first_question_id(ask_user: dict[str, Any]) -> str:questions = ask_user.get("questions") or []if not isinstance(questions, list):diff --git a/deeptutor/capabilities/mastery/prompts/en/system.md b/deeptutor/capabilities/mastery/prompts/en/system.mdindex 187bbeeeb..b3ec15c20 100644--- a/deeptutor/capabilities/mastery/prompts/en/system.md+++ b/deeptutor/capabilities/mastery/prompts/en/system.md@@ -11,4 +11,8 @@ Then act on the objective:- `review`: a spaced-repetition item is due — quiz it again to refresh it.- `complete`: congratulate the learner and summarise what they have mastered.+A path outlives any one conversation. When the learner asks what they are studying or what they have finished, list everything with `mastery_paths`. When they want to start or return to a particular one, `mastery_switch` to it and then call `mastery_status` again. When they want to set the course aside and work on something else, `mastery_leave` — the path keeps every bit of its progress and can be resumed later.++Questions must discriminate: test whether the learner can tell things apart and apply them, never whether they can recite a definition back. Every distractor should encode a specific, plausible misconception, and match the correct option in length, specificity, and phrasing. **Never** hint at the answer — no "(Recommended)" markers on options, no writing the correct one longer or more complete than the rest, no ordering by correctness. This is an assessment, not a preference card.+Teach from the learner's own materials when available. Keep each turn focused on one objective. Be warm and encouraging, but hold the bar — clearing the gate is the point, not moving fast.diff --git a/deeptutor/capabilities/mastery/prompts/zh/system.md b/deeptutor/capabilities/mastery/prompts/zh/system.mdindex 66e112ec1..452e5146b 100644--- a/deeptutor/capabilities/mastery/prompts/zh/system.md+++ b/deeptutor/capabilities/mastery/prompts/zh/system.md@@ -11,4 +11,8 @@- `review`:有到期的间隔复习项——再考一次以巩固。- `complete`:祝贺学习者并总结其已掌握的内容。+一条精通之路的寿命长于任何一次对话。学习者问「我在学什么 / 哪些已经学完」时用 `mastery_paths` 列出全部路径及其进度;学习者想开始或回到某条路径时用 `mastery_switch` 切过去(之后立刻再调 `mastery_status`);学习者说这门先放一放、想聊点别的时用 `mastery_leave` 脱离——路径进度分毫不失,随时可以再切回来。++出题必须有区分度:考的是能否辨析与应用,而不是复述定义原话;每个干扰项都要对应一种具体的常见误解,并且与正确项在长度、具体程度、措辞风格上相当。**绝不**以任何方式暗示答案——不给选项加「(推荐)」这类标记,不把正确项写得更长更完整,也不按正确性排序。这是考核,不是选择偏好。+有材料时优先用学习者自己的材料来教。每一轮聚焦一个知识点。态度温暖鼓励,但守住门槛——目标是达成掌握,而非求快。diff --git a/deeptutor/capabilities/mastery/tools.py b/deeptutor/capabilities/mastery/tools.pyindex c6180ab19..6dc55ebfb 100644--- a/deeptutor/capabilities/mastery/tools.py+++ b/deeptutor/capabilities/mastery/tools.py@@ -66,6 +66,9 @@ MASTERY_TOOL_NAMES: tuple[str, ...] = ("mastery_grade","mastery_assess","mastery_build",+ "mastery_paths",+ "mastery_switch",+ "mastery_leave",)_QUESTION_TYPES = ("choice", "short", "open")@@ -719,6 +722,151 @@ class MasteryBuildTool(BaseTool):)+class MasteryPathsTool(BaseTool):+ """List every path the learner owns and which one this turn is on."""++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="mastery_paths",+ description=(+ "List every mastery path this learner has — name, how many "+ "objectives are mastered vs still being learned, reviews due, "+ "and which one this conversation is currently on. Use it when "+ "the learner asks what they are studying or what is finished, "+ "or before mastery_switch, to find the id to switch to."+ ),+ parameters=[],+ )++ async def execute(self, **kwargs: Any) -> ToolResult:+ service = _new_service()+ active = _resolve_path_id(kwargs)+ overviews = await asyncio.to_thread(service.list_path_overviews)+ # A path with no objectives is one nobody has built yet; listing it+ # would offer the model an id that teaches nothing.+ paths = [+ {**overview, "active": overview["path_id"] == active}+ for overview in overviews+ if overview["objectives"] > 0+ ]+ return _json_result(+ {+ "active_path_id": active,+ "paths": paths,+ "instruction": (+ "Switch with mastery_switch(path_id=...) — it takes effect "+ "from your next round, so call mastery_status afterwards."+ ),+ },+ meta_key="mastery_paths",+ )+++class MasterySwitchTool(BaseTool):+ """Point this conversation at a different mastery path."""++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="mastery_switch",+ description=(+ "Put this conversation on a different mastery path — use it to "+ "enter a path the learner names, or to move from the current "+ "one to another. The path keeps all of its own progress; the "+ "conversation simply follows it from now on, including on "+ "later turns. Call mastery_paths first for valid ids, and "+ "mastery_status afterwards to see where the new path stands."+ ),+ parameters=[+ ToolParameter(+ name="path_id",+ type="string",+ description="Path id from mastery_paths (verbatim).",+ )+ ],+ )++ async def execute(self, **kwargs: Any) -> ToolResult:+ from deeptutor.capabilities.mastery.binding import (+ PathBindingError,+ rebind_active_path,+ )++ requested = str(kwargs.get("path_id") or "").strip()+ if not requested:+ return ToolResult(+ content="mastery_switch needs a path_id; call mastery_paths for the ids.",+ success=False,+ )+ previous = _resolve_path_id(kwargs)+ try:+ active = await rebind_active_path(+ path_id=requested,+ session_id=_resolve_session_id(kwargs),+ turn_id=_resolve_turn_id(kwargs),+ bind_turn=kwargs.get("_bind_active_path"),+ )+ except PathBindingError as exc:+ return ToolResult(content=str(exc), success=False)+ return _json_result(+ {+ "status": "switched",+ "previous_path_id": previous,+ "active_path_id": active,+ "instruction": (+ "This conversation now follows that path, on this turn and "+ "later ones. Call mastery_status to see where it stands."+ ),+ },+ meta_key="mastery_switch",+ )+++class MasteryLeaveTool(BaseTool):+ """Detach this conversation from the named path it was following."""++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="mastery_leave",+ description=(+ "Stop following the current mastery path in this conversation. "+ "The path keeps every bit of its progress and can be resumed "+ "any time with mastery_switch; this conversation falls back to "+ "a scratch path of its own, so the learner can start something "+ "new here. Use it when the learner says they are done with the "+ "course for now, or wants to work on something unrelated."+ ),+ parameters=[],+ )++ async def execute(self, **kwargs: Any) -> ToolResult:+ from deeptutor.capabilities.mastery.binding import (+ PathBindingError,+ leave_active_path,+ )++ previous = _resolve_path_id(kwargs)+ try:+ active = await leave_active_path(+ session_id=_resolve_session_id(kwargs),+ turn_id=_resolve_turn_id(kwargs),+ bind_turn=kwargs.get("_bind_active_path"),+ )+ except PathBindingError as exc:+ return ToolResult(content=str(exc), success=False)+ return _json_result(+ {+ "status": "left",+ "previous_path_id": previous,+ "active_path_id": active,+ "instruction": (+ "That path is untouched and resumable with mastery_switch. "+ "This conversation is now on its own scratch path."+ ),+ },+ meta_key="mastery_leave",+ )++def _parse_modules(raw_modules: Any, path_id: str, offset: int) -> tuple[list[LearningModule], str | None]:@@ -770,15 +918,21 @@ MASTERY_TOOL_TYPES: tuple[type[BaseTool], ...] = (MasteryGradeTool,MasteryAssessTool,MasteryBuildTool,+ MasteryPathsTool,+ MasterySwitchTool,+ MasteryLeaveTool,)__all__ = ["MASTERY_TOOL_NAMES","MASTERY_TOOL_TYPES",- "MasteryStatusTool",- "MasteryQuizTool",- "MasteryGradeTool","MasteryAssessTool","MasteryBuildTool",+ "MasteryGradeTool",+ "MasteryLeaveTool",+ "MasteryPathsTool",+ "MasteryQuizTool",+ "MasteryStatusTool",+ "MasterySwitchTool",]diff --git a/deeptutor/core/agentic/tool_dispatch.py b/deeptutor/core/agentic/tool_dispatch.pyindex c9acf2a86..33146924f 100644--- a/deeptutor/core/agentic/tool_dispatch.py+++ b/deeptutor/core/agentic/tool_dispatch.py@@ -46,6 +46,13 @@ logger = logging.getLogger(__name__)MAX_PARALLEL_TOOL_CALLS = 8+# Tools that pause the turn to show the user something. They run *after* the+# rest of their round and re-bind their arguments against whatever those calls+# committed: a model that poses a question and shows it in one round would+# otherwise have its card bound before the question existed, so the card could+# not carry the persisted version of it.+PAUSE_LAST_TOOLS = frozenset({"ask_user"})+KwargAugmenter = Callable[[str, dict[str, Any], UnifiedContext], dict[str, Any]]RetrieveMetaFactory = Callable[[dict[str, Any], str, dict[str, Any]], dict[str, Any] | None]@@ -107,7 +114,7 @@ async def dispatch_tool_calls()tool_calls = tool_calls[:MAX_PARALLEL_TOOL_CALLS]- prepared = _prepare_tool_args(tool_calls, context, kwarg_augmenter)+ prepared, raw_args = _prepare_tool_args(tool_calls, context, kwarg_augmenter)# Collapse duplicates within this parallel batch. Models occasionally# emit repeated tool_calls in one assistant message. For most tools,# "duplicate" means same tool + same JSON-normalised args. For@@ -194,7 +201,27 @@ async def dispatch_tool_calls(retrieve_label=retrieve_label,)- results = await asyncio.gather(*[_run_one(i) for i in range(len(prepared))])+ # Pausing tools go last, and re-bind first: their whole job is to show the+ # user the state of the round, which does not exist until the round has+ # run. Everything else still runs concurrently, and a pause costs no+ # parallelism worth keeping — the turn is about to stop and wait anyway.+ deferred = [index for index, (_, name, _) in enumerate(prepared) if name in PAUSE_LAST_TOOLS]+ if deferred:+ immediate = [index for index in range(len(prepared)) if index not in set(deferred)]+ by_index = dict(+ zip(immediate, await asyncio.gather(*[_run_one(i) for i in immediate]), strict=True)+ )+ for index in deferred:+ if kwarg_augmenter is None or duplicate_of.get(index) is not None:+ continue+ call_id, name, _stale = prepared[index]+ prepared[index] = (call_id, name, kwarg_augmenter(name, raw_args[index], context))+ by_index.update(+ zip(deferred, await asyncio.gather(*[_run_one(i) for i in deferred]), strict=True)+ )+ results = [by_index[index] for index in range(len(prepared))]+ else:+ results = await asyncio.gather(*[_run_one(i) for i in range(len(prepared))])return await _collect_outcome(prepared=prepared,@@ -347,8 +374,14 @@ def _prepare_tool_args(tool_calls: list[dict[str, Any]],context: UnifiedContext,kwarg_augmenter: KwargAugmenter | None,-) -> list[tuple[str, str, dict[str, Any]]]:+) -> tuple[list[tuple[str, str, dict[str, Any]]], list[dict[str, Any]]]:+ """Bind each call's execution args, keeping the model's originals.++ The originals are what a deferred re-bind starts from, so re-binding is+ exactly as idempotent as the first bind (see :data:`PAUSE_LAST_TOOLS`).+ """prepared: list[tuple[str, str, dict[str, Any]]] = []+ raw_args: list[dict[str, Any]] = []for tc in tool_calls:tool_name = str(tc.get("name") or "").strip()tool_call_id = str(tc.get("id") or "").strip()@@ -365,7 +398,8 @@ def _prepare_tool_args(else dict(tool_args))prepared.append((tool_call_id, tool_name, exec_args))- return prepared+ raw_args.append(dict(tool_args))+ return prepared, raw_argsdef _build_per_tool_trace_meta(diff --git a/deeptutor/core/stream_bus.py b/deeptutor/core/stream_bus.pyindex a1dbf2b7b..13b0a4435 100644--- a/deeptutor/core/stream_bus.py+++ b/deeptutor/core/stream_bus.py@@ -31,17 +31,23 @@ from .trace import merge_trace_metadataclass StreamBus:"""Fan-out async event bus for a single chat turn."""- def __init__(self) -> None:+ def __init__(self, *, max_history: int | None = None) -> None:self._subscribers: list[asyncio.Queue[StreamEvent | None]] = []self._closed = Falseself._history: list[StreamEvent] = []self._input_listeners: list[asyncio.Queue[str]] = []+ # ``None`` keeps the full history (turn-scoped buses live and die with+ # one turn). Long-lived buses pass a bound so replay stays useful+ # without growing without limit.+ self._max_history = max_historyasync def emit(self, event: StreamEvent) -> None:"""Push *event* to every active subscriber."""if self._closed:returnself._history.append(event)+ if self._max_history is not None and len(self._history) > self._max_history:+ del self._history[: len(self._history) - self._max_history]for q in self._subscribers:await q.put(event)@@ -67,11 +73,20 @@ class StreamBus:finally:self._subscribers.remove(q)- async def close(self) -> None:- """Signal all subscribers that the stream is finished."""+ def mark_closed(self) -> None:+ """Synchronous ``close()``.++ Safe because subscriber queues are unbounded, so handing them the+ sentinel never blocks. Lets synchronous call sites (engine teardown,+ CLI paths) shut a bus down without an event loop.+ """self._closed = Truefor q in self._subscribers:- await q.put(None)+ q.put_nowait(None)++ async def close(self) -> None:+ """Signal all subscribers that the stream is finished."""+ self.mark_closed()# ---- convenience helpers for producers ----diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.pyindex 5cdb2329e..27bba1720 100644--- a/deeptutor/knowledge/manager.py+++ b/deeptutor/knowledge/manager.py@@ -893,10 +893,16 @@ class KnowledgeBaseManager:Like the other connected types this creates no folder under ``base_dir``and runs no index pipeline: it records a ``type: ima`` entry whose- credentials and library id the ``ima`` provider queries over IMA's- OpenAPI. IMA owns indexing entirely. Callers should validate the binding- with the probe helper first; this only guards basic invariants. Raises- ``ValueError`` on a missing field or a name clash.+ library id the ``ima`` provider queries over IMA's OpenAPI. IMA owns+ indexing entirely.++ Credentials are optional here: leave them empty and the KB retrieves+ with the account-level pair from the engine settings, so rotating that+ key updates every such KB at once. Passing a pair pins this KB to it —+ the way to reach a second IMA account. Callers should validate the+ binding with the probe helper first; this only guards basic invariants.+ Raises ``ValueError`` on a missing field, a half-filled credential pair,+ or a name clash."""name = (name or "").strip()client_id = (client_id or "").strip()@@ -904,8 +910,8 @@ class KnowledgeBaseManager:knowledge_base_id = (knowledge_base_id or "").strip()if not name:raise ValueError("Knowledge base name is required.")- if not client_id or not api_key:- raise ValueError("IMA Client ID and API Key are required.")+ if bool(client_id) != bool(api_key):+ raise ValueError("IMA Client ID and API Key must be given together.")if not knowledge_base_id:raise ValueError("IMA knowledge base ID is required.")@@ -919,8 +925,9 @@ class KnowledgeBaseManager:"path": name,"type": IMA_KB_TYPE,"rag_provider": IMA_PROVIDER,- "client_id": client_id,- "api_key": api_key,+ # Written only when this KB overrides the account credentials;+ # absent means "resolve them from the engine settings".+ **({"client_id": client_id, "api_key": api_key} if client_id else {}),"knowledge_base_id": knowledge_base_id,"description": description or f"Tencent IMA: {name}","status": "ready",diff --git a/deeptutor/learning/policy.py b/deeptutor/learning/policy.pyindex 9bc2943f1..93e8a1702 100644--- a/deeptutor/learning/policy.py+++ b/deeptutor/learning/policy.py@@ -280,6 +280,74 @@ def map_summary(progress: LearningProgress, *, now: float | None = None) -> dict}+def objective_report(progress: LearningProgress, kp_id: str) -> dict | None:+ """Everything the engine knows about one objective, for review.++ ``map_summary`` stays deliberately thin because the tutor reads it on every+ turn; this is the opposite trade — the whole evidence trail behind a single+ objective, read only when someone opens it. ``None`` when *kp_id* is not on+ the path.+ """+ kp, module_id, module_name = find_knowledge_point(progress, kp_id)+ if kp is None:+ return None++ attempts = [+ {+ "question_id": attempt.question_id,+ "is_correct": attempt.is_correct,+ "answer": str(attempt.user_answer or ""),+ "error_type": attempt.error_type.value if attempt.error_type else "",+ "at": attempt.timestamp,+ }+ for attempt in progress.quiz_attempts+ if attempt.knowledge_point_id == kp_id+ ]+ state = progress.repetition_states.get(kp_id)+ due_at = next(+ (task.due_at for task in progress.review_queue if task.knowledge_point_id == kp_id),+ None,+ )+ return {+ "id": kp.id,+ "name": kp.name,+ "type": kp.type.value,+ "module_id": module_id,+ "module_name": module_name,+ "status": objective_status(progress, kp),+ "gate": _gate_kind(kp),+ "mastered": is_mastered(progress, kp),+ "mastery": round(display_mastery(progress, kp), 3),+ "threshold": round(gate_threshold(kp.type), 3),+ "attempts": attempts,+ "correct_count": sum(1 for attempt in attempts if attempt["is_correct"]),+ # The learner's own words, kept as the evidence behind a qualitative pass.+ "explanation": progress.feynman_explanations.get(kp_id, ""),+ "review": (+ {+ "due_at": due_at,+ "interval_index": state.interval_index,+ "consecutive_correct": state.consecutive_correct,+ "consecutive_wrong": state.consecutive_wrong,+ }+ if state is not None+ else None+ ),+ "errors": [+ {+ "id": record.id,+ "error_type": record.error_type.value,+ "status": record.status,+ "self_attribution": record.self_attribution,+ "retries": len(record.retry_history),+ "created_at": record.created_at,+ }+ for record in progress.error_records+ if record.knowledge_point_id == kp_id+ ],+ }++__all__ = ["QUANTITATIVE_GATE","QUALITATIVE_TYPES",@@ -288,6 +356,7 @@ __all__ = ["is_mastered","display_mastery","objective_status",+ "objective_report","due_reviews","find_knowledge_point","next_objective",diff --git a/deeptutor/learning/service.py b/deeptutor/learning/service.pyindex 8e95e132a..d8ac93032 100644--- a/deeptutor/learning/service.py+++ b/deeptutor/learning/service.py@@ -644,6 +644,38 @@ class LearningService:progress, _ = self._store.mutate(book_id, replace, create=True)return progress+ def abandon_active_question(self, book_id: str) -> tuple[LearningProgress, bool]:+ """Drop the outstanding question so the path can move on.++ A posed question outranks everything in ``policy.next_objective`` and+ blocks ``register_question`` from posing another, which is what keeps+ the gate honest — but it also means a question the learner can no+ longer answer (its conversation is gone, the card was never shown)+ would stall the path with no way out short of resetting all progress.+ Abandoning is deliberately explicit rather than automatic: an+ unanswered question is normally resumable across turns, so only the+ learner can say this one is not.++ Returns the progress and whether anything was outstanding.+ """++ def abandon(tx):+ interaction = tx.active_interaction()+ abandoned = tx.abandon_active_interactions() > 0+ if tx.progress.pending_question is not None:+ tx.progress.pending_question = None+ abandoned = True+ if not abandoned:+ return False+ tx.touch()+ tx.emit(+ "interaction.abandoned",+ {"interaction_id": interaction.interaction_id if interaction else ""},+ )+ return True++ return self._store.mutate(book_id, abandon)+def reset_path(self, book_id: str) -> LearningProgress:def reset(tx):progress = tx.progress@@ -764,6 +796,48 @@ class LearningService:progress.review_queue = scheduler.build_review_queue(progress)progress.updated_at = time.time()+ def list_path_overviews(self) -> list[dict]:+ """Gate-accurate one-line state for every path the learner owns.++ ``list_progress`` reports an *average* mastery percentage, which is the+ right number for a progress bar and the wrong one for deciding what is+ finished: mastery is a per-objective gate, so "3 of 4 cleared" is the+ fact, and an average can sit at 75% with nothing actually mastered.+ This reports the counts the gate itself produces.+ """+ from deeptutor.learning import policy++ overviews: list[dict] = []+ for path_id in self._store.list_all():+ try:+ progress = self._store.load(path_id)+ except Exception:+ logging.getLogger(__name__).warning(+ "Failed to load mastery path %s for overview", path_id, exc_info=True+ )+ continue+ if progress is None:+ continue+ summary = policy.map_summary(progress)+ counts = summary["counts"]+ overviews.append(+ {+ "path_id": progress.book_id,+ "name": (progress.modules[0].name if progress.modules else "")+ or progress.book_id,+ "objectives": counts["total"],+ "mastered": counts["mastered"],+ "learning": counts["learning"],+ "not_started": counts["new"],+ "due_reviews": summary["due_reviews"],+ "complete": summary["complete"],+ "open_question": progress.pending_question is not None,+ "updated_at": progress.updated_at,+ }+ )+ overviews.sort(key=lambda overview: overview["updated_at"], reverse=True)+ return overviews+def list_progress(self) -> dict:"""Return summary of all book progress with per-book error info."""logger = logging.getLogger(__name__)diff --git a/deeptutor/learning/storage.py b/deeptutor/learning/storage.pyindex 7c9f190f1..0ee04b320 100644--- a/deeptutor/learning/storage.py+++ b/deeptutor/learning/storage.py@@ -168,7 +168,7 @@ class LearningTransaction:SELECT * FROM mastery_interactionsWHERE path_id = ? AND status IN ({placeholders})ORDER BY created_at DESC LIMIT 1- """,+ """, # nosec B608 - placeholders is a generated "?,?" list; every value is bound(self.progress.book_id, *_ACTIVE_INTERACTION_STATES),).fetchone()return self._interaction_from_row(row)@@ -230,7 +230,7 @@ class LearningTransaction:UPDATE mastery_interactionsSET status = ?, updated_at = ?WHERE path_id = ? AND status IN ({placeholders})- """,+ """, # nosec B608 - placeholders is a generated "?,?" list; every value is bound(InteractionStatus.ABANDONED.value,time.time(),@@ -888,6 +888,27 @@ class LearningStore:path_id=path_id, session_id=session_id, turn_id=turn_id, acquired_at=now)+ def release_leases_for_turn(self, turn_id: str) -> str:+ """Release whatever path *turn_id* currently holds; return that path id.++ ``turn_id`` is unique across the lease table, so a turn holds at most+ one path — which makes this the only release that stays correct when a+ turn changes paths mid-flight. Releasing by the path id the turn *began*+ with would free the wrong one and leak the other.+ """+ turn_id = str(turn_id or "").strip()+ if not turn_id:+ return ""+ with self._connect() as conn:+ row = conn.execute(+ "SELECT path_id FROM mastery_path_leases WHERE turn_id = ?", (turn_id,)+ ).fetchone()+ if row is None:+ return ""+ conn.execute("DELETE FROM mastery_path_leases WHERE turn_id = ?", (turn_id,))+ conn.commit()+ return str(row["path_id"])+def release_path_lease(self, path_id: str, *, turn_id: str | None = None) -> bool:path_id = self._validate_id(path_id)with self._connect() as conn:@@ -928,11 +949,33 @@ class LearningStore:SELECT * FROM mastery_interactionsWHERE path_id = ? AND status IN ({placeholders})ORDER BY created_at DESC LIMIT 1- """,+ """, # nosec B608 - placeholders is a generated "?,?" list; every value is bound(path_id, *_ACTIVE_INTERACTION_STATES),).fetchone()return LearningTransaction._interaction_from_row(row)+ def list_interactions(self, path_id: str, *, limit: int = 200) -> list[MasteryInteraction]:+ """Question/answer transactions for a path, most recent first.++ The aggregate keeps only the *current* question; the durable history of+ what was asked lives here, which is what lets a review surface the+ actual prompts behind an objective's attempts.+ """+ path_id = self._validate_id(path_id)+ self._import_legacy_if_needed(path_id)+ with self._connect() as conn:+ rows = conn.execute(+ """+ SELECT * FROM mastery_interactions+ WHERE path_id = ?+ ORDER BY created_at DESC, rowid DESC+ LIMIT ?+ """,+ (path_id, max(1, int(limit))),+ ).fetchall()+ interactions = (LearningTransaction._interaction_from_row(row) for row in rows)+ return [interaction for interaction in interactions if interaction is not None]+def list_events(self, path_id: str, *, after_revision: int = 0) -> list[MasteryEvent]:path_id = self._validate_id(path_id)self._import_legacy_if_needed(path_id)diff --git a/deeptutor/learning/tests/test_api_endpoints.py b/deeptutor/learning/tests/test_api_endpoints.pyindex 7dfea9968..2f85e9564 100644--- a/deeptutor/learning/tests/test_api_endpoints.py+++ b/deeptutor/learning/tests/test_api_endpoints.py@@ -9,6 +9,7 @@ import pytestfrom deeptutor.api.routers.mastery_path import routerfrom deeptutor.learning.models import PendingQuestion+from deeptutor.learning.service import LearningServicefrom deeptutor.learning.storage import LearningStore@@ -298,6 +299,116 @@ class TestDeleteProgress:assert resp.status_code == 400+# -- GET /progress/{book_id}/objectives/{kp_id} ---------------------------+++class TestObjectiveReport:+ def test_report_joins_prompts_without_leaking_the_answer_key(self, client, app):+ client.post(+ "/api/v1/learning/progress/report1/init-modules",+ json={"modules": [_module_payload()]},+ )+ store = LearningStore(root=app.state.learning_root)+ service = LearningService(store)+ service.register_question(+ "report1",+ PendingQuestion(+ question_id="q1",+ knowledge_point_id="kp1",+ module_id="m1",+ prompt="What is 2+2?",+ expected_answer="do-not-expose",+ ),+ )+ service.grade_interaction("report1", answer="4", question_id="q1")++ resp = client.get("/api/v1/learning/progress/report1/objectives/kp1")++ assert resp.status_code == 200+ objective = resp.json()["objective"]+ assert objective["name"] == "KP1"+ assert objective["gate"] == "qualitative" # concept type+ assert [a["prompt"] for a in objective["attempts"]] == ["What is 2+2?"]+ assert objective["attempts"][0]["answer"] == "4"+ assert "do-not-expose" not in resp.text++ def test_report_for_unknown_objective_returns_404(self, client):+ client.post(+ "/api/v1/learning/progress/report2/init-modules",+ json={"modules": [_module_payload()]},+ )+ resp = client.get("/api/v1/learning/progress/report2/objectives/nope")+ assert resp.status_code == 404++ def test_report_for_unknown_path_returns_404(self, client):+ assert client.get("/api/v1/learning/progress/nosuch/objectives/kp1").status_code == 404++ def test_report_invalid_book_id_returns_400(self, client):+ assert client.get("/api/v1/learning/progress/a\\b/objectives/kp1").status_code == 400+++# -- POST /progress/{book_id}/skip-question -------------------------------+++class TestSkipPendingQuestion:+ def _path_with_pending_question(self, client, app, book_id: str) -> LearningStore:+ client.post(+ f"/api/v1/learning/progress/{book_id}/init-modules",+ json={"modules": [_module_payload()]},+ )+ store = LearningStore(root=app.state.learning_root)+ progress = store.load(book_id)+ assert progress is not None+ progress.pending_question = PendingQuestion(+ question_id="question-1",+ knowledge_point_id="kp1",+ module_id="m1",+ prompt="Unanswerable?",+ expected_answer="lost",+ )+ store.save(progress)+ return store++ def test_skip_unblocks_the_next_objective(self, client, app):+ store = self._path_with_pending_question(client, app, "stuck")+ blocked = client.get("/api/v1/learning/progress/stuck/map").json()+ assert blocked["next"]["action"] == "answer_pending"++ resp = client.post("/api/v1/learning/progress/stuck/skip-question")++ assert resp.status_code == 200+ assert resp.json()["skipped"] is True+ assert store.load("stuck").pending_question is None+ assert client.get("/api/v1/learning/progress/stuck/map").json()["next"]["action"] != (+ "answer_pending"+ )++ def test_skip_keeps_earned_mastery(self, client, app):+ store = self._path_with_pending_question(client, app, "keepmastery")+ progress = store.load("keepmastery")+ progress.mastery_levels["kp1"] = 1.0+ store.save(progress)++ client.post("/api/v1/learning/progress/keepmastery/skip-question")++ assert store.load("keepmastery").mastery_levels["kp1"] == 1.0++ def test_skip_with_nothing_pending_is_a_no_op(self, client):+ client.post(+ "/api/v1/learning/progress/nothingpending/init-modules",+ json={"modules": [_module_payload()]},+ )+ resp = client.post("/api/v1/learning/progress/nothingpending/skip-question")+ assert resp.status_code == 200+ assert resp.json()["skipped"] is False++ def test_skip_unknown_path_returns_404(self, client):+ assert client.post("/api/v1/learning/progress/nosuchpath/skip-question").status_code == 404++ def test_skip_invalid_book_id_returns_400(self, client):+ assert client.post("/api/v1/learning/progress/a\\b/skip-question").status_code == 400++# -- POST /progress/{book_id}/redo ----------------------------------------diff --git a/deeptutor/learning/tests/test_mastery_tools.py b/deeptutor/learning/tests/test_mastery_tools.pyindex 325965bab..addbe78e9 100644--- a/deeptutor/learning/tests/test_mastery_tools.py+++ b/deeptutor/learning/tests/test_mastery_tools.py@@ -16,8 +16,11 @@ from deeptutor.tools.mastery_tool import (MasteryAssessTool,MasteryBuildTool,MasteryGradeTool,+ MasteryLeaveTool,+ MasteryPathsTool,MasteryQuizTool,MasteryStatusTool,+ MasterySwitchTool,)@@ -756,3 +759,166 @@ async def test_assess_rejects_quantitative_type(path_id):_mastery_path_id=path_id, knowledge_point_id=mem_kp, passed=True)assert result.success is False+++# ── path switching: a conversation is not bound to one path ───────────────+++async def _build_named(path_id: str, module_name: str) -> None:+ await MasteryBuildTool().execute(+ _mastery_path_id=path_id,+ mode="replace",+ modules=[+ {+ "name": module_name,+ "knowledge_points": [{"name": f"{module_name} basics", "type": "concept"}],+ }+ ],+ )+++async def test_paths_tool_reports_every_path_and_marks_the_active_one(path_id):+ await _build_named("calculus", "Calculus")+ await _build_named("algebra", "Algebra")++ payload = json.loads((await MasteryPathsTool().execute(_mastery_path_id="algebra")).content)++ assert payload["active_path_id"] == "algebra"+ by_id = {entry["path_id"]: entry for entry in payload["paths"]}+ assert by_id.keys() == {"calculus", "algebra"}+ assert by_id["algebra"]["active"] is True+ assert by_id["calculus"]["active"] is False+ assert by_id["calculus"]["objectives"] == 1+ assert by_id["calculus"]["mastered"] == 0+++async def test_paths_tool_hides_paths_with_nothing_to_teach(path_id):+ await _build_named("calculus", "Calculus")+ # A conversation-owned scratch path exists as soon as a mastery turn runs,+ # long before anyone builds objectives into it.+ with LearningStore().transaction("empty_scratch", create=True):+ pass++ payload = json.loads((await MasteryPathsTool().execute(_mastery_path_id="calculus")).content)++ assert [entry["path_id"] for entry in payload["paths"]] == ["calculus"]+++async def test_switch_rebinds_the_running_turn_and_hands_over_the_lease(path_id, session_store):+ await _build_named("calculus", "Calculus")+ await _build_named("algebra", "Algebra")+ store = LearningStore()+ store.acquire_path_lease("calculus", "session-1", "turn-1")+ bound: list[str] = []++ result = await MasterySwitchTool().execute(+ path_id="algebra",+ _mastery_path_id="calculus",+ _session_id="session-1",+ _turn_id="turn-1",+ _bind_active_path=bound.append,+ )++ assert result.success+ payload = json.loads(result.content)+ assert payload["previous_path_id"] == "calculus"+ assert payload["active_path_id"] == "algebra"+ # The rest of THIS turn must operate on the new path...+ assert bound == ["algebra"]+ # ...and exclusion moves with it, rather than being held on both or neither.+ assert store.get_path_lease("calculus") is None+ assert store.get_path_lease("algebra").turn_id == "turn-1"+++async def test_switch_to_an_unknown_path_changes_nothing(path_id):+ await _build_named("calculus", "Calculus")+ store = LearningStore()+ store.acquire_path_lease("calculus", "session-1", "turn-1")+ bound: list[str] = []++ result = await MasterySwitchTool().execute(+ path_id="not_a_path",+ _mastery_path_id="calculus",+ _session_id="session-1",+ _turn_id="turn-1",+ _bind_active_path=bound.append,+ )++ assert not result.success+ assert "mastery_paths" in result.content+ assert bound == []+ assert store.get_path_lease("calculus").turn_id == "turn-1"+++async def test_switch_into_a_path_busy_elsewhere_keeps_the_current_one(path_id):+ await _build_named("calculus", "Calculus")+ await _build_named("algebra", "Algebra")+ store = LearningStore()+ store.acquire_path_lease("calculus", "session-1", "turn-1")+ store.acquire_path_lease("algebra", "session-2", "turn-2")+ bound: list[str] = []++ result = await MasterySwitchTool().execute(+ path_id="algebra",+ _mastery_path_id="calculus",+ _session_id="session-1",+ _turn_id="turn-1",+ _bind_active_path=bound.append,+ )++ assert not result.success+ assert "another conversation" in result.content+ assert bound == []+ # Rolled back onto the path the learner was already on.+ assert store.get_path_lease("calculus").turn_id == "turn-1"+ assert store.get_path_lease("algebra").turn_id == "turn-2"+++async def test_leave_falls_back_to_the_conversation_scratch_path(path_id, session_store):+ await _build_named("calculus", "Calculus")+ store = LearningStore()+ store.acquire_path_lease("calculus", "session-1", "turn-1")+ bound: list[str] = []++ result = await MasteryLeaveTool().execute(+ _mastery_path_id="calculus",+ _session_id="session-1",+ _turn_id="turn-1",+ _bind_active_path=bound.append,+ )++ assert result.success+ payload = json.loads(result.content)+ assert payload["previous_path_id"] == "calculus"+ assert payload["active_path_id"] == "session-1"+ assert bound == ["session-1"]+ # The course keeps everything and stays resumable.+ assert store.load("calculus") is not None+ assert store.get_path_lease("calculus") is None+ assert store.get_path_lease("session-1").turn_id == "turn-1"+++async def test_leave_makes_the_conversation_own_its_scratch_path(path_id, session_store):+ """Otherwise leaving strews empty orphan paths that nothing cleans up."""+ await _build_named("calculus", "Calculus")+ store = LearningStore()+ store.acquire_path_lease("calculus", "session-1", "turn-1")++ await MasteryLeaveTool().execute(+ _mastery_path_id="calculus",+ _session_id="session-1",+ _turn_id="turn-1",+ _bind_active_path=lambda _path_id: None,+ )+ removed = store.detach_session("session-1", delete_owned_orphans=True)++ assert removed == ["session-1"]+ assert store.exists("session-1") is False+ assert store.exists("calculus") is Truediff --git a/deeptutor/learning/tests/test_policy.py b/deeptutor/learning/tests/test_policy.pyindex ce9f0296f..506202bda 100644--- a/deeptutor/learning/tests/test_policy.py+++ b/deeptutor/learning/tests/test_policy.py@@ -14,11 +14,14 @@ import timefrom deeptutor.learning import policyfrom deeptutor.learning.models import (+ ErrorRecord,+ ErrorType,KnowledgePoint,KnowledgeType,LearningModule,LearningProgress,PendingQuestion,+ QuizAttempt,RepetitionState,ReviewTask,)@@ -209,3 +212,86 @@ def test_map_summary_counts_and_completion():assert summary["complete"] is Falseprogress.qualitative_mastery["kp2"] = Trueassert policy.map_summary(progress)["complete"] is True+++# ── per-objective report (the review view) ─────────────────────────────────+++def test_objective_report_gathers_the_whole_evidence_trail():+ kp = _kp("kp1", KnowledgeType.MEMORY)+ progress = _progress(kp)+ progress.mastery_levels["kp1"] = 0.5+ progress.quiz_attempts = [+ QuizAttempt(+ question_id="q1",+ knowledge_point_id="kp1",+ module_id="m1",+ is_correct=False,+ user_answer="7",+ error_type=ErrorType.APPLICATION_ERROR,+ ),+ QuizAttempt(+ question_id="q2",+ knowledge_point_id="kp1",+ module_id="m1",+ is_correct=True,+ user_answer="4",+ ),+ QuizAttempt(question_id="q3", knowledge_point_id="other", module_id="m1", is_correct=True),+ ]+ progress.error_records = [+ ErrorRecord(+ id="e1",+ question_id="q1",+ knowledge_point_id="kp1",+ module_id="m1",+ error_type=ErrorType.APPLICATION_ERROR,+ )+ ]+ progress.repetition_states["kp1"] = RepetitionState(+ interval_index=2, consecutive_correct=1, next_review_at=1000.0+ )+ progress.review_queue = [+ ReviewTask(+ id="r1",+ knowledge_point_id="kp1",+ knowledge_type=KnowledgeType.MEMORY,+ due_at=1000.0,+ priority=1,+ state=progress.repetition_states["kp1"],+ )+ ]++ report = policy.objective_report(progress, "kp1")++ assert report is not None+ assert report["module_name"] == "M1"+ assert report["gate"] == "quantitative"+ assert report["threshold"] == 0.9+ assert report["mastered"] is False+ # Only this objective's attempts, in order, with their grading outcome.+ assert [a["question_id"] for a in report["attempts"]] == ["q1", "q2"]+ assert report["correct_count"] == 1+ assert report["attempts"][0]["error_type"] == "application"+ assert report["review"]["due_at"] == 1000.0+ assert report["review"]["interval_index"] == 2+ assert [e["id"] for e in report["errors"]] == ["e1"]+++def test_objective_report_carries_qualitative_evidence():+ kp = _kp("kp1", KnowledgeType.CONCEPT)+ progress = _progress(kp)+ progress.qualitative_mastery["kp1"] = True+ progress.feynman_explanations["kp1"] = "It routes by intent."++ report = policy.objective_report(progress, "kp1")++ assert report is not None+ assert report["gate"] == "qualitative"+ assert report["mastered"] is True+ assert report["explanation"] == "It routes by intent."+ assert report["review"] is None+++def test_objective_report_is_none_for_an_unknown_objective():+ assert policy.objective_report(_progress(_kp("kp1", KnowledgeType.MEMORY)), "nope") is Nonediff --git a/deeptutor/services/config/runtime_settings.py b/deeptutor/services/config/runtime_settings.pyindex 465ab517a..b894ea620 100644--- a/deeptutor/services/config/runtime_settings.py+++ b/deeptutor/services/config/runtime_settings.py@@ -224,6 +224,18 @@ DEFAULT_PAGEINDEX_SETTINGS: dict[str, Any] = {"api_base_url": "https://api.pageindex.ai",}+# Tencent IMA. The credential pair (``client_id`` + ``api_key``, issued at+# https://ima.qq.com/agent-interface) identifies one IMA account, and every+# library in that account is reachable with it — so it belongs here, beside the+# other engine credentials, rather than being retyped for each connected KB.+# A KB may still carry its own pair to reach a *different* IMA account; that+# per-KB binding wins (see ``pipelines/ima/config.py``).+DEFAULT_IMA_SETTINGS: dict[str, Any] = {+ "version": 1,+ "client_id": "",+ "api_key": "",+}+# LlamaIndex local RAG engine. These are the retrieval + chunking knobs the# default engine exposes; they were previously hardcoded / env-only. Kept in# their own JSON file so the engine's detail page can read/write them.@@ -485,6 +497,17 @@ class RuntimeSettingsService:_atomic_write_json(self.path_for("pageindex"), payload)return payload+ def load_ima(self, *, include_process_overrides: bool = True) -> dict[str, Any]:+ payload = self._load_or_create("ima", DEFAULT_IMA_SETTINGS, self._normalize_ima)+ if include_process_overrides:+ payload = self._apply_ima_process_overrides(payload)+ return payload++ def save_ima(self, settings: dict[str, Any]) -> dict[str, Any]:+ payload = self._normalize_ima({**DEFAULT_IMA_SETTINGS, **settings})+ _atomic_write_json(self.path_for("ima"), payload)+ return payload+def load_llamaindex(self, *, include_process_overrides: bool = True) -> dict[str, Any]:payload = self._load_or_create("llamaindex",@@ -522,6 +545,7 @@ class RuntimeSettingsService:self.load_integrations(include_process_overrides=False)self.load_mineru(include_process_overrides=False)self.load_pageindex(include_process_overrides=False)+ self.load_ima(include_process_overrides=False)self.load_llamaindex(include_process_overrides=False)self.load_graphrag()self.load_lightrag()@@ -739,6 +763,21 @@ class RuntimeSettingsService:or "https://api.pageindex.ai",}+ def _apply_ima_process_overrides(self, settings: dict[str, Any]) -> dict[str, Any]:+ payload = dict(settings)+ if value := self._process_env_value("IMA_CLIENT_ID"):+ payload["client_id"] = value+ if value := self._process_env_value("IMA_API_KEY"):+ payload["api_key"] = value+ return self._normalize_ima(payload)++ def _normalize_ima(self, settings: dict[str, Any]) -> dict[str, Any]:+ return {+ "version": 1,+ "client_id": _string(settings.get("client_id")),+ "api_key": _string(settings.get("api_key")),+ }+def _apply_llamaindex_process_overrides(self, settings: dict[str, Any]) -> dict[str, Any]:# Only the retrieval profile had an env override historically# (DEEPTUTOR_RAG_RETRIEVAL_PROFILE / RAG_RETRIEVAL_PROFILE); preserve it.@@ -1130,6 +1169,7 @@ __all__ = ["DEFAULT_AUTH_SETTINGS","DEFAULT_DOCUMENT_PARSING_SETTINGS","DEFAULT_GRAPHRAG_SETTINGS",+ "DEFAULT_IMA_SETTINGS","DEFAULT_INTEGRATIONS_SETTINGS","DEFAULT_LIGHTRAG_SETTINGS","DEFAULT_LLAMAINDEX_SETTINGS",diff --git a/deeptutor/services/memory/snapshot/entity.py b/deeptutor/services/memory/snapshot/entity.pyindex 1bb67fa27..f45773569 100644--- a/deeptutor/services/memory/snapshot/entity.py+++ b/deeptutor/services/memory/snapshot/entity.py@@ -31,11 +31,20 @@ class Entity:@runtime_checkableclass Stamped(Protocol):- """The three fields the diff engine actually reads off an entity."""+ """The three fields the diff engine actually reads off an entity.- id: str- label: str- fingerprint: str+ Declared read-only so a frozen carrier (:class:`EntityStamp`) satisfies it+ as readily as a mutable one (:class:`Entity`); the diff never writes back.+ """++ @property+ def id(self) -> str: ...++ @property+ def label(self) -> str: ...++ @property+ def fingerprint(self) -> str: ...@dataclass(frozen=True, slots=True)diff --git a/deeptutor/services/rag/factory.py b/deeptutor/services/rag/factory.pyindex 43598db90..7c97e340e 100644--- a/deeptutor/services/rag/factory.py+++ b/deeptutor/services/rag/factory.py@@ -188,6 +188,13 @@ def list_pipelines() -> List[Dict[str, Any]]:except Exception:pageindex_ready = False+ try:+ from .pipelines.ima.config import is_ima_configured++ ima_ready = is_ima_configured()+ except Exception:+ ima_ready = False+try:from .pipelines.graphrag import config as graphrag_config@@ -264,13 +271,14 @@ def list_pipelines() -> List[Dict[str, Any]]:"description": ("Retrieval offloaded to a knowledge base you keep in Tencent IMA. ""No local index and no copy — connect a KB to its IMA library and "- "query it over IMA's OpenAPI. Documents are added in IMA itself."+ "query it over IMA's OpenAPI. Documents are added in IMA itself. "+ "Requires an IMA Client ID and API key."),- # Always available: a thin HTTPS client with no install and no global- # credential. Client ID, API key and library id are per-KB, set at- # connect time.- "configured": True,- "requires_api_key": False,+ # A thin HTTPS client with no install; readiness is only about the+ # account credentials. The library id stays per-KB, set at connect+ # time, and a KB may pin its own credentials to reach another account.+ "configured": ima_ready,+ "requires_api_key": True,},]diff --git a/deeptutor/services/rag/pipelines/ima/__init__.py b/deeptutor/services/rag/pipelines/ima/__init__.pyindex b48163985..8cc71e474 100644--- a/deeptutor/services/rag/pipelines/ima/__init__.py+++ b/deeptutor/services/rag/pipelines/ima/__init__.py@@ -4,9 +4,10 @@ A KB bound to the ``ima`` provider is a connection pointer to a library the userkeeps in IMA (https://ima.qq.com) and curates there. DeepTutor never indexes orstores anything locally: retrieval calls IMA's ``search_knowledge`` OpenAPI anduses a bounded read-only source fallback when a match has no snippet. DeepTutor's-chat LLM still writes the answer, and credentials plus the knowledge base id are-configured per-KB. See ``client`` for the wire and ``probe`` for the connect-time-health check.+chat LLM still writes the answer. The IMA credentials are configured once for the+account on the engine page (a KB may override them to reach another account); the+knowledge base id is always per-KB. See ``client`` for the wire and ``probe`` for+the connect-time health check."""from __future__ import annotationsdiff --git a/deeptutor/services/rag/pipelines/ima/config.py b/deeptutor/services/rag/pipelines/ima/config.pyindex 1169966f8..43a6054da 100644--- a/deeptutor/services/rag/pipelines/ima/config.py+++ b/deeptutor/services/rag/pipelines/ima/config.py@@ -1,15 +1,19 @@-"""Per-KB connection config for the Tencent IMA engine.+"""Connection config for the Tencent IMA engine.IMA credentials (``client_id`` + ``api_key``, issued at-https://ima.qq.com/agent-interface) identify a *person*, and a knowledge base id-identifies one of that person's libraries. Both are stored per-KB in-``kb_config.json`` — the same place a ``lightrag-server`` KB keeps its endpoint —-rather than as one global account key:+https://ima.qq.com/agent-interface) identify an *account*, and a knowledge base+id identifies one of that account's libraries. The credentials therefore resolve+at two levels:-* on a multi-user deployment each user connects their own IMA account, so- nobody retrieves through somebody else's credentials;-* connecting is self-contained, with no separate global settings surface to fill- in first.+* **account level** — ``settings/ima.json`` (managed by+ ``RuntimeSettingsService``), edited under Knowledge → the IMA engine page.+ One pair is shared by every ``ima`` KB, the way PageIndex's key is;+* **per KB** — the same two fields on the KB's ``kb_config.json`` entry. Present+ on knowledge bases connected before the engine page existed, and still the way+ to point one KB at a *different* IMA account.++The per-KB pair wins when it is complete, so an existing binding keeps working+untouched and rotating the account key updates every KB that relies on it.This module is the single seam that reads that binding into a typed config; itholds no global state and imports no HTTP client (the client lives in@@ -19,7 +23,7 @@ holds no global state and imports no HTTP client (the client lives infrom __future__ import annotationsfrom dataclasses import dataclass-from typing import Any+from typing import Any, Optional# IMA exposes exactly one retrieval call (``search_knowledge``) with no mode# knob, so a KB bound to this engine has no per-KB search mode to pick. The@@ -33,6 +37,18 @@ class ImaNotConfiguredError(RuntimeError):"""Raised when a KB is missing the credentials or the knowledge base id."""+@dataclass(frozen=True)+class ImaCredentials:+ """One IMA account's credential pair."""++ client_id: str = ""+ api_key: str = ""++ @property+ def complete(self) -> bool:+ return bool(self.client_id and self.api_key)++@dataclass(frozen=True)class ImaConfig:"""A KB's resolved connection to one Tencent IMA knowledge base."""@@ -42,16 +58,47 @@ class ImaConfig:knowledge_base_id: str-def config_from_entry(entry: dict[str, Any]) -> ImaConfig:+def get_account_credentials() -> ImaCredentials:+ """Load the account-level credential pair, or an empty one.++ Never raises: an unreadable settings file only means "not configured", which+ the callers already handle.+ """+ try:+ from deeptutor.services.config import get_runtime_settings_service++ settings = get_runtime_settings_service().load_ima()+ except Exception:+ return ImaCredentials()+ return ImaCredentials(+ client_id=str(settings.get("client_id") or "").strip(),+ api_key=str(settings.get("api_key") or "").strip(),+ )+++def is_ima_configured() -> bool:+ """Whether account-level credentials are set (flags the engine as ready)."""+ return get_account_credentials().complete+++def config_from_entry(+ entry: dict[str, Any],+ *,+ fallback: Optional[ImaCredentials] = None,+) -> ImaConfig:"""Build an :class:`ImaConfig` from a ``kb_config.json`` KB entry.- Raises :class:`ImaNotConfiguredError` when any of the three required fields- is missing, so retrieval fails with a clear message instead of an opaque- HTTP error from IMA.+ The entry's own credentials win; *fallback* (normally the account-level+ pair) fills in what it omits. Raises :class:`ImaNotConfiguredError` when any+ of the three required fields is still missing, so retrieval fails with a+ clear message instead of an opaque HTTP error from IMA."""client_id = str(entry.get("client_id") or "").strip()api_key = str(entry.get("api_key") or "").strip()knowledge_base_id = str(entry.get("knowledge_base_id") or "").strip()+ if fallback is not None:+ client_id = client_id or fallback.client_id+ api_key = api_key or fallback.api_keymissing = [labelfor label, value in (@@ -64,7 +111,9 @@ def config_from_entry(entry: dict[str, Any]) -> ImaConfig:if missing:raise ImaNotConfiguredError("This knowledge base is not fully connected to Tencent IMA "- f"(missing {', '.join(missing)}). Re-create it with complete credentials."+ f"(missing {', '.join(missing)}). Add the IMA credentials on the "+ "engine page under Knowledge, or re-create the knowledge base with "+ "complete credentials.")return ImaConfig(client_id=client_id,@@ -73,10 +122,19 @@ def config_from_entry(entry: dict[str, Any]) -> ImaConfig:)+def resolve_kb_config(entry: dict[str, Any]) -> ImaConfig:+ """``config_from_entry`` with the account-level credentials as fallback."""+ return config_from_entry(entry, fallback=get_account_credentials())++__all__ = ["SUPPORTED_MODES","DEFAULT_MODE","ImaNotConfiguredError",+ "ImaCredentials","ImaConfig","config_from_entry",+ "get_account_credentials",+ "is_ima_configured",+ "resolve_kb_config",]diff --git a/deeptutor/services/rag/pipelines/ima/pipeline.py b/deeptutor/services/rag/pipelines/ima/pipeline.pyindex eefaa415a..701c97b21 100644--- a/deeptutor/services/rag/pipelines/ima/pipeline.py+++ b/deeptutor/services/rag/pipelines/ima/pipeline.py@@ -3,7 +3,7 @@Implements the same contract as the other pipelines (see ``..base.RAGPipeline``)but owns no index: an ``ima`` KB is a connection pointer (``type: ima`` in``kb_config.json``) to a library the user keeps in IMA and curates there. Only-:meth:`search` does real work — it reads the KB's credentials, asks IMA for+:meth:`search` does real work — it resolves the KB's credentials, asks IMA formatching passages, and shapes them for the ``rag`` tool. Documents are added inIMA, so :meth:`initialize` / :meth:`add_documents` are not part of this engine'sjob and fail with a clear message; :meth:`delete` is a no-op because deleting the@@ -26,7 +26,7 @@ from deeptutor.utils.document_extractor import ()from .client import MAX_MEDIA_BYTES, ImaMediaContent-from .config import ImaNotConfiguredError, config_from_entry+from .config import ImaNotConfiguredError, resolve_kb_configlogger = logging.getLogger(__name__)@@ -74,7 +74,7 @@ class ImaPipeline:async def search(self, query: str, kb_name: str, **kwargs) -> Dict[str, Any]:try:- config = config_from_entry(load_kb_config_entry(self.kb_base_dir, kb_name))+ config = resolve_kb_config(load_kb_config_entry(self.kb_base_dir, kb_name))except ImaNotConfiguredError as exc:return self._error_result(query, exc, error_type="not_configured")diff --git a/deeptutor/services/rag/preflight.py b/deeptutor/services/rag/preflight.pyindex fb9e1abf3..1c3ecc8ad 100644--- a/deeptutor/services/rag/preflight.py+++ b/deeptutor/services/rag/preflight.py@@ -181,13 +181,24 @@ def _lightrag_preflight() -> dict:def _ima_preflight() -> dict:+ try:+ from .pipelines.ima.config import get_account_credentials++ credentials = get_account_credentials()+ except Exception:+ from .pipelines.ima.config import ImaCredentials++ credentials = ImaCredentials()return _finalize([_check(- "per_kb_credentials",- "Credentials supplied when connecting a knowledge base",- True,- "Enter the IMA Client ID and API key in the link-existing flow.",+ "credentials",+ "IMA Client ID and API key configured",+ credentials.complete,+ credentials.client_id+ if credentials.complete+ else "Add them under Credentials, or supply a pair per knowledge base "+ "when connecting one.",)])diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.pyindex 4582b6c1f..1367232df 100644--- a/deeptutor/services/session/turn_runtime.py+++ b/deeptutor/services/session/turn_runtime.py@@ -23,6 +23,7 @@ from deeptutor.services.session.artifact_attachments import (from deeptutor.services.session.protocol import SessionStoreProtocolif TYPE_CHECKING:+ from deeptutor.learning.storage import MasteryPathLeasefrom deeptutor.services.llm.config import LLMConfiglogger = logging.getLogger(__name__)@@ -613,6 +614,10 @@ class _TurnExecution:capability: strpayload: dict[str, Any]task: asyncio.Task[None] | None = None+ # True while the turn is parked inside ``ask_user`` waiting for a learner+ # reply. Such a turn holds its resources (notably a mastery path lease)+ # but is doing no work, so another turn may take over from it.+ awaiting_user_reply: bool = Falsesubscribers: list[_LiveSubscriber] = field(default_factory=list)events: list[dict[str, Any]] = field(default_factory=list)next_seq: int = 1@@ -683,6 +688,41 @@ class TurnRuntimeManager:for turn in await self.store.list_active_turns(session_id):await self._fail_orphan_running_turn(turn)+ async def _is_awaiting_user_reply(self, turn_id: str) -> bool:+ async with self._lock:+ execution = self._executions.get(turn_id)+ return execution is not None and execution.awaiting_user_reply++ async def _release_superseded_lease(self, path_id: str, lease: MasteryPathLease) -> None:+ """Free ``lease`` when its turn can no longer be working on the path.++ Two cases release it. A turn that is no longer ``running`` (finished,+ or orphaned by a restart) is simply gone. A turn parked inside+ ``ask_user`` is alive but idle — it holds the lease for as long as the+ learner takes to answer, which may be forever. Since the posed question+ is persisted on the path itself, the arriving turn resumes exactly+ where the parked one stopped, so handing the path over loses nothing;+ the parked turn is cancelled rather than left to mutate a path it no+ longer owns. Only a turn that is actively generating keeps the lease.+ """+ from deeptutor.learning.storage import LearningStore++ leased_turn = await self._fail_orphan_running_turn(await self.store.get_turn(lease.turn_id))+ alive = leased_turn is not None and str(leased_turn.get("status") or "") == "running"+ if alive:+ if not await self._is_awaiting_user_reply(lease.turn_id):+ # Genuinely busy — leave the lease, and let the store report+ # the conflict to the caller.+ return+ await self.cancel_turn(lease.turn_id)+ # Scoped to the superseded turn id, so a lease already re-taken by+ # someone else survives.+ await asyncio.to_thread(+ LearningStore().release_path_lease,+ path_id,+ turn_id=lease.turn_id,+ )+async def _acquire_mastery_path_lease(self,*,@@ -691,7 +731,7 @@ class TurnRuntimeManager:turn_id: str,owns_path: bool,) -> None:- """Bind a session to its path and recover only demonstrably stale leases."""+ """Bind a session to its path and take over from any superseded turn."""from deeptutor.learning.storage import LearningStore, PathLeaseConflictErrorlearning_store = LearningStore()@@ -703,14 +743,7 @@ class TurnRuntimeManager:)lease = await asyncio.to_thread(learning_store.get_path_lease, path_id)if lease is not None and lease.turn_id != turn_id and lease.session_id != "__path_api__":- leased_turn = await self.store.get_turn(lease.turn_id)- leased_turn = await self._fail_orphan_running_turn(leased_turn)- if leased_turn is None or str(leased_turn.get("status") or "") != "running":- await asyncio.to_thread(- learning_store.release_path_lease,- path_id,- turn_id=lease.turn_id,- )+ await self._release_superseded_lease(path_id, lease)try:await asyncio.to_thread(learning_store.acquire_path_lease,@@ -1345,7 +1378,13 @@ class TurnRuntimeManager:self._reply_queues[turn_id] = reply_queueasync def _wait_for_user_reply() -> dict[str, Any] | None:- return await reply_queue.get()+ # Publish the pause so a turn that wants the same mastery path can+ # tell "busy generating" apart from "parked, learner walked away".+ execution.awaiting_user_reply = True+ try:+ return await reply_queue.get()+ finally:+ execution.awaiting_user_reply = Falsetry:from deeptutor.agents.notebook import NotebookAnalysisAgent@@ -1834,6 +1873,18 @@ class TurnRuntimeManager:seen_artifact_urls.add(attachment["url"])generated_attachments.append(attachment)+ # A mastery turn may have changed which path it is on+ # (``mastery_switch`` / ``mastery_leave``). The conversation's+ # stored preference already followed it; tell the open client too,+ # so what it shows as "currently mastering" is not the path the+ # turn merely started on.+ await self._publish_mastery_path_change(+ execution,+ capability_name=capability_name,+ started_on=_mastery_path_id(payload.get("mastery_path_id")),+ ended_on=str(context.metadata.get("mastery_path_id") or ""),+ )+# Office binaries the browser cannot render need their text pulled# out now, while the files are still on disk, or their preview card# opens empty. Skipped on the cancelled path below: that one is@@ -2026,17 +2077,16 @@ class TurnRuntimeManager:# that finds the queue gone will return ``False`` rather than# accumulating on a dead turn.self._reply_queues.pop(turn_id, None)- mastery_path_id = _mastery_path_id(payload.get("mastery_path_id"))- if capability_name == "mastery_path" and mastery_path_id:+ if capability_name == "mastery_path":from deeptutor.learning.storage import LearningStore+ # By turn, not by the path the turn started on: mastery_switch+ # can move a turn onto a different path mid-flight, and freeing+ # the original id would release someone else's lease while+ # leaking the one this turn actually holds.with contextlib.suppress(Exception):await asyncio.shield(- asyncio.to_thread(- LearningStore().release_path_lease,- mastery_path_id,- turn_id=turn_id,- )+ asyncio.to_thread(LearningStore().release_leases_for_turn, turn_id))async with self._lock:current = self._executions.get(turn_id)@@ -2052,6 +2102,26 @@ class TurnRuntimeManager:schedule_memory_reclaim()+ async def _publish_mastery_path_change(+ self,+ execution: _TurnExecution,+ *,+ capability_name: str,+ started_on: str,+ ended_on: str,+ ) -> None:+ """Announce a path the turn moved onto, so the client stops lying."""+ if capability_name != "mastery_path" or not ended_on or ended_on == started_on:+ return+ await self._publish_live_event(+ execution,+ StreamEvent(+ type=StreamEventType.SESSION_META,+ source="turn_runtime",+ metadata={"mastery_path_id": ended_on},+ ),+ )+async def _publish_live_event(self,execution: _TurnExecution,diff --git a/deeptutor/tools/mastery_tool.py b/deeptutor/tools/mastery_tool.pyindex 02a0ef9a5..0333f146c 100644--- a/deeptutor/tools/mastery_tool.py+++ b/deeptutor/tools/mastery_tool.py@@ -12,16 +12,22 @@ from deeptutor.capabilities.mastery.tools import (MasteryAssessTool,MasteryBuildTool,MasteryGradeTool,+ MasteryLeaveTool,+ MasteryPathsTool,MasteryQuizTool,MasteryStatusTool,+ MasterySwitchTool,)__all__ = ["MASTERY_TOOL_NAMES","MASTERY_TOOL_TYPES",- "MasteryStatusTool",- "MasteryQuizTool",- "MasteryGradeTool","MasteryAssessTool","MasteryBuildTool",+ "MasteryGradeTool",+ "MasteryLeaveTool",+ "MasteryPathsTool",+ "MasteryQuizTool",+ "MasteryStatusTool",+ "MasterySwitchTool",]diff --git a/tests/api/test_book_ws_stream.py b/tests/api/test_book_ws_stream.pynew file mode 100644index 000000000..b31f18ed1--- /dev/null+++ b/tests/api/test_book_ws_stream.py@@ -0,0 +1,189 @@+"""End-to-end cover for the book WebSocket protocol.++The bug this protects against was invisible to unit tests: the router created a+bus per action and closed it in ``finally``, so every event emitted by work that+outlived the action — i.e. all background compilation — was dropped on the+floor. Both halves have to be checked through the real socket:++1. a subscriber receives events published after any action has returned, and+2. finishing an action does not close the book's stream out from under it.+"""++from __future__ import annotations++import asyncio++from fastapi import FastAPI+import pytest+from starlette.testclient import TestClient++from deeptutor.api.routers import book as book_router+from deeptutor.book import event_hub+from deeptutor.book.event_hub import get_book_stream++BOOK_ID = "bk_ws_test"++[email protected](autouse=True)+def _clean_hub():+ event_hub._buses.clear()+ yield+ event_hub._buses.clear()+++class _StubEngine:+ """Just enough engine for the socket to run an action."""++ def __init__(self, *, known: set[str] | None = None) -> None:+ self.compiled: list[str] = []+ # The socket verifies a book is visible to this user before attaching+ # its stream; anything not here behaves like another user's book.+ self.known = {BOOK_ID} if known is None else known++ def load_book(self, book_id: str):+ from deeptutor.book.models import Book++ return Book(id=book_id) if book_id in self.known else None++ async def compile_page(self, *, book_id, page_id, force=False):+ from deeptutor.book.models import Page++ self.compiled.append(page_id)+ # Publish the way the real compiler does — into the book's own stream.+ await get_book_stream(book_id).book_event(+ "block_ready", {"page_id": page_id, "block_id": "blk_1"}+ )+ return Page(id=page_id, book_id=book_id)+++def client(monkeypatch) -> TestClient:+ engine = _StubEngine()+ monkeypatch.setattr(book_router, "get_book_engine", lambda: engine)+ app = FastAPI()+ app.include_router(book_router.router, prefix="/api/v1/book")+ return TestClient(app)+++def _drain_until(ws, predicate, *, limit=12):+ """Read frames until *predicate* matches; returns the matching frame."""+ for _ in range(limit):+ frame = ws.receive_json()+ if predicate(frame):+ return frame+ raise AssertionError("expected frame never arrived")+++def test_subscribe_is_acknowledged(client: TestClient) -> None:+ with client.websocket_connect("/api/v1/book/ws") as ws:+ ws.send_json({"type": "subscribe", "book_id": BOOK_ID})+ assert ws.receive_json() == {"type": "subscribed", "book_id": BOOK_ID}+++def test_subscribe_without_a_book_id_is_rejected(client: TestClient) -> None:+ with client.websocket_connect("/api/v1/book/ws") as ws:+ ws.send_json({"type": "subscribe"})+ frame = ws.receive_json()+ assert frame["type"] == "error"+++def test_a_subscriber_receives_events_from_an_action(client: TestClient) -> None:+ with client.websocket_connect("/api/v1/book/ws") as ws:+ ws.send_json({"type": "subscribe", "book_id": BOOK_ID})+ assert ws.receive_json()["type"] == "subscribed"++ ws.send_json({"type": "compile_page", "book_id": BOOK_ID, "page_id": "pg_1"})++ event = _drain_until(ws, lambda f: f.get("metadata", {}).get("kind") == "block_ready")+ assert event["metadata"]["page_id"] == "pg_1"+++def test_the_book_stream_survives_the_action_that_used_it(client: TestClient) -> None:+ """The regression itself: work queued by an action keeps streaming after it."""+ with client.websocket_connect("/api/v1/book/ws") as ws:+ ws.send_json({"type": "subscribe", "book_id": BOOK_ID})+ assert ws.receive_json()["type"] == "subscribed"++ ws.send_json({"type": "compile_page", "book_id": BOOK_ID, "page_id": "pg_1"})+ _drain_until(ws, lambda f: f.get("type") == "compile_page_result")++ # The action has replied and its handler has unwound. Previously the bus+ # was closed at exactly this point and everything below was lost.+ bus = event_hub.get_book_bus(BOOK_ID)+ assert not bus._closed, "an action must not close the book's shared stream"++ async def _emit_later() -> None:+ await get_book_stream(BOOK_ID).book_event(+ "page_compiled", {"page_id": "pg_9", "status": "ready"}+ )++ asyncio.run(_emit_later())++ event = _drain_until(ws, lambda f: f.get("metadata", {}).get("kind") == "page_compiled")+ assert event["metadata"]["page_id"] == "pg_9"+++def test_a_reconnecting_client_catches_up_on_replayed_history(client: TestClient) -> None:+ async def _emit_before_anyone_is_listening() -> None:+ stream = get_book_stream(BOOK_ID)+ await stream.book_event("page_planned", {"page_id": "pg_1"})+ await stream.book_event("block_ready", {"page_id": "pg_1", "block_id": "blk_1"})++ asyncio.run(_emit_before_anyone_is_listening())++ with client.websocket_connect("/api/v1/book/ws") as ws:+ ws.send_json({"type": "subscribe", "book_id": BOOK_ID})+ kinds = []+ for _ in range(6):+ frame = ws.receive_json()+ kind = frame.get("metadata", {}).get("kind")+ if kind:+ kinds.append(kind)+ if "page_planned" in kinds and "block_ready" in kinds:+ break+ assert "page_planned" in kinds and "block_ready" in kinds+++def test_two_clients_watching_one_book_both_get_events(client: TestClient) -> None:+ with client.websocket_connect("/api/v1/book/ws") as first:+ first.send_json({"type": "subscribe", "book_id": BOOK_ID})+ assert first.receive_json()["type"] == "subscribed"++ with client.websocket_connect("/api/v1/book/ws") as second:+ second.send_json({"type": "subscribe", "book_id": BOOK_ID})+ assert second.receive_json()["type"] == "subscribed"++ second.send_json({"type": "compile_page", "book_id": BOOK_ID, "page_id": "pg_1"})++ for ws in (first, second):+ event = _drain_until(+ ws, lambda f: f.get("metadata", {}).get("kind") == "block_ready"+ )+ assert event["metadata"]["page_id"] == "pg_1"+++def test_unknown_message_types_are_reported_not_ignored(client: TestClient) -> None:+ with client.websocket_connect("/api/v1/book/ws") as ws:+ ws.send_json({"type": "nonsense", "book_id": BOOK_ID})+ frame = ws.receive_json()+ assert frame["type"] == "error"+ assert "nonsense" in frame["content"]+++def test_subscribing_to_a_book_this_user_cannot_see_is_refused(+ monkeypatch,+) -> None:+ """Buses are keyed by book id alone, so the socket must check visibility."""+ engine = _StubEngine(known=set())+ monkeypatch.setattr(book_router, "get_book_engine", lambda: engine)+ app = FastAPI()+ app.include_router(book_router.router, prefix="/api/v1/book")++ with TestClient(app).websocket_connect("/api/v1/book/ws") as ws:+ ws.send_json({"type": "subscribe", "book_id": "bk_someone_else"})+ frame = ws.receive_json()+ assert frame["type"] == "error"+ assert "not found" in frame["content"].lower()+ assert "bk_someone_else" not in event_hub._buses, (+ "a refused subscribe must not create the book's bus"+ )diff --git a/tests/api/test_knowledge_router.py b/tests/api/test_knowledge_router.pyindex b651ff9b7..580084673 100644--- a/tests/api/test_knowledge_router.py+++ b/tests/api/test_knowledge_router.py@@ -7,11 +7,14 @@ from pathlib import Pathimport pytest+import deeptutor.services.config as config_module+from deeptutor.services.config.runtime_settings import RuntimeSettingsServicefrom deeptutor.services.rag.pipelines.ima.client import (ImaAPIError,ImaAuthError,ImaRateLimitError,)+import deeptutor.services.rag.pipelines.ima.config as ima_config_moduletry:from fastapi import FastAPI@@ -133,7 +136,8 @@ def _write_ready_llamaindex_version(kb_dir: Path) -> None:)-def test_rag_providers_lists_llamaindex_and_pageindex() -> None:+def test_rag_providers_lists_llamaindex_and_pageindex(monkeypatch) -> None:+ monkeypatch.setattr(ima_config_module, "is_ima_configured", lambda: True)with TestClient(_build_app()) as client:response = client.get("/api/v1/knowledge/rag-providers")@@ -158,9 +162,9 @@ def test_rag_providers_lists_llamaindex_and_pageindex() -> None:# (the per-KB endpoint is configured at connect time).assert by_id["lightrag-server"]["requires_api_key"] is Falseassert by_id["lightrag-server"]["configured"] is True- # Same for IMA: a thin HTTPS client, credentials bound per-KB at connect- # time rather than gated by one global key.- assert by_id["ima"]["requires_api_key"] is False+ # IMA is a thin HTTPS client with no install, but it does need an account+ # credential pair — configured here by the patched account settings.+ assert by_id["ima"]["requires_api_key"] is Trueassert by_id["ima"]["configured"] is True# Mode-aware engines advertise their retrieval modes; vector engines don't.assert "hybrid" in by_id["lightrag"]["modes"]@@ -301,6 +305,177 @@ def test_list_ima_maps_upstream_errors_without_leaking_credentials(assert "private-key" not in response.text+def ima_account(tmp_path: Path, monkeypatch) -> RuntimeSettingsService:+ """Account-level IMA settings backed by a throwaway directory."""+ service = RuntimeSettingsService(tmp_path / "settings", process_env={})+ monkeypatch.setattr(config_module, "get_runtime_settings_service", lambda: service)+ return service+++def test_list_ima_falls_back_to_the_account_credentials(monkeypatch, ima_account) -> None:+ ima_account.save_ima({"client_id": "account-client", "api_key": "account-key"})+ captured: dict = {}+ stub = _ImaListStub()++ def build_client(config):+ captured["config"] = config+ return stub++ monkeypatch.setattr(knowledge_router_module, "ImaClient", build_client, raising=False)+ with TestClient(_build_app()) as client:+ response = client.post("/api/v1/knowledge/list-ima", json={})++ assert response.status_code == 200+ assert captured["config"].client_id == "account-client"+ assert captured["config"].api_key == "account-key"+++def test_list_ima_does_not_complete_half_a_supplied_pair(monkeypatch, ima_account) -> None:+ # Mixing one account's Client ID with another's key would fail at IMA with+ # a confusing verdict; ask for the missing half instead.+ ima_account.save_ima({"client_id": "account-client", "api_key": "account-key"})++ with TestClient(_build_app()) as client:+ response = client.post("/api/v1/knowledge/list-ima", json={"client_id": "other"})++ assert response.status_code == 400+ assert "required" in response.json()["detail"]+++def test_ima_config_reports_state_without_echoing_the_key(ima_account) -> None:+ with TestClient(_build_app()) as client:+ assert client.get("/api/v1/knowledge/rag-pipelines/ima/config").json() == {+ "client_id": "",+ "api_key_set": False,+ "configured": False,+ }++ response = client.put(+ "/api/v1/knowledge/rag-pipelines/ima/config",+ json={"client_id": " account-client ", "api_key": " private-key "},+ )++ assert response.status_code == 200+ assert response.json() == {+ "client_id": "account-client",+ "api_key_set": True,+ "configured": True,+ }+ assert "private-key" not in response.text+ assert ima_account.load_ima(include_process_overrides=False)["api_key"] == "private-key"+++def test_ima_config_keeps_the_stored_key_when_omitted(ima_account) -> None:+ ima_account.save_ima({"client_id": "account-client", "api_key": "private-key"})++ with TestClient(_build_app()) as client:+ response = client.put(+ "/api/v1/knowledge/rag-pipelines/ima/config",+ json={"client_id": "renamed-client"},+ )++ assert response.status_code == 200+ assert response.json()["api_key_set"] is True+ stored = ima_account.load_ima(include_process_overrides=False)+ assert stored == {"version": 1, "client_id": "renamed-client", "api_key": "private-key"}+++def test_ima_config_clears_the_key_on_an_empty_string(ima_account) -> None:+ ima_account.save_ima({"client_id": "account-client", "api_key": "private-key"})++ with TestClient(_build_app()) as client:+ response = client.put(+ "/api/v1/knowledge/rag-pipelines/ima/config",+ json={"api_key": ""},+ )++ assert response.json() == {+ "client_id": "account-client",+ "api_key_set": False,+ "configured": False,+ }+++class _ProbeResult:+ def __init__(self) -> None:+ self.ok = True+ self.error = None+ self.description = "notes"++ def to_dict(self) -> dict:+ return {"ok": True, "error": None, "description": self.description}+++def _capture_probe(monkeypatch) -> list[tuple[str, str, str]]:+ """Record the credentials the router probes with, without any network."""+ import deeptutor.services.rag.pipelines.ima.probe as probe_module++ calls: list[tuple[str, str, str]] = []++ async def fake_probe(client_id: str, api_key: str, knowledge_base_id: str, **_kwargs):+ calls.append((client_id, api_key, knowledge_base_id))+ return _ProbeResult()++ monkeypatch.setattr(probe_module, "probe_knowledge_base", fake_probe)+ return calls+++def _real_manager(monkeypatch, tmp_path: Path):+ from deeptutor.knowledge.manager import KnowledgeBaseManager++ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))+ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)+ return manager+++def test_connect_ima_uses_the_account_pair_without_copying_it(+ monkeypatch, tmp_path: Path, ima_account+) -> None:+ ima_account.save_ima({"client_id": "account-client", "api_key": "account-key"})+ calls = _capture_probe(monkeypatch)+ manager = _real_manager(monkeypatch, tmp_path)++ with TestClient(_build_app()) as client:+ response = client.post(+ "/api/v1/knowledge/connect-ima",+ json={"name": "IMA", "knowledge_base_id": "kb-1"},+ )++ assert response.status_code == 200+ # Probed with the account credentials …+ assert calls == [("account-client", "account-key", "kb-1")]+ # … but the KB keeps only the pointer, so rotating the key keeps it working.+ entry = manager.config["knowledge_bases"]["IMA"]+ assert entry["knowledge_base_id"] == "kb-1"+ assert "client_id" not in entry and "api_key" not in entry+++def test_connect_ima_pins_supplied_credentials_to_the_kb(+ monkeypatch, tmp_path: Path, ima_account+) -> None:+ ima_account.save_ima({"client_id": "account-client", "api_key": "account-key"})+ calls = _capture_probe(monkeypatch)+ manager = _real_manager(monkeypatch, tmp_path)++ with TestClient(_build_app()) as client:+ response = client.post(+ "/api/v1/knowledge/connect-ima",+ json={+ "name": "Other",+ "client_id": "other-client",+ "api_key": "other-key",+ "knowledge_base_id": "kb-2",+ },+ )++ assert response.status_code == 200+ assert calls == [("other-client", "other-key", "kb-2")]+ entry = manager.config["knowledge_bases"]["Other"]+ assert entry["client_id"] == "other-client"+ assert entry["api_key"] == "other-key"++def test_set_rag_provider_mode_persists_validates_and_reflects() -> None:with TestClient(_build_app()) as client:ok = client.put("/api/v1/knowledge/rag-providers/lightrag/mode", json={"mode": "MIX"})diff --git a/tests/book/test_code_block_validation.py b/tests/book/test_code_block_validation.pynew file mode 100644index 000000000..9ca4c183b--- /dev/null+++ b/tests/book/test_code_block_validation.py@@ -0,0 +1,66 @@+"""Generated code must at least parse before it reaches the reader.++A truncated snippet is worse than no snippet: the reader copies it, it fails,+and nothing in the page said it was never checked. Parsing is free, runs+in-process, and has no side effects — unlike executing it, which a generated+snippet must never be trusted to do.+"""++from __future__ import annotations++import pytest++from deeptutor.book.blocks.code import _CHECKABLE, _syntax_error+++ "code",+ [+ "def f():\n return 1",+ "x = [1, 2, 3]\nprint(sum(x))",+ "", # empty is rejected earlier, and parses here+ ],+)+def test_valid_python_passes(code: str) -> None:+ assert _syntax_error(code, "python") is None+++ "code",+ [+ 'print("hi', # unterminated string — the classic truncation+ "def f(:\n pass", # malformed signature+ "if True\n pass", # missing colon+ "def f():\n return 1\n return 2", # inconsistent indent+ ],+)+def test_malformed_python_is_reported(code: str) -> None:+ error = _syntax_error(code, "python")+ assert error, f"expected a syntax error for {code!r}"+ assert isinstance(error, str) and error.strip()+++def test_json_is_validated_too() -> None:+ assert _syntax_error('{"a": 1}', "json") is None+ assert _syntax_error('{"a": }', "json")++[email protected]("language", ["rust", "go", "haskell", "", "unknown"])+def test_languages_we_cannot_check_are_left_alone(language: str) -> None:+ """No false failures for languages without an in-process parser."""+ assert _syntax_error("this is definitely not valid code {{{", language) is None+++def test_language_matching_is_case_and_whitespace_insensitive() -> None:+ assert _syntax_error('print("hi', " Python ") is not None+ assert _syntax_error('print("hi', "PY") is not None+++def test_a_broken_checker_never_breaks_generation(monkeypatch) -> None:+ """Validation is a safety net, not a new failure mode."""++ def boom(_code: str) -> str | None:+ raise RuntimeError("checker exploded")++ monkeypatch.setitem(_CHECKABLE, "python", boom)+ assert _syntax_error("anything", "python") is Nonediff --git a/tests/book/test_compile_scheduling.py b/tests/book/test_compile_scheduling.pynew file mode 100644index 000000000..bb291fe70--- /dev/null+++ b/tests/book/test_compile_scheduling.py@@ -0,0 +1,229 @@+"""Scheduling guarantees for book compilation.++Covers the two failure modes that were previously untested and invisible in+production: the same page being compiled twice concurrently (paid for twice,+one result silently discarded) and a book grinding on through a provider+outage until every chapter is half-generated.+"""++import asyncio++import pytest++from deeptutor.book.compiler import systemic_failure_reason+from deeptutor.book.engine import (+ CONSECUTIVE_PAGE_FAILURE_LIMIT,+ BookEngine,+ _BookRuntime,+)+from deeptutor.book.models import (+ Block,+ BlockStatus,+ BlockType,+ Book,+ BookStatus,+ Page,+ PageStatus,+)+++def _engine() -> BookEngine:+ """A BookEngine with no storage/compiler wiring — scheduling only."""+ engine = BookEngine.__new__(BookEngine)+ engine._global_lock = asyncio.Lock()+ engine._runtimes = {}+ return engine+++# ─────────────────────────────────────────────────────────────────────────────+# In-flight coalescing+# ─────────────────────────────────────────────────────────────────────────────+++async def test_concurrent_requests_for_a_page_share_one_run() -> None:+ engine = _engine()+ started = 0+ release = asyncio.Event()++ async def fake_compile(*, book_id, page_id, stream=None, force=False):+ nonlocal started+ started += 1+ await release.wait()+ return Page(id=page_id, book_id=book_id)++ engine._compile_page_now = fake_compile++ waiters = [+ asyncio.create_task(engine.compile_page(book_id="bk", page_id="pg_1")) for _ in range(4)+ ]+ await asyncio.sleep(0) # let them all reach the in-flight table+ release.set()+ pages = await asyncio.gather(*waiters)++ assert started == 1, "four readers opening the same page must not trigger four runs"+ assert {p.id for p in pages} == {"pg_1"}+++async def test_distinct_pages_do_not_block_each_other() -> None:+ engine = _engine()+ started: list[str] = []++ async def fake_compile(*, book_id, page_id, stream=None, force=False):+ started.append(page_id)+ return Page(id=page_id, book_id=book_id)++ engine._compile_page_now = fake_compile++ await asyncio.gather(+ engine.compile_page(book_id="bk", page_id="pg_1"),+ engine.compile_page(book_id="bk", page_id="pg_2"),+ )++ assert sorted(started) == ["pg_1", "pg_2"]+++async def test_force_waits_for_the_run_in_flight_then_starts_a_fresh_one() -> None:+ engine = _engine()+ calls: list[bool] = []+ release = asyncio.Event()++ async def fake_compile(*, book_id, page_id, stream=None, force=False):+ calls.append(force)+ if not force:+ await release.wait()+ return Page(id=page_id, book_id=book_id)++ engine._compile_page_now = fake_compile++ plain = asyncio.create_task(engine.compile_page(book_id="bk", page_id="pg_1"))+ await asyncio.sleep(0)+ forced = asyncio.create_task(engine.compile_page(book_id="bk", page_id="pg_1", force=True))+ await asyncio.sleep(0)++ assert calls == [False], "the forced pass must not interleave with the one in flight"+ release.set()+ await asyncio.gather(plain, forced)+ assert calls == [False, True]+++async def test_in_flight_entry_is_released_even_when_compilation_fails() -> None:+ engine = _engine()++ async def boom(*, book_id, page_id, stream=None, force=False):+ raise RuntimeError("provider exploded")++ engine._compile_page_now = boom++ with pytest.raises(RuntimeError):+ await engine.compile_page(book_id="bk", page_id="pg_1")++ runtime = engine._runtimes["bk"]+ await asyncio.sleep(0) # let the done-callback run+ assert runtime.in_flight == {}, "a failed run must not wedge the page forever"+++# ─────────────────────────────────────────────────────────────────────────────+# Breaker+# ─────────────────────────────────────────────────────────────────────────────+++def _page_with_failures(*kinds: str) -> Page:+ return Page(+ id="pg_1",+ book_id="bk",+ status=PageStatus.ERROR,+ blocks=[+ Block(+ type=BlockType.TEXT,+ status=BlockStatus.ERROR,+ metadata={"failure": {"kind": kind, "message": f"{kind} happened"}},+ )+ for kind in kinds+ ],+ )+++def test_provider_failures_are_systemic() -> None:+ assert systemic_failure_reason(_page_with_failures("rate_limit", "provider_error"))+ assert systemic_failure_reason(_page_with_failures("timeout", "timeout"))+++def test_the_reason_names_the_failure_so_the_reader_can_act_on_it() -> None:+ reason = systemic_failure_reason(_page_with_failures("rate_limit", "rate_limit"))+ assert reason.startswith("rate_limit:")+ assert "happened" in reason+++def test_content_failures_are_not_systemic() -> None:+ assert not systemic_failure_reason(_page_with_failures("json_parse", "empty_response"))+ assert not systemic_failure_reason(+ _page_with_failures("json_parse", "rate_limit", "json_parse")+ )+ assert not systemic_failure_reason(Page(id="pg_1", book_id="bk"))+++async def test_breaker_pauses_the_book_after_repeated_provider_failures(tmp_path) -> None:+ engine = _engine()+ runtime = _BookRuntime()+ engine._runtimes["bk"] = runtime++ saved: dict[str, Book] = {}+ logged: list[str] = []++ class _Storage:+ def load_book(self, book_id):+ return saved.get(book_id, Book(id="bk", status=BookStatus.COMPILING))++ def save_book(self, book):+ saved[book.id] = book++ def append_log(self, book_id, message, op="info"):+ logged.append(op)++ engine.storage = _Storage()++ page = _page_with_failures("rate_limit", "provider_error")+ tripped = False+ for _ in range(CONSECUTIVE_PAGE_FAILURE_LIMIT):+ tripped = await engine._record_page_outcome(runtime, "bk", page)++ assert tripped is True+ assert saved["bk"].status == BookStatus.PAUSED+ assert saved["bk"].metadata.get("pause_reason")+ assert "paused" in logged+++async def test_a_page_that_produced_something_resets_the_breaker() -> None:+ engine = _engine()+ runtime = _BookRuntime()+ runtime.consecutive_page_failures = CONSECUTIVE_PAGE_FAILURE_LIMIT - 1++ ok = Page(id="pg_2", book_id="bk", status=PageStatus.PARTIAL)+ tripped = await engine._record_page_outcome(runtime, "bk", ok)++ assert tripped is False+ assert runtime.consecutive_page_failures == 0+++# ─────────────────────────────────────────────────────────────────────────────+# Path containment+# ─────────────────────────────────────────────────────────────────────────────+++def test_book_ids_cannot_escape_the_workspace() -> None:+ """Ids arrive in request bodies and become directory names."""+ from deeptutor.book.storage import _safe_book_id++ assert "/" not in _safe_book_id("../../etc/passwd")+ assert ".." not in _safe_book_id("bk_1/../../x")+ assert _safe_book_id("bk_7c5634d091") == "bk_7c5634d091"++ for rejected in ("", " ", "..", "///"):+ with pytest.raises(ValueError):+ _safe_book_id(rejected)diff --git a/tests/book/test_cross_module_call_contracts.py b/tests/book/test_cross_module_call_contracts.pynew file mode 100644index 000000000..aeba14747--- /dev/null+++ b/tests/book/test_cross_module_call_contracts.py@@ -0,0 +1,103 @@+"""Book calls three pipelines it does not own. Pin those call shapes.++figure and interactive drive VisualizePipeline, animation drives+MathAnimatorPipeline, quiz drives QuestionPipeline. Every one is reached through+a lazy import inside a try/except, so a renamed or dropped parameter upstream+produces a GenerationFailure at compile time — a block that quietly fails for+every reader — rather than anything a type checker or an import would catch.++These assert the arguments book passes are still accepted. They deliberately+check signatures rather than calling the pipelines: the point is a cheap,+always-run tripwire, not an integration test.+"""++from __future__ import annotations++import inspect++import pytest+++def _accepted(func) -> set[str]:+ sig = inspect.signature(func)+ return set(sig.parameters) - {"self"}+++def _required(func) -> set[str]:+ sig = inspect.signature(func)+ return {+ name+ for name, p in sig.parameters.items()+ if name != "self"+ and p.default is inspect.Parameter.empty+ and p.kind not in (p.VAR_POSITIONAL, p.VAR_KEYWORD)+ }+++def _assert_call_is_valid(func, passed: set[str], label: str) -> None:+ accepted, required = _accepted(func), _required(func)+ assert passed <= accepted, f"{label}: book passes unknown args {passed - accepted}"+ assert required <= passed, f"{label}: book omits required args {required - passed}"+++# ── visualize (figure, interactive) ─────────────────────────────────────+++def test_visualize_pipeline_construction() -> None:+ from deeptutor.agents.visualize.pipeline import VisualizePipeline++ _assert_call_is_valid(+ VisualizePipeline.__init__,+ {"api_key", "base_url", "api_version", "language"},+ "VisualizePipeline()",+ )+++def test_visualize_analysis_and_generation_calls() -> None:+ from deeptutor.agents.visualize.pipeline import VisualizePipeline++ _assert_call_is_valid(+ VisualizePipeline.run_analysis,+ {"user_input", "history_context", "render_mode"},+ "run_analysis",+ )+ _assert_call_is_valid(+ VisualizePipeline.run_code_generation,+ {"user_input", "history_context", "analysis"},+ "run_code_generation",+ )+++# ── math_animator (animation) ───────────────────────────────────────────+++def test_math_animator_request_config_fields() -> None:+ """A pydantic model — check declared fields, not the generated __init__."""+ pytest.importorskip("deeptutor.agents.math_animator.pipeline")+ from deeptutor.agents.math_animator.pipeline import MathAnimatorRequestConfig++ fields = set(MathAnimatorRequestConfig.model_fields)+ passed = {"output_mode", "quality", "style_hint"}+ assert passed <= fields, f"unknown fields {passed - fields}"+++def test_math_animator_pipeline_construction() -> None:+ pytest.importorskip("deeptutor.agents.math_animator.pipeline")+ from deeptutor.agents.math_animator.pipeline import MathAnimatorPipeline++ _assert_call_is_valid(+ MathAnimatorPipeline.__init__,+ {"api_key", "base_url", "api_version", "language"},+ "MathAnimatorPipeline()",+ )+++# ── shared prompt layer ─────────────────────────────────────────────────+++def test_the_book_prompt_loader_contract() -> None:+ """Every block now goes through these two; keep their shape pinned."""+ from deeptutor.book.blocks._prompts import get_book_prompt, load_book_prompts++ assert len(_accepted(load_book_prompts)) >= 2+ assert len(_accepted(get_book_prompt)) >= 2diff --git a/tests/book/test_editing.py b/tests/book/test_editing.pynew file mode 100644index 000000000..888ccee5e--- /dev/null+++ b/tests/book/test_editing.py@@ -0,0 +1,134 @@+"""Reader-authored content: in-place edits, notes, and remediation.++Covers the promise the UI used to make and could not keep — the note block+invited you to "start writing" with nowhere to write — plus the rule that+makes editing safe to offer at all: a forced regenerate must not silently+delete what the reader wrote.+"""++from __future__ import annotations++import pytest++from deeptutor.book.engine import BookEngine+from deeptutor.book.models import Block, BlockStatus, BlockType, Page, PageStatus+++class _Storage:+ """In-memory stand-in holding exactly one page."""++ def __init__(self, page: Page) -> None:+ self.page = page+ self.logs: list[str] = []++ def load_page(self, book_id: str, page_id: str) -> Page | None:+ return self.page if page_id == self.page.id else None++ def save_page(self, page: Page) -> None:+ self.page = page++ def append_log(self, book_id: str, message: str, op: str = "info") -> None:+ self.logs.append(op)+++def _engine(page: Page) -> BookEngine:+ engine = BookEngine.__new__(BookEngine)+ engine.storage = _Storage(page)+ from deeptutor.book.compiler import BookCompiler, CompilerOptions++ engine.compiler = BookCompiler.__new__(BookCompiler)+ engine.compiler.options = CompilerOptions()+ return engine+++# ── Editing ─────────────────────────────────────────────────────────────+++async def test_editing_a_note_stores_the_body() -> None:+ note = Block(type=BlockType.USER_NOTE, status=BlockStatus.READY, payload={"body": ""})+ page = Page(id="pg_1", book_id="bk", blocks=[note])+ engine = _engine(page)++ updated = await engine.update_block(+ book_id="bk", page_id="pg_1", block_id=note.id, body="my annotation"+ )++ assert updated is not None+ assert updated.payload["body"] == "my annotation"+ assert updated.metadata["edited_by_user"] is True+++async def test_editing_a_text_block_writes_the_key_it_already_uses() -> None:+ # Overview blocks store prose under `content`; generated ones use `body`.+ block = Block(type=BlockType.TEXT, status=BlockStatus.READY, payload={"content": "original"})+ page = Page(id="pg_1", book_id="bk", blocks=[block])+ engine = _engine(page)++ updated = await engine.update_block(+ book_id="bk", page_id="pg_1", block_id=block.id, body="corrected"+ )++ assert updated is not None+ assert updated.payload["content"] == "corrected"+ assert "body" not in updated.payload, "an edit must land where the renderer reads"+++async def test_structured_blocks_are_not_editable_as_plain_text() -> None:+ quiz = Block(type=BlockType.QUIZ, status=BlockStatus.READY, payload={"questions": []})+ page = Page(id="pg_1", book_id="bk", blocks=[quiz])+ engine = _engine(page)++ assert (+ await engine.update_block(book_id="bk", page_id="pg_1", block_id=quiz.id, body="nope")+ is None+ )+++def test_a_forced_regenerate_keeps_hand_edited_prose() -> None:+ edited = Block(+ type=BlockType.TEXT,+ status=BlockStatus.READY,+ payload={"body": "I fixed this sentence"},+ metadata={"edited_by_user": True},+ )+ generated = Block(type=BlockType.TEXT, status=BlockStatus.READY, payload={"body": "untouched"})+ page = Page(status=PageStatus.READY, blocks=[edited, generated])++ BookEngine._reset_page_for_force_compile(page)++ assert edited.payload == {"body": "I fixed this sentence"}+ assert edited.status == BlockStatus.READY+ assert generated.payload == {}+ assert generated.status == BlockStatus.PENDING+++# ── Remediation ─────────────────────────────────────────────────────────+++async def test_supplement_is_idempotent_per_topic() -> None:+ """Three generated blocks a click is too expensive to duplicate."""+ existing = Block(+ type=BlockType.TEXT,+ status=BlockStatus.READY,+ params={"role": "remediation", "topic": "gradients"},+ )+ page = Page(id="pg_1", book_id="bk", blocks=[existing])+ engine = _engine(page)++ inserted: list[str] = []++ async def _fail_insert(**kwargs):+ inserted.append(kwargs["block_type"].value)++ engine.insert_block = _fail_insert++ result = await engine.supplement_for_weakness(+ book_id="bk", page_id="pg_1", topic=" gradients "+ )++ assert result is existing+ assert inserted == [], "asking twice must not stack a second remediation"diff --git a/tests/book/test_event_hub.py b/tests/book/test_event_hub.pynew file mode 100644index 000000000..6a028510d--- /dev/null+++ b/tests/book/test_event_hub.py@@ -0,0 +1,124 @@+"""The book event stream must outlive the request that started the work.++Regression cover for the bug this module exists to fix: background compilation+published into a bus the router had already closed, so every ``block_ready``+after ``confirm_spine`` returned was silently dropped and the reader watched a+frozen page for the whole build.+"""++import asyncio++import pytest++from deeptutor.book import event_hub+from deeptutor.book.event_hub import (+ BOOK_EVENT_HISTORY_LIMIT,+ close_book_bus,+ get_book_bus,+ get_book_stream,+)+from deeptutor.book.streaming import SOURCE as BOOK_SOURCE++[email protected](autouse=True)+def _clean_hub():+ event_hub._buses.clear()+ yield+ event_hub._buses.clear()+++async def _drain(bus, count, timeout=1.0):+ """Collect *count* events from a fresh subscription."""+ received = []++ async def _read():+ async for event in bus.subscribe():+ received.append(event)+ if len(received) >= count:+ return++ await asyncio.wait_for(_read(), timeout=timeout)+ return received+++def test_the_same_book_always_gets_the_same_bus() -> None:+ assert get_book_bus("bk_1") is get_book_bus("bk_1")+ assert get_book_bus("bk_1") is not get_book_bus("bk_2")+++async def test_a_late_subscriber_catches_up_on_what_it_missed() -> None:+ """A reader who refreshes mid-compilation must not see a frozen page."""+ stream = get_book_stream("bk_1")+ await stream.book_event("page_planned", {"page_id": "pg_1"})+ await stream.book_event("block_ready", {"block_id": "blk_1"})++ events = await _drain(get_book_bus("bk_1"), 2)++ assert [e.metadata["kind"] for e in events] == ["page_planned", "block_ready"]+++async def test_background_events_still_arrive_after_the_action_returns() -> None:+ """The exact shape of the original bug, in miniature.++ A client subscribes, an action finishes and its handler unwinds, and only+ *then* does background work emit. Those events must still be delivered.+ """+ bus = get_book_bus("bk_1")+ received: list[str] = []+ ready = asyncio.Event()++ async def watcher():+ async for event in bus.subscribe():+ received.append(str(event.metadata.get("kind")))+ ready.set()++ task = asyncio.create_task(watcher())+ await asyncio.sleep(0)++ # …the request handler returns here; previously it closed the bus …+ await get_book_stream("bk_1").book_event("block_ready", {"block_id": "blk_late"})++ await asyncio.wait_for(ready.wait(), timeout=1.0)+ task.cancel()+ assert received == ["block_ready"]+++async def test_history_is_bounded_so_a_long_build_cannot_grow_without_limit() -> None:+ stream = get_book_stream("bk_1")+ for index in range(BOOK_EVENT_HISTORY_LIMIT + 25):+ await stream.book_event("block_ready", {"index": index})++ bus = get_book_bus("bk_1")+ assert len(bus._history) == BOOK_EVENT_HISTORY_LIMIT+ # The tail is what a reconnecting client cares about.+ assert bus._history[-1].metadata["index"] == BOOK_EVENT_HISTORY_LIMIT + 24+++async def test_deleting_a_book_ends_its_stream() -> None:+ bus = get_book_bus("bk_1")+ finished = asyncio.Event()++ async def watcher():+ async for _ in bus.subscribe():+ pass+ finished.set()++ task = asyncio.create_task(watcher())+ await asyncio.sleep(0)++ close_book_bus("bk_1")++ await asyncio.wait_for(finished.wait(), timeout=1.0)+ await task+ assert get_book_bus("bk_1") is not bus, "a deleted book must not reuse its closed bus"+++async def test_events_carry_the_book_source_so_sockets_can_filter() -> None:+ await get_book_stream("bk_1").book_event("spine_ready", {"chapter_count": 3})+ (event,) = await _drain(get_book_bus("bk_1"), 1)+ assert event.source == BOOK_SOURCEdiff --git a/tests/book/test_export.py b/tests/book/test_export.pynew file mode 100644index 000000000..3c95dc4ba--- /dev/null+++ b/tests/book/test_export.py@@ -0,0 +1,187 @@+"""Markdown export — a generated book has to be able to leave the app."""++from deeptutor.book.export import export_filename, render_block, render_book_markdown+from deeptutor.book.models import (+ Block,+ BlockStatus,+ BlockType,+ Book,+ Page,+)+++def _ready(block_type: BlockType, payload: dict, **kwargs) -> Block:+ return Block(type=block_type, status=BlockStatus.READY, payload=payload, **kwargs)+++def test_section_renders_intro_subsections_and_takeaway() -> None:+ md = render_block(+ _ready(+ BlockType.SECTION,+ {+ "intro": "Opening paragraph.",+ "subsections": [{"heading": "First", "body": "Body one."}],+ "key_takeaway": "The thing to remember.",+ },+ )+ )+ assert "Opening paragraph." in md+ assert "### First" in md+ assert "Body one." in md+ assert "> **Key takeaway** — The thing to remember." in md+++def test_quiz_hides_the_answer_behind_a_details_block() -> None:+ md = render_block(+ _ready(+ BlockType.QUIZ,+ {+ "questions": [+ {+ "question": "What is 2+2?",+ "options": {"a": "3", "b": "4"},+ "correct_answer": "B",+ "explanation": "Addition.",+ }+ ]+ },+ )+ )+ assert "**1. What is 2+2?**" in md+ assert "- **A.** 3" in md+ assert "<details><summary>Answer</summary>" in md+ assert "_Addition._" in md+++def test_flash_cards_become_a_table_with_escaped_pipes() -> None:+ md = render_block(+ _ready(+ BlockType.FLASH_CARDS,+ {"cards": [{"front": "a|b", "back": "c"}]},+ )+ )+ assert "| Front | Back |" in md+ assert r"a\|b" in md+++def test_unrendered_blocks_contribute_nothing() -> None:+ pending = Block(type=BlockType.TEXT, status=BlockStatus.PENDING, payload={"body": "x"})+ assert render_block(pending) == ""+ assert render_block(_ready(BlockType.TEXT, {})) == ""+++def test_a_visual_with_no_text_says_so_rather_than_vanishing() -> None:+ md = render_block(_ready(BlockType.ANIMATION, {}))+ assert "animation" in md.lower()+++def test_bridge_text_precedes_the_block_it_introduces() -> None:+ md = render_block(+ _ready(+ BlockType.CALLOUT,+ {"bridge_text": "Which brings us to…", "label": "Key idea", "body": "It matters."},+ )+ )+ assert md.index("Which brings us to…") < md.index("Key idea")+++def test_whole_book_carries_title_chapters_and_objectives() -> None:+ book = Book(title="My Book", description="A guide.", page_count=1)+ page = Page(+ id="pg_1",+ book_id=book.id,+ title="Chapter One",+ learning_objectives=["Understand X"],+ blocks=[_ready(BlockType.TEXT, {"body": "Hello."})],+ )+ md = render_book_markdown(book, None, [page])++ assert md.startswith("# My Book")+ assert "*A guide.*" in md+ assert "## Chapter One" in md+ assert "- Understand X" in md+ assert "Hello." in md+ assert md.endswith("\n")+++def test_an_ungenerated_chapter_is_marked_rather_than_dropped() -> None:+ book = Book(title="My Book")+ page = Page(id="pg_1", book_id=book.id, title="Not yet")+ md = render_book_markdown(book, None, [page])+ assert "## Not yet" in md+ assert "not been generated" in md+++def test_chapters_export_in_reading_order() -> None:+ book = Book(title="B")+ pages = [+ Page(id="pg_2", book_id=book.id, title="Second", order=2),+ Page(id="pg_1", book_id=book.id, title="First", order=1),+ ]+ md = render_book_markdown(book, None, pages)+ assert md.index("## First") < md.index("## Second")+++def test_filenames_survive_cjk_and_punctuation() -> None:+ assert export_filename(Book(title="Agentic RAG: 从静态到自治")) == (+ "Agentic-RAG-从静态到自治.md"+ )+ assert export_filename(Book(title=" ")) == "book.md"+ assert export_filename(Book(title="///")) == "book.md"+++# ── Language awareness + header safety ──────────────────────────────────+++def test_a_chinese_book_exports_with_chinese_scaffolding() -> None:+ book = Book(title="智能体检索增强", language="zh", knowledge_bases=["kb1"])+ page = Page(+ id="pg_1",+ book_id=book.id,+ title="第一章",+ blocks=[+ _ready(BlockType.SECTION, {"intro": "导言", "key_takeaway": "记住这个"}),+ _ready(BlockType.FLASH_CARDS, {"cards": [{"front": "问", "back": "答"}]}),+ _ready(BlockType.QUIZ, {"questions": [{"question": "Q", "correct_answer": "A"}]}),+ ],+ )+ md = render_book_markdown(book, None, [page])++ assert "**来源:**" in md and "**Sources:**" not in md+ assert "> **要点** —" in md and "Key takeaway" not in md+ assert "| 正面 | 背面 |" in md and "| Front | Back |" not in md+ assert "<details><summary>答案</summary>" in md+++def test_an_unknown_language_falls_back_to_english() -> None:+ book = Book(title="Buch", language="de")+ page = Page(+ id="pg_1",+ book_id=book.id,+ title="Kapitel",+ blocks=[_ready(BlockType.SECTION, {"intro": "x", "key_takeaway": "y"})],+ )+ assert "> **Key takeaway** —" in render_book_markdown(book, None, [page])+++def test_deep_dive_suggestions_render_as_the_generator_emits_them() -> None:+ """The generator produces dicts; a string-only filter dropped the block."""+ md = render_block(+ _ready(+ BlockType.DEEP_DIVE,+ {"suggestions": [{"topic": "Attention", "rationale": "the core idea"}]},+ )+ )+ assert "**Attention**" in md+ assert "the core idea" in md+++def test_export_filenames_survive_a_latin_1_hostile_title() -> None:+ from deeptutor.api.utils.http_headers import content_disposition++ header = content_disposition(+ export_filename(Book(title="智能体检索增强")), disposition="attachment"+ )+ # HTTP/1.1 headers are latin-1; this used to raise UnicodeEncodeError and 500.+ header.encode("latin-1")+ assert "filename*=UTF-8''" in headerdiff --git a/tests/book/test_overview_chapter.py b/tests/book/test_overview_chapter.pynew file mode 100644index 000000000..b0949f40c--- /dev/null+++ b/tests/book/test_overview_chapter.py@@ -0,0 +1,133 @@+"""The engine-injected Overview chapter must stay singular and non-destructive.++Two defects motivated these: the idempotency guard keyed on ``chapters[0]``, so+any caller handing the spine back with the overview elsewhere (the spine editor+re-appends hidden chapters) grew a second overview on every re-confirm; and the+overview page is rebuilt wholesale, which is the one path the ``edited_by_user``+protection cannot reach.+"""++from __future__ import annotations++import pytest++from deeptutor.book.engine import BookEngine, _is_auto_overview+from deeptutor.book.models import (+ Block,+ BlockStatus,+ BlockType,+ Book,+ Chapter,+ ConceptGraph,+ ContentType,+ Page,+ PageStatus,+ Spine,+)+++def _engine() -> BookEngine:+ return BookEngine.__new__(BookEngine)+++def _spine(*chapters: Chapter) -> Spine:+ return Spine(book_id="bk", chapters=list(chapters), concept_graph=ConceptGraph())+++def _authored(title: str, order: int) -> Chapter:+ return Chapter(title=title, content_type=ContentType.THEORY, order=order)+++async def test_overview_is_injected_once() -> None:+ engine, book = _engine(), Book(id="bk", language="en")+ spine = await engine._ensure_overview_chapter(+ _spine(_authored("One", 0), _authored("Two", 1)), book, stream=None+ )++ assert sum(1 for c in spine.chapters if _is_auto_overview(c)) == 1+ assert _is_auto_overview(spine.chapters[0])+ assert [c.order for c in spine.chapters] == [0, 1, 2]+++async def test_re_confirming_does_not_add_a_second_overview() -> None:+ engine, book = _engine(), Book(id="bk", language="en")+ spine = await engine._ensure_overview_chapter(_spine(_authored("One", 0)), book, stream=None)+ again = await engine._ensure_overview_chapter(spine, book, stream=None)++ assert sum(1 for c in again.chapters if _is_auto_overview(c)) == 1+++async def test_an_overview_that_came_back_out_of_position_is_reseated() -> None:+ """The spine editor hides the overview and re-attaches it around the edits."""+ engine, book = _engine(), Book(id="bk", language="en")+ overview = Chapter(title="How to read this book", content_type=ContentType.OVERVIEW)+ # Overview last — the shape that used to defeat the guard entirely.+ spine = _spine(_authored("One", 0), _authored("Two", 1), overview)++ result = await engine._ensure_overview_chapter(spine, book, stream=None)++ assert sum(1 for c in result.chapters if _is_auto_overview(c)) == 1+ assert result.chapters[0] is overview, "the overview must lead the book"+ assert [c.order for c in result.chapters] == [0, 1, 2], "orders must be contiguous"+++async def test_duplicate_overviews_from_older_data_are_collapsed() -> None:+ engine, book = _engine(), Book(id="bk", language="en")+ first = Chapter(title="How to read this book", content_type=ContentType.OVERVIEW)+ stale = Chapter(title="How to read this book", content_type=ContentType.OVERVIEW)+ spine = _spine(first, _authored("One", 1), stale)++ result = await engine._ensure_overview_chapter(spine, book, stream=None)++ assert sum(1 for c in result.chapters if _is_auto_overview(c)) == 1+ assert len(result.chapters) == 2+++# ── Rebuild preserves reader-authored content ───────────────────────────+++class _Storage:+ def __init__(self) -> None:+ self.saved: list[Page] = []++ def save_page(self, page: Page) -> None:+ self.saved.append(page)+++async def test_rebuilding_the_overview_keeps_notes_and_hand_edits() -> None:+ engine = _engine()+ engine.storage = _Storage()+ book = Book(id="bk", language="en", title="B")++ note = Block(type=BlockType.USER_NOTE, status=BlockStatus.READY, payload={"body": "my note"})+ edited_intro = Block(+ type=BlockType.TEXT,+ status=BlockStatus.READY,+ params={"role": "overview_intro"},+ payload={"content": "my own introduction"},+ metadata={"edited_by_user": True},+ )+ overview_chapter = Chapter(title="How to read this book", content_type=ContentType.OVERVIEW)+ page = Page(+ id="pg_0",+ book_id="bk",+ chapter_id=overview_chapter.id,+ content_type=ContentType.OVERVIEW,+ status=PageStatus.PENDING,+ blocks=[edited_intro, note],+ )+ spine = _spine(overview_chapter, _authored("One", 1))++ await engine._materialize_overview_page(spine, [page], book, stream=None)++ bodies = [b.payload.get("content", "") for b in page.blocks]+ assert "my own introduction" in bodies, "a hand-edited intro must survive"+ assert note in page.blocks, "the reader's note must survive"+ # The un-edited deterministic blocks are still refreshed from the spine.+ assert any(b.type == BlockType.CONCEPT_GRAPH for b in page.blocks)+ assert page.status == PageStatus.READYdiff --git a/tests/book/test_overview_copy.py b/tests/book/test_overview_copy.pynew file mode 100644index 000000000..387beef31--- /dev/null+++ b/tests/book/test_overview_copy.py@@ -0,0 +1,83 @@+"""The Overview page is built without an LLM, so its copy is ours to get right.++Every other block's wording comes from the model in the book's language. This+one page is rendered deterministically, so its strings used to be+`"中文" if language == "zh" else "English"` conditionals in engine.py — which is+why the language picker could offer eleven languages while the book's own front+page spoke two.++These tests pin the table's shape and keep the remaining gap countable rather+than implicit.+"""++from __future__ import annotations++import pytest++from deeptutor.book.overview_copy import (+ _COPY,+ REQUIRED_KEYS,+ missing_languages,+ overview_copy,+)++# What the creator's picker offers (BookCreator.BOOK_LANGUAGES).+PICKER_LANGUAGES = [+ "en",+ "zh",+ "zh-tw",+ "ja",+ "ko",+ "es",+ "fr",+ "de",+ "ru",+ "pt",+ "it",+]++[email protected]("language", sorted(_COPY))+def test_every_entry_defines_every_key(language: str) -> None:+ """A partial translation would render a stray English string mid-page."""+ missing = REQUIRED_KEYS - set(_COPY[language])+ assert not missing, f"{language} is missing {missing}"++[email protected]("language", sorted(_COPY))+def test_the_intro_body_interpolates(language: str) -> None:+ body = _COPY[language]["intro_body"].format(concepts=7, chapters=3)+ assert "7" in body and "3" in body+ assert "{" not in body++[email protected]("language", sorted(_COPY))+def test_objectives_are_a_non_empty_list_of_strings(language: str) -> None:+ objectives = _COPY[language]["objectives"]+ assert isinstance(objectives, list) and objectives+ assert all(isinstance(o, str) and o.strip() for o in objectives)+++def test_a_regional_tag_resolves_to_its_base_language() -> None:+ assert overview_copy("zh-tw") is _COPY["zh"]+ assert overview_copy("zh-CN") is _COPY["zh"]+++def test_an_unknown_language_falls_back_to_english_rather_than_breaking() -> None:+ for unknown in ("ja", "kl", "", None, " "):+ assert overview_copy(unknown) is _COPY["en"]+++def test_the_translation_gap_is_reported_honestly() -> None:+ """Not a failure — a ledger. Adding a language is one entry in _COPY."""+ gap = missing_languages(PICKER_LANGUAGES)+ covered = len(PICKER_LANGUAGES) - len(gap)+ assert covered >= 3, "en, zh and zh-tw (via fallback) must be covered"+ # If this trips, someone translated more languages — update the number,+ # and be glad.+ assert set(gap) <= {"ja", "ko", "es", "fr", "de", "ru", "pt", "it"}+++def test_english_is_always_present_because_it_is_the_fallback() -> None:+ assert "en" in _COPY+ assert REQUIRED_KEYS <= set(_COPY["en"])diff --git a/tests/book/test_progress.py b/tests/book/test_progress.pynew file mode 100644index 000000000..7fd76ac70--- /dev/null+++ b/tests/book/test_progress.py@@ -0,0 +1,133 @@+"""Reading progress: position, bookmarks, and derived quiz stats.++These three fields existed on the model from the beginning and were never once+written to, so none of this behaviour had cover.+"""++from deeptutor.book import progress as progress_ops+from deeptutor.book.models import Progress, QuizAttempt++PAGE_TO_CHAPTER = {"pg_1": "ch_1", "pg_2": "ch_2"}+++def _attempt(question: str, correct: bool | None, *, page="pg_1", ts=1.0) -> QuizAttempt:+ return QuizAttempt(+ block_id="blk_1",+ page_id=page,+ question_id=question,+ user_answer="A",+ is_correct=correct,+ timestamp=ts,+ )+++# ── Position ────────────────────────────────────────────────────────────+++def test_visiting_a_page_records_position_once() -> None:+ progress = Progress(book_id="bk")++ assert progress_ops.mark_visited(progress, "pg_1") is True+ assert progress.current_page_id == "pg_1"+ assert progress.visited_page_ids == ["pg_1"]++ # Re-reading the same page is not a change worth a disk write.+ assert progress_ops.mark_visited(progress, "pg_1") is False+ assert progress.visited_page_ids == ["pg_1"]+++def test_moving_on_updates_position_without_forgetting_history() -> None:+ progress = Progress(book_id="bk")+ progress_ops.mark_visited(progress, "pg_1")+ progress_ops.mark_visited(progress, "pg_2")++ assert progress.current_page_id == "pg_2"+ assert progress.visited_page_ids == ["pg_1", "pg_2"]+++def test_bookmarks_toggle() -> None:+ progress = Progress(book_id="bk")+ assert progress_ops.toggle_bookmark(progress, "pg_1") is True+ assert progress.bookmarked_page_ids == ["pg_1"]+ assert progress_ops.toggle_bookmark(progress, "pg_1") is False+ assert progress.bookmarked_page_ids == []+++def test_completion_ratio_is_clamped() -> None:+ progress = Progress(book_id="bk", visited_page_ids=["pg_1", "pg_1", "pg_2"])+ assert progress_ops.completion_ratio(progress, 4) == 0.5+ assert progress_ops.completion_ratio(progress, 1) == 1.0+ assert progress_ops.completion_ratio(progress, 0) == 0.0+++# ── Derived stats ───────────────────────────────────────────────────────+++def test_answering_the_same_question_again_does_not_inflate_the_score() -> None:+ progress = Progress(book_id="bk")+ for ts in (1.0, 2.0, 3.0):+ progress_ops.record_attempt(+ progress,+ page_id="pg_1",+ block_id="blk_1",+ question_id="q1",+ user_answer="A",+ is_correct=True,+ page_to_chapter=PAGE_TO_CHAPTER,+ )+ assert progress.score == 1+++def test_getting_it_right_clears_the_weak_chapter() -> None:+ progress = Progress(book_id="bk")+ progress_ops.record_attempt(+ progress,+ page_id="pg_1",+ block_id="blk_1",+ question_id="q1",+ user_answer="B",+ is_correct=False,+ page_to_chapter=PAGE_TO_CHAPTER,+ )+ assert progress.weak_chapters == ["ch_1"]++ progress_ops.record_attempt(+ progress,+ page_id="pg_1",+ block_id="blk_1",+ question_id="q1",+ user_answer="A",+ is_correct=True,+ page_to_chapter=PAGE_TO_CHAPTER,+ )+ assert progress.weak_chapters == [], "a corrected mistake must not brand the chapter"+ assert progress.score == 1+++def test_an_ungraded_written_answer_counts_neither_way() -> None:+ progress = Progress(book_id="bk")+ progress_ops.record_attempt(+ progress,+ page_id="pg_1",+ block_id="blk_1",+ question_id="q1",+ user_answer="",+ is_correct=None,+ page_to_chapter=PAGE_TO_CHAPTER,+ )+ assert progress.score == 0+ assert progress.weak_chapters == []+++def test_latest_attempt_wins_per_question() -> None:+ progress = Progress(+ book_id="bk",+ quiz_attempts=[+ _attempt("q1", False, ts=1.0),+ _attempt("q1", True, ts=2.0),+ _attempt("q2", True, ts=1.0),+ _attempt("q2", False, ts=2.0, page="pg_2"),+ ],+ )+ assert progress_ops.recompute_score(progress) == 1+ assert progress_ops.recompute_weak_chapters(progress, PAGE_TO_CHAPTER) == ["ch_2"]diff --git a/tests/book/test_quiz_extraction.py b/tests/book/test_quiz_extraction.pynew file mode 100644index 000000000..80d38f84d--- /dev/null+++ b/tests/book/test_quiz_extraction.py@@ -0,0 +1,153 @@+"""Quiz reads QuestionPipeline's result directly, not the legacy summary shape.++`AgentCoordinator` is a documented legacy facade; going through it also built a+throwaway StreamBus, so progress from the book's slowest block was discarded.+Reading the pipeline directly means the extraction has to apply the `success`+rule the facade used to back-fill.+"""++from __future__ import annotations++from deeptutor.book.blocks.quiz import QuizGenerator+++def _qa(qid: str) -> dict:+ return {+ "question_id": qid,+ "question": f"Q{qid}?",+ "question_type": "single_choice",+ "options": {"a": "1", "b": "2"},+ "correct_answer": "A",+ "explanation": "because",+ }+++def test_explicit_success_flags_are_honoured() -> None:+ summary = {+ "results": [+ {"success": True, "qa_pair": _qa("1")},+ {"success": False, "qa_pair": _qa("2")},+ ]+ }+ got = QuizGenerator._extract_questions(summary)+ assert [q["question_id"] for q in got] == ["1"]+++def test_missing_success_falls_back_to_the_error_marker() -> None:+ """The pipeline's native shape has no `success` key — the facade added it."""+ summary = {+ "results": [+ {"qa_pair": _qa("1"), "metadata": {}},+ {"qa_pair": _qa("2"), "metadata": {"error": "generation failed"}},+ {"qa_pair": _qa("3")}, # no metadata at all → keep+ ]+ }+ got = QuizGenerator._extract_questions(summary)+ assert [q["question_id"] for q in got] == ["1", "3"]+++def test_malformed_entries_are_skipped_not_crashed() -> None:+ summary = {"results": ["nonsense", None, 42, {"qa_pair": "not a dict"}]}+ assert QuizGenerator._extract_questions(summary) == []+++def test_an_empty_or_absent_result_set_yields_nothing() -> None:+ assert QuizGenerator._extract_questions({}) == []+ assert QuizGenerator._extract_questions({"results": []}) == []+ assert QuizGenerator._extract_questions({"results": "not a list"}) == []+++def test_the_question_shape_is_preserved() -> None:+ got = QuizGenerator._extract_questions({"results": [{"success": True, "qa_pair": _qa("7")}]})+ assert got[0]["question"] == "Q7?"+ assert got[0]["question_type"] == "single_choice"+ assert got[0]["options"] == {"a": "1", "b": "2"}+++def test_the_legacy_facade_is_no_longer_imported() -> None:+ """The name may still appear in a comment; what matters is the import."""+ import ast+ import inspect++ import deeptutor.book.blocks.quiz as module++ imported: set[str] = set()+ for node in ast.walk(ast.parse(inspect.getsource(module))):+ if isinstance(node, ast.ImportFrom):+ imported.update(alias.name for alias in node.names)+ elif isinstance(node, ast.Import):+ imported.update(alias.name for alias in node.names)++ assert "AgentCoordinator" not in imported+ assert "QuestionPipeline" in imported+++# ── Call contract ───────────────────────────────────────────────────────+#+# Quiz calls QuestionPipeline directly now, so a signature change upstream+# would only surface when a reader actually generates a quiz. These pin the+# contract at import time instead.+++def test_the_pipeline_call_is_signature_correct() -> None:+ import inspect++ from deeptutor.agents.question.pipeline import QuestionPipeline++ run = inspect.signature(QuestionPipeline.run)+ accepted = set(run.parameters) - {"self"}+ passed = {+ "context",+ "user_message",+ "num_questions",+ "difficulty",+ "question_types",+ "stream",+ }+ assert passed <= accepted, f"quiz passes unknown args: {passed - accepted}"++ required = {+ name+ for name, p in run.parameters.items()+ if name != "self"+ and p.default is inspect.Parameter.empty+ and p.kind not in (p.VAR_POSITIONAL, p.VAR_KEYWORD)+ }+ assert required <= passed, f"quiz omits required args: {required - passed}"+++def test_the_pipeline_constructor_accepts_what_quiz_passes() -> None:+ import inspect++ from deeptutor.agents.question.pipeline import QuestionPipeline++ ctor = set(inspect.signature(QuestionPipeline.__init__).parameters) - {"self"}+ assert {"language", "kb_name"} <= ctor+++def test_the_context_fields_quiz_sets_all_exist() -> None:+ import inspect++ from deeptutor.core.context import UnifiedContext++ fields = set(inspect.signature(UnifiedContext.__init__).parameters) - {"self"}+ mine = {+ "session_id",+ "user_message",+ "active_capability",+ "knowledge_bases",+ "language",+ }+ assert mine <= fields, f"unknown UnifiedContext fields: {mine - fields}"+++def test_progress_reaches_the_books_own_stream() -> None:+ """The reason for going direct: the facade discarded the stream."""+ import inspect++ import deeptutor.book.blocks.quiz as module++ source = inspect.getsource(module)+ assert "get_book_bus(ctx.book_id)" in source, (+ "quiz must publish into the book's long-lived bus, not a throwaway one"+ )diff --git a/tests/book/test_runtime_reclaim.py b/tests/book/test_runtime_reclaim.pyindex a6b9428e1..099878e65 100644--- a/tests/book/test_runtime_reclaim.py+++ b/tests/book/test_runtime_reclaim.py@@ -22,4 +22,7 @@ async def test_idle_background_runtime_is_released(monkeypatch) -> None:assert "book-1" not in engine._runtimesassert runtime.worker is None- assert runtime.stream is None+ # The runtime no longer holds an event stream at all — streams live in+ # ``event_hub`` so background progress survives the request that queued it.+ assert not hasattr(runtime, "stream")+ assert runtime.in_flight == {}diff --git a/tests/book/test_source_exploration_budget.py b/tests/book/test_source_exploration_budget.pynew file mode 100644index 000000000..253f3457e--- /dev/null+++ b/tests/book/test_source_exploration_budget.py@@ -0,0 +1,51 @@+"""The source sweep must stay bounded, and stay fair when it is bounded.++One retrieval per (knowledge base x query) pair, each a vector search plus an+LLM synthesis on most backends. Ungated, eight KBs against a dozen queries+fired ~100 concurrent provider calls. Capping is only half the fix: capping a+KB-major list would spend the whole budget on the first few knowledge bases.+"""++from __future__ import annotations++from deeptutor.book.agents.source_explorer import (+ MAX_RETRIEVAL_CALLS,+ RETRIEVAL_CONCURRENCY,+)+++def _pairs(kbs: list[str], queries: list[str]) -> list[tuple[str, str]]:+ """The interleaving the explorer uses, then the same cap it applies."""+ return [(kb, q) for q in queries for kb in kbs][:MAX_RETRIEVAL_CALLS]+++def test_the_budget_is_actually_bounded() -> None:+ pairs = _pairs([f"kb{i}" for i in range(8)], [f"q{i}" for i in range(12)])+ assert len(pairs) == MAX_RETRIEVAL_CALLS+ assert MAX_RETRIEVAL_CALLS < 8 * 12, "the cap must bite on a realistic fan-out"+++def test_capping_still_covers_every_knowledge_base() -> None:+ kbs = [f"kb{i}" for i in range(8)]+ pairs = _pairs(kbs, [f"q{i}" for i in range(12)])+ assert {kb for kb, _ in pairs} == set(kbs), "a knowledge base was starved"+++def test_kb_major_ordering_would_have_starved_most_of_them() -> None:+ """Guards the ordering itself, not just the cap."""+ kbs = [f"kb{i}" for i in range(8)]+ queries = [f"q{i}" for i in range(12)]+ kb_major = [(kb, q) for kb in kbs for q in queries][:MAX_RETRIEVAL_CALLS]+ assert len({kb for kb, _ in kb_major}) < len(kbs), (+ "if this passes, the interleaving no longer matters — re-check the fix"+ )+++def test_small_workloads_are_untouched() -> None:+ kbs, queries = ["kb0", "kb1"], ["q0", "q1", "q2"]+ assert len(_pairs(kbs, queries)) == len(kbs) * len(queries)+++def test_concurrency_gate_is_sane() -> None:+ assert 1 <= RETRIEVAL_CONCURRENCY <= 16+ assert RETRIEVAL_CONCURRENCY < MAX_RETRIEVAL_CALLSdiff --git a/tests/book/test_source_partitioning.py b/tests/book/test_source_partitioning.pynew file mode 100644index 000000000..cea4b8eb2--- /dev/null+++ b/tests/book/test_source_partitioning.py@@ -0,0 +1,91 @@+"""Retrieval must tell indexed knowledge bases apart from connected pointers.++A connected KB — an Obsidian vault, a subagent CLI, a remote LightRAG or IMA+library — has no local index, so `rag_search` returns nothing. Sweeping them+anyway looked exactly like a source with no relevant content, so a reader who+attached their vault never learned it contributed zero.+"""++from __future__ import annotations++import pytest++from deeptutor.book.agents.source_explorer import SourceExplorer, _balanced_slice+from deeptutor.book.models import SourceChunk+++def _chunk(source: str, kb: str, score: float) -> SourceChunk:+ return SourceChunk(+ chunk_id=f"{kb}-{score}",+ kb_name=kb,+ source=source,+ ref="r",+ text="t",+ score=score,+ query="q",+ )+++def fake_metadata(monkeypatch):+ table: dict[str, dict] = {}++ def _resolve(kb_ref):+ return table.get(kb_ref)++ monkeypatch.setattr("deeptutor.multi_user.knowledge_access.resolve_kb_metadata", _resolve)+ return table+++def test_connected_kbs_are_separated_from_indexed_ones(fake_metadata) -> None:+ fake_metadata.update(+ {+ "my-vault": {"type": "obsidian"},+ "my-agent": {"type": "subagent"},+ "papers": {"type": "local"},+ }+ )+ retrievable, connected = SourceExplorer.partition_knowledge_bases(+ ["papers", "my-vault", "my-agent"]+ )+ assert retrievable == ["papers"]+ assert sorted(connected) == ["my-agent", "my-vault"]+++def test_unresolvable_references_are_treated_as_ordinary(fake_metadata) -> None:+ """A KB we cannot resolve must not be silently dropped from the sweep."""+ retrievable, connected = SourceExplorer.partition_knowledge_bases(["mystery"])+ assert retrievable == ["mystery"]+ assert connected == []+++# ── Balanced slice ──────────────────────────────────────────────────────+++def test_one_engines_score_scale_cannot_crowd_out_the_others() -> None:+ """Cosine, BM25 and a remote service score on different scales."""+ chunks = (+ [_chunk("kb", "vector_kb", 90 - i) for i in range(30)]+ + [_chunk("kb", "bm25_kb", 0.9 - i * 0.01) for i in range(30)]+ + [_chunk("notebook", "", 0.0) for _ in range(5)]+ )++ globally_sorted = sorted(chunks, key=lambda c: -c.score)[:24]+ assert len({(c.source, c.kb_name) for c in globally_sorted}) == 1, (+ "precondition: a global sort collapses to one source"+ )++ balanced = _balanced_slice(chunks, limit=24)+ assert len(balanced) == 24+ assert len({(c.source, c.kb_name) for c in balanced}) == 3+++def test_within_a_source_the_best_chunks_still_win() -> None:+ chunks = [_chunk("kb", "a", float(i)) for i in range(10)]+ picked = _balanced_slice(chunks, limit=3)+ assert [c.score for c in picked] == [9.0, 8.0, 7.0]+++def test_a_small_sweep_is_returned_whole() -> None:+ chunks = [_chunk("kb", "a", 1.0), _chunk("kb", "b", 2.0)]+ assert len(_balanced_slice(chunks, limit=24)) == 2diff --git a/tests/book/test_visual_block_prompts.py b/tests/book/test_visual_block_prompts.pynew file mode 100644index 000000000..44e586477--- /dev/null+++ b/tests/book/test_visual_block_prompts.py@@ -0,0 +1,63 @@+"""The visual blocks must take their brief from YAML, like every other block.++figure / interactive / animation used to build their prompt in Python with+English f-strings, so a Chinese book asked the shared visualize pipeline for a+figure in English — the one part of the book whose prompt ignored the book's+language. These check both that the prompts exist for every block/language pair+and that they interpolate without spacing artefacts in either direction.+"""++from __future__ import annotations++import pytest++from deeptutor.book.blocks._prompts import get_book_prompt, load_book_prompts++VISUAL_BLOCKS = ("figure", "interactive", "animation")+LANGUAGES = ("en", "zh")++# Every placeholder any of the three briefs might use.+FILLERS = {+ "chapter_title": "Matrix factorisation",+ "variant": "schematic",+ "interaction": "explorable",+}++[email protected]("block", VISUAL_BLOCKS)[email protected]("language", LANGUAGES)+def test_every_visual_block_has_a_brief_in_every_language(block: str, language: str) -> None:+ prompts = load_book_prompts(block, language)+ for key in ("brief", "focus_clause", "context_summary", "context_objectives"):+ assert get_book_prompt(prompts, key).strip(), f"{block}/{language} missing {key}"++[email protected]("block", VISUAL_BLOCKS)[email protected]("language", LANGUAGES)+def test_the_brief_renders_with_and_without_a_focus(block: str, language: str) -> None:+ prompts = load_book_prompts(block, language)+ brief = get_book_prompt(prompts, "brief").strip()++ focused = brief.format(+ **FILLERS,+ focus_clause=get_book_prompt(prompts, "focus_clause").rstrip().format(focus="SVD"),+ )+ assert "SVD" in focused+ assert "{" not in focused, "an unfilled placeholder survived"+ assert " " not in focused, "double space — the focus clause spacing is off"++ unfocused = brief.format(**FILLERS, focus_clause="")+ assert "{" not in unfocused+ assert " " not in unfocused, "empty focus clause left a dangling space"+++def test_the_english_focus_clause_keeps_its_leading_space() -> None:+ """A YAML block scalar would strip it; the file uses a quoted scalar."""+ clause = get_book_prompt(load_book_prompts("figure", "en"), "focus_clause")+ assert clause.startswith(" "), "English clause must separate itself from the title"+++def test_a_chinese_book_gets_a_chinese_brief() -> None:+ zh = get_book_prompt(load_book_prompts("figure", "zh"), "brief")+ assert any("一" <= ch <= "鿿" for ch in zh), "expected Chinese text"+ assert "figure for the chapter" not in zhdiff --git a/tests/book/test_worker_context.py b/tests/book/test_worker_context.pynew file mode 100644index 000000000..6b6126b5c--- /dev/null+++ b/tests/book/test_worker_context.py@@ -0,0 +1,64 @@+"""Background compilation must not inherit a request's scoped LLM config.++`asyncio.create_task` copies the context it is created in. The book worker is+created inside whichever request first enqueued a page, so a per-run model pick+made by that one request would otherwise pin every chapter the worker compiles+for the rest of its life — invisibly, since generated prose does not say which+model wrote it.+"""++from __future__ import annotations++import asyncio++import pytest++from deeptutor.services.llm.config import (+ _SCOPED_LLM_CONFIG,+ set_scoped_llm_config,+)+++async def test_a_task_inherits_its_creators_scope() -> None:+ """The hazard itself — asserted so the fix below has a stated premise."""++ async def observe() -> object:+ await asyncio.sleep(0)+ return _SCOPED_LLM_CONFIG.get()++ token = set_scoped_llm_config("request-scoped") # type: ignore[arg-type]+ task = asyncio.create_task(observe())+ _SCOPED_LLM_CONFIG.reset(token)++ assert _SCOPED_LLM_CONFIG.get() is None, "the request's scope has ended"+ assert await task == "request-scoped", (+ "a task created inside that request still sees it — this is why the "+ "worker clears the scope explicitly"+ )+++async def test_clearing_the_scope_inside_the_task_restores_the_default() -> None:+ """What `_worker_loop` does on entry."""++ async def worker_entry() -> object:+ set_scoped_llm_config(None)+ await asyncio.sleep(0)+ return _SCOPED_LLM_CONFIG.get()++ token = set_scoped_llm_config("request-scoped") # type: ignore[arg-type]+ task = asyncio.create_task(worker_entry())+ _SCOPED_LLM_CONFIG.reset(token)++ assert await task is None, "the worker must fall back to the user's config"+++def test_the_worker_actually_clears_it() -> None:+ """Guards the call site, not just the mechanism."""+ import inspect++ from deeptutor.book.engine import BookEngine++ source = inspect.getsource(BookEngine._worker_loop)+ assert "set_scoped_llm_config(None)" in sourcediff --git a/tests/capabilities/test_mastery_capability.py b/tests/capabilities/test_mastery_capability.pyindex 32ddfd2e7..baa4c62bd 100644--- a/tests/capabilities/test_mastery_capability.py+++ b/tests/capabilities/test_mastery_capability.py@@ -2,6 +2,7 @@from __future__ import annotations+import jsonfrom pathlib import Pathimport pytest@@ -161,6 +162,61 @@ async def test_pause_and_resume_hooks_persist_interaction_boundaries(tmp_path, massert answered.user_answer == "B"+async def test_hooks_bind_to_the_open_interaction_not_the_card_id(tmp_path, monkeypatch):+ """A same-round mastery_quiz + ask_user leaves the model's id on the card.++ Every tool call in a round has its arguments bound before any of them runs,+ so nothing is persisted yet when ask_user is bound and its question keeps+ whatever id the model invented. Committing against that id used to raise+ StaleInteractionError out of the hook and kill the turn.+ """+ _use_store_root(monkeypatch, tmp_path)+ LearningStore().save(_progress_with_objective())+ LearningService().register_question(+ "path-1",+ PendingQuestion(+ question_id="persisted-id",+ knowledge_point_id="kp-1",+ prompt="Which colour?",+ expected_answer="B",+ ),+ session_id="session-1",+ turn_id="turn-2",+ )+ model_authored_card = {"questions": [{"id": "routing_choice", "prompt": "Which colour?"}]}+ capability = MasteryLoopCapability()++ await capability.on_user_pause(_context(), model_authored_card)+ await capability.on_user_resume(+ _context(),+ model_authored_card,+ reply_text="B",+ answers=[{"questionId": "routing_choice", "text": "B"}],+ )++ interaction = LearningStore().get_interaction("path-1", "persisted-id")+ assert interaction is not None+ assert interaction.status == InteractionStatus.ANSWERED+ assert interaction.user_answer == "B"+++async def test_hooks_are_inert_when_no_question_is_open(tmp_path, monkeypatch):+ """A generic clarification card must not invent an interaction."""+ _use_store_root(monkeypatch, tmp_path)+ LearningStore().save(_progress_with_objective())+ clarification = {"questions": [{"id": "clarify", "prompt": "Which scope?"}]}+ capability = MasteryLoopCapability()++ await capability.on_user_pause(_context(), clarification)+ await capability.on_user_resume(+ _context(), clarification, reply_text="the second one", answers=None+ )++ assert LearningStore().get_active_interaction("path-1") is None++@pytest.mark.asyncioasync def test_direct_capability_call_holds_path_lease(tmp_path, monkeypatch):_use_store_root(monkeypatch, tmp_path)@@ -180,3 +236,77 @@ async def test_direct_capability_call_holds_path_lease(tmp_path, monkeypatch):assert lease.turn_id == "turn-2"assert LearningStore().get_path_lease("path-1") is Noneassert LearningStore().list_session_ids("path-1") == ["session-1"]+++def test_ask_user_card_never_marks_a_recommended_option(tmp_path, monkeypatch):+ """A quiz card must not point at its own answer.++ The generic ask_user contract tells the model to append "(Recommended)" to+ a suggested choice; on an assessment that marker is the answer key.+ """+ _use_store_root(monkeypatch, tmp_path)+ LearningStore().save(_progress_with_objective())+ authored = {+ "questions": [+ {+ "id": "q1",+ "prompt": "Which one holds?",+ "options": [+ {"label": "B(推荐)", "description": "the right one(推荐)"},+ {"label": "A (Recommended)", "description": "a distractor"},+ {"label": "C", "description": "another distractor"},+ ],+ }+ ]+ }++ bound = MasteryLoopCapability().augment_kwargs("ask_user", authored, _context())++ labels = [option["label"] for option in bound["questions"][0]["options"]]+ assert labels == ["B", "A", "C"]+ assert "推荐" not in json.dumps(bound, ensure_ascii=False)+ assert "Recommended" not in json.dumps(bound)+++def test_stripping_hints_leaves_ordinary_option_text_alone(tmp_path, monkeypatch):+ _use_store_root(monkeypatch, tmp_path)+ LearningStore().save(_progress_with_objective())+ authored = {+ "questions": [+ {+ "id": "q1",+ "prompt": "Which one?",+ "options": [+ # "推荐" mid-sentence is subject matter, not a marker.+ {"label": "推荐系统", "description": "Recommended reading is a use case"},+ ],+ }+ ]+ }++ bound = MasteryLoopCapability().augment_kwargs("ask_user", authored, _context())++ assert bound["questions"][0]["options"][0] == {+ "label": "推荐系统",+ "description": "Recommended reading is a use case",+ }+++def test_only_path_switching_tools_get_a_handle_on_the_live_binding(tmp_path, monkeypatch):+ """The binder is the one thing that can move a turn between paths."""+ _use_store_root(monkeypatch, tmp_path)+ LearningStore().save(_progress_with_objective())+ capability = MasteryLoopCapability()+ context = _context()++ status_kwargs = capability.augment_kwargs("mastery_status", {}, context)+ switch_kwargs = capability.augment_kwargs("mastery_switch", {"path_id": "other"}, context)++ assert "_bind_active_path" not in status_kwargs+ assert status_kwargs["_mastery_path_id"] == "path-1"+ assert callable(switch_kwargs["_bind_active_path"])++ switch_kwargs["_bind_active_path"]("other")+ assert context.metadata["mastery_path_id"] == "other"+ # And the next tool call on this turn follows the new binding.+ assert capability.augment_kwargs("mastery_status", {}, context)["_mastery_path_id"] == "other"diff --git a/tests/core/agentic/test_tool_dispatch_pause_ordering.py b/tests/core/agentic/test_tool_dispatch_pause_ordering.pynew file mode 100644index 000000000..62ca10117--- /dev/null+++ b/tests/core/agentic/test_tool_dispatch_pause_ordering.py@@ -0,0 +1,119 @@+"""A pausing tool binds its arguments after its round-mates have run.++Every tool call in a round used to have its arguments bound up front and then+run concurrently. That is wrong for a tool whose job is to *show the user what+the round produced*: a mastery tutor that poses a question (``mastery_quiz``)+and presents it (``ask_user``) in one round had the card bound before the+question was persisted, so the card could only carry the model's own draft of+it — and grading then had to guess how the shown options mapped onto the stored+ones.+"""++from __future__ import annotations++from typing import Any++import pytest++from deeptutor.core.agentic.tool_dispatch import dispatch_tool_calls+from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream_bus import StreamBus+from deeptutor.core.tool_protocol import ToolResult+++class _RecordingRegistry:+ """Stands in for the persisted question: the quiz commits, ask_user reads."""++ def __init__(self) -> None:+ self.order: list[str] = []+ self.committed: str | None = None+ self.seen_by_ask_user: str | None = None++ async def execute(self, name: str, **kwargs: Any) -> ToolResult:+ self.order.append(name)+ if name == "mastery_quiz":+ self.committed = "persisted question"+ if name == "ask_user":+ self.seen_by_ask_user = kwargs.get("prompt")+ return ToolResult(content="ok", success=True)+++async def _dispatch(registry: _RecordingRegistry, tool_calls: list[dict[str, Any]]) -> None:+ def augment(tool_name: str, tool_args: dict[str, Any], _ctx: UnifiedContext) -> dict[str, Any]:+ # Mirrors the mastery binder: an ask_user card is rebound onto whatever+ # question is committed at bind time, and left alone when none is.+ if tool_name == "ask_user" and registry.committed:+ return {**tool_args, "prompt": registry.committed}+ return dict(tool_args)++ await dispatch_tool_calls(+ tool_calls=tool_calls,+ context=UnifiedContext(session_id="s1", user_message="hi"),+ stream=StreamBus(),+ source="chat",+ stage="responding",+ iteration_index=0,+ registry=registry,+ kwarg_augmenter=augment,+ )+++async def test_ask_user_runs_last_and_rebinds_against_the_round() -> None:+ registry = _RecordingRegistry()++ await _dispatch(+ registry,+ [+ {"id": "c1", "name": "ask_user", "arguments": '{"prompt": "model draft"}'},+ {"id": "c2", "name": "mastery_quiz", "arguments": "{}"},+ ],+ )++ # Declared first by the model, still run last.+ assert registry.order == ["mastery_quiz", "ask_user"]+ assert registry.seen_by_ask_user == "persisted question"+++async def test_a_round_without_a_pausing_tool_is_unchanged() -> None:+ registry = _RecordingRegistry()++ await _dispatch(+ registry,+ [+ {"id": "c1", "name": "rag", "arguments": "{}"},+ {"id": "c2", "name": "web_search", "arguments": "{}"},+ ],+ )++ assert sorted(registry.order) == ["rag", "web_search"]+++async def test_results_stay_paired_with_their_tool_calls() -> None:+ """Reordering execution must not reorder the role=tool messages."""++ class _EchoRegistry:+ async def execute(self, name: str, **kwargs: Any) -> ToolResult:+ return ToolResult(content=f"{name}-done", success=True)++ outcome = await dispatch_tool_calls(+ tool_calls=[+ {"id": "c1", "name": "ask_user", "arguments": "{}"},+ {"id": "c2", "name": "rag", "arguments": "{}"},+ {"id": "c3", "name": "web_search", "arguments": "{}"},+ ],+ context=UnifiedContext(session_id="s1", user_message="hi"),+ stream=StreamBus(),+ source="chat",+ stage="responding",+ iteration_index=0,+ registry=_EchoRegistry(),+ )++ assert [(m["tool_call_id"], m["content"]) for m in outcome.tool_messages] == [+ ("c1", "ask_user-done"),+ ("c2", "rag-done"),+ ("c3", "web_search-done"),+ ]diff --git a/tests/knowledge/test_ima_kb.py b/tests/knowledge/test_ima_kb.pyindex 638733752..8d81f2fb7 100644--- a/tests/knowledge/test_ima_kb.py+++ b/tests/knowledge/test_ima_kb.py@@ -46,10 +46,23 @@ def test_register_keeps_the_probed_description(tmp_path) -> None:assert entry["description"] == "My notes"+def test_register_without_credentials_defers_to_the_account_pair(tmp_path) -> None:+ # Omitting both halves means "use the engine's account credentials"; storing+ # a copy would pin the KB to today's key and break the next rotation.+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))++ entry = manager.register_ima_kb("IMA", "", "", "kb-1")++ assert entry["knowledge_base_id"] == "kb-1"+ assert "client_id" not in entry+ assert "api_key" not in entry++@pytest.mark.parametrize("args",[("", "cid", "secret", "kb-1"),+ # Half a credential pair is a mistake, not an account-level fallback.("IMA", "", "secret", "kb-1"),("IMA", "cid", "", "kb-1"),("IMA", "cid", "secret", ""),diff --git a/tests/services/config/test_ima_settings.py b/tests/services/config/test_ima_settings.pynew file mode 100644index 000000000..cc155aac3--- /dev/null+++ b/tests/services/config/test_ima_settings.py@@ -0,0 +1,38 @@+"""Account-level Tencent IMA credential storage in RuntimeSettingsService."""++from __future__ import annotations++from pathlib import Path++from deeptutor.services.config.runtime_settings import RuntimeSettingsService+++def test_ima_settings_roundtrip(tmp_path: Path) -> None:+ svc = RuntimeSettingsService(tmp_path, process_env={})+ svc.save_ima({"client_id": " cid-1 ", "api_key": " secret "})++ loaded = svc.load_ima(include_process_overrides=False)+ assert loaded["client_id"] == "cid-1"+ assert loaded["api_key"] == "secret"++ # Persisted to its own file beside other per-feature settings.+ assert (tmp_path / "ima.json").exists()+++def test_ima_defaults_when_absent(tmp_path: Path) -> None:+ svc = RuntimeSettingsService(tmp_path, process_env={})+ loaded = svc.load_ima(include_process_overrides=False)+ assert loaded == {"version": 1, "client_id": "", "api_key": ""}+++def test_ima_env_override(tmp_path: Path) -> None:+ svc = RuntimeSettingsService(+ tmp_path,+ process_env={"IMA_CLIENT_ID": "from-env", "IMA_API_KEY": "env-key"},+ )+ loaded = svc.load_ima(include_process_overrides=True)+ assert loaded["client_id"] == "from-env"+ assert loaded["api_key"] == "env-key"++ # The override is a deployment knob, not something the UI can overwrite.+ assert svc.load_ima(include_process_overrides=False)["client_id"] == ""diff --git a/tests/services/rag/test_graphrag_completion_adapter.py b/tests/services/rag/test_graphrag_completion_adapter.pyindex 4ecfc6729..eaa721582 100644--- a/tests/services/rag/test_graphrag_completion_adapter.py+++ b/tests/services/rag/test_graphrag_completion_adapter.py@@ -292,6 +292,7 @@ def test_sync_completion_caches_explicit_json_object_fallback(tmp_path: Path,) -> None:litellm = pytest.importorskip("litellm")+ pytest.importorskip("graphrag")from graphrag.index.operations.summarize_communities.community_reports_extractor import (CommunityReportResponse,)@@ -333,6 +334,7 @@ def test_authentication_failure_is_not_retried(tmp_path: Path,) -> None:litellm = pytest.importorskip("litellm")+ pytest.importorskip("graphrag")from graphrag.index.operations.summarize_communities.community_reports_extractor import (CommunityReportResponse,)@@ -367,6 +369,7 @@ def test_invalid_fallback_json_fails_strict_validation(tmp_path: Path,) -> None:litellm = pytest.importorskip("litellm")+ pytest.importorskip("graphrag")from graphrag.index.operations.summarize_communities.community_reports_extractor import (CommunityReportResponse,)@@ -404,6 +407,7 @@ def test_truncated_fallback_is_unverifiable_instead_of_incompatible(tmp_path: Path,) -> None:litellm = pytest.importorskip("litellm")+ pytest.importorskip("graphrag")from graphrag.index.operations.summarize_communities.community_reports_extractor import (CommunityReportResponse,)@@ -448,6 +452,7 @@ def test_native_validation_failure_retries_once_without_caching(tmp_path: Path,) -> None:litellm = pytest.importorskip("litellm")+ pytest.importorskip("graphrag")from graphrag.index.operations.summarize_communities.community_reports_extractor import (CommunityReportResponse,)@@ -532,6 +537,7 @@ def test_cached_fallback_is_safe_under_concurrent_sync_calls(tmp_path: Path,) -> None:litellm = pytest.importorskip("litellm")+ pytest.importorskip("graphrag")from graphrag.index.operations.summarize_communities.community_reports_extractor import (CommunityReportResponse,)diff --git a/tests/services/rag/test_ima_pipeline.py b/tests/services/rag/test_ima_pipeline.pyindex 3c0b7888f..d1d6bd679 100644--- a/tests/services/rag/test_ima_pipeline.py+++ b/tests/services/rag/test_ima_pipeline.py@@ -32,6 +32,7 @@ from deeptutor.services.rag.pipelines.ima.client import ()from deeptutor.services.rag.pipelines.ima.config import (ImaConfig,+ ImaCredentials,ImaNotConfiguredError,config_from_entry,)@@ -81,6 +82,26 @@ class TestConfigFromEntry:message = str(exc.value)assert "API key" in message and "knowledge base ID" in message+ def test_account_credentials_fill_in_what_the_entry_omits(self) -> None:+ config = config_from_entry(+ {"knowledge_base_id": "kb-1"},+ fallback=ImaCredentials(client_id="cid", api_key="key"),+ )+ assert config == CONFIG++ def test_entry_credentials_win_over_the_account_pair(self) -> None:+ # A KB pinned to a second IMA account must not silently retrieve+ # through the account-level credentials.+ config = config_from_entry(+ {"client_id": "other", "api_key": "other-key", "knowledge_base_id": "kb-1"},+ fallback=ImaCredentials(client_id="cid", api_key="key"),+ )+ assert config == ImaConfig(client_id="other", api_key="other-key", knowledge_base_id="kb-1")++ def test_knowledge_base_id_is_never_inherited(self) -> None:+ with pytest.raises(ImaNotConfiguredError, match="knowledge base ID"):+ config_from_entry({}, fallback=ImaCredentials(client_id="cid", api_key="key"))+# ---------------------------------------------------------------------------# client@@ -713,6 +734,28 @@ class TestPipelineSearch:assert stub.limit == 50+ def test_kb_without_credentials_uses_the_account_pair(self, tmp_path, monkeypatch) -> None:+ import deeptutor.services.config as config_module+ from deeptutor.services.config.runtime_settings import RuntimeSettingsService++ service = RuntimeSettingsService(tmp_path / "settings", process_env={})+ service.save_ima({"client_id": "cid", "api_key": "key"})+ monkeypatch.setattr(config_module, "get_runtime_settings_service", lambda: service)++ base = _kb_config(tmp_path, {"type": "ima", "knowledge_base_id": "kb-1"})+ seen: list[ImaConfig] = []++ def factory(config: ImaConfig):+ seen.append(config)+ return _SearchStub([{"media_id": "m1", "title": "Alpha", "highlight_content": "a"}])++ pipeline = ImaPipeline(kb_base_dir=base, client_factory=factory)++ result = asyncio.run(pipeline.search("q", "IMA"))++ assert seen == [CONFIG]+ assert [source["title"] for source in result["sources"]] == ["Alpha"]+def test_unconfigured_kb_reports_not_configured(self, tmp_path) -> None:base = _kb_config(tmp_path, {"type": "ima", "rag_provider": "ima"})pipeline = ImaPipeline(kb_base_dir=base)diff --git a/tests/services/rag/test_preflight.py b/tests/services/rag/test_preflight.pyindex d5ec8e80c..adcaf0fa6 100644--- a/tests/services/rag/test_preflight.py+++ b/tests/services/rag/test_preflight.py@@ -1,16 +1,55 @@+from pathlib import Path++import pytest++import deeptutor.services.config as config_module+from deeptutor.services.config.runtime_settings import RuntimeSettingsServicefrom deeptutor.services.rag.preflight import engine_preflight-def test_ima_preflight_explains_per_kb_credentials_without_network() -> None:+def ima_settings(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> RuntimeSettingsService:+ """Point the account-level IMA credentials at a throwaway settings dir."""+ service = RuntimeSettingsService(tmp_path, process_env={})+ monkeypatch.setattr(config_module, "get_runtime_settings_service", lambda: service)+ return service+++def test_ima_preflight_is_not_ready_without_credentials(+ ima_settings: RuntimeSettingsService,+) -> None:report = engine_preflight("ima")- assert report["ok"] is True+ assert report["ok"] is Falseassert report["checks"] == [{- "key": "per_kb_credentials",- "label": "Credentials supplied when connecting a knowledge base",- "ok": True,- "detail": "Enter the IMA Client ID and API key in the link-existing flow.",+ "key": "credentials",+ "label": "IMA Client ID and API key configured",+ "ok": False,+ "detail": (+ "Add them under Credentials, or supply a pair per knowledge base "+ "when connecting one."+ ),"optional": False,}]+++def test_ima_preflight_reports_the_configured_client_id(+ ima_settings: RuntimeSettingsService,+) -> None:+ ima_settings.save_ima({"client_id": "cid-1", "api_key": "secret"})++ report = engine_preflight("ima")++ assert report["ok"] is True+ assert report["checks"][0]["ok"] is True+ # The Client ID is not a secret and identifies which account is wired up;+ # the API key must never reach the report.+ assert report["checks"][0]["detail"] == "cid-1"+++def test_ima_preflight_needs_both_halves(ima_settings: RuntimeSettingsService) -> None:+ ima_settings.save_ima({"client_id": "cid-1", "api_key": ""})++ assert engine_preflight("ima")["ok"] is Falsediff --git a/tests/services/session/test_turn_runtime_subscribe.py b/tests/services/session/test_turn_runtime_subscribe.pyindex c5c656173..1cc6ce73d 100644--- a/tests/services/session/test_turn_runtime_subscribe.py+++ b/tests/services/session/test_turn_runtime_subscribe.py@@ -291,6 +291,50 @@ async def test_mastery_path_allows_only_one_live_turn_across_sessions(LearningStore().release_path_lease("shared", turn_id=first_turn["id"])+async def test_mastery_turn_takes_over_a_path_parked_on_ask_user(+ monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ """A turn waiting on the learner must not lock the path forever."""+ _isolate_learning_store(monkeypatch, tmp_path)+ store = SQLiteSessionStore(tmp_path / "chat_history.db")+ runtime = TurnRuntimeManager(store)+ first_session = await store.ensure_session("session-1")+ second_session = await store.ensure_session("session-2")+ parked = asyncio.Event()++ async def _park_turn(execution) -> None:+ # Mirrors the real turn: flag the ask_user pause, then wait for a+ # reply that never comes, then finalize like ``_run_turn`` does.+ execution.awaiting_user_reply = True+ try:+ await parked.wait()+ finally:+ execution.awaiting_user_reply = False+ await store.update_turn_status(execution.turn_id, "cancelled", "Turn cancelled")+ async with runtime._lock:+ runtime._executions.pop(execution.turn_id, None)++ monkeypatch.setattr(runtime, "_run_turn", _park_turn)+ _, parked_turn = await runtime.start_turn(_mastery_payload(first_session["id"], "shared"))+ while not runtime._executions[parked_turn["id"]].awaiting_user_reply:+ await asyncio.sleep(0)++ _, resuming_turn = await runtime.start_turn(_mastery_payload(second_session["id"], "shared"))++ superseded = await store.get_turn(parked_turn["id"])+ assert superseded is not None+ assert superseded["status"] == "cancelled"+ lease = LearningStore().get_path_lease("shared")+ assert lease is not None+ assert lease.turn_id == resuming_turn["id"]+ assert lease.session_id == second_session["id"]++ parked.set()+ await runtime.cancel_turn(resuming_turn["id"])+ LearningStore().release_path_lease("shared", turn_id=resuming_turn["id"])++@pytest.mark.asyncioasync def test_racing_mastery_start_does_not_steal_pre_task_lease(monkeypatch: pytest.MonkeyPatch, tmp_path@@ -405,3 +449,45 @@ async def test_mastery_turn_cannot_steal_administrative_path_lease(assert lease.turn_id == "api-operation"finally:learning_store.release_path_lease("shared", turn_id="api-operation")+++async def test_a_mid_turn_path_switch_is_pushed_to_the_client(tmp_path) -> None:+ """Otherwise the composer keeps naming the path the turn started on."""+ store = SQLiteSessionStore(tmp_path / "chat_history.db")+ runtime = TurnRuntimeManager(store)+ execution = _TurnExecution(+ turn_id="turn-1",+ session_id="session-1",+ capability="mastery_path",+ payload={},+ )++ await runtime._publish_mastery_path_change(+ execution,+ capability_name="mastery_path",+ started_on="calculus",+ ended_on="algebra",+ )++ pushed = [event for event in execution.events if event["type"] == "session_meta"]+ assert len(pushed) == 1+ assert pushed[0]["metadata"]["mastery_path_id"] == "algebra"+++async def test_no_path_push_when_the_turn_never_moved(tmp_path) -> None:+ store = SQLiteSessionStore(tmp_path / "chat_history.db")+ runtime = TurnRuntimeManager(store)+ execution = _TurnExecution(+ turn_id="turn-1", session_id="session-1", capability="mastery_path", payload={}+ )++ await runtime._publish_mastery_path_change(+ execution, capability_name="mastery_path", started_on="calculus", ended_on="calculus"+ )+ await runtime._publish_mastery_path_change(+ execution, capability_name="chat", started_on="", ended_on="algebra"+ )++ assert [event for event in execution.events if event["type"] == "session_meta"] == []diff --git a/web/app/(utility)/settings/document-parsing/page.tsx b/web/app/(utility)/settings/document-parsing/page.tsxindex f1c8e83e6..720e8a867 100644--- a/web/app/(utility)/settings/document-parsing/page.tsx+++ b/web/app/(utility)/settings/document-parsing/page.tsx@@ -57,7 +57,8 @@ export default function DocumentParsingSettingsPage() {apiUrl("/api/v1/settings/document-parsing"),);const payload = (await response.json().catch(() => ({}))) as- DocumentParsingPayload | { detail?: string };+ | DocumentParsingPayload+ | { detail?: string };if (!response.ok) {throw new Error("detail" in payload && payload.detail@@ -91,7 +92,8 @@ export default function DocumentParsingSettingsPage() {},);const payload = (await response.json().catch(() => ({}))) as- DocumentParsingPayload | { detail?: string };+ | DocumentParsingPayload+ | { detail?: string };if (!response.ok) {throw new Error("detail" in payload && payload.detaildiff --git a/web/app/(utility)/settings/starters/page.tsx b/web/app/(utility)/settings/starters/page.tsxindex 82ca51476..046d55fb9 100644--- a/web/app/(utility)/settings/starters/page.tsx+++ b/web/app/(utility)/settings/starters/page.tsx@@ -52,7 +52,8 @@ export default function StarterSettingsPage() {setPayload(next);setDraft({ ...next.settings });} catch (err) {- if (!cancelled) setError(err instanceof Error ? err.message : String(err));+ if (!cancelled)+ setError(err instanceof Error ? err.message : String(err));} finally {if (!cancelled) setLoading(false);}@@ -64,7 +65,10 @@ export default function StarterSettingsPage() {}, [t]);const dirty = useMemo(- () => Boolean(payload && draft && payload.settings.trace_count !== draft.trace_count),+ () =>+ Boolean(+ payload && draft && payload.settings.trace_count !== draft.trace_count,+ ),[draft, payload],);@@ -76,11 +80,14 @@ export default function StarterSettingsPage() {if (!current) return;setError(null);try {- const response = await apiFetch(apiUrl("/api/v1/settings/chat-starters"), {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(current),- });+ const response = await apiFetch(+ apiUrl("/api/v1/settings/chat-starters"),+ {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(current),+ },+ );const data = (await response.json().catch(() => ({}))) as| StarterSettingsPayload| { detail?: string };diff --git a/web/app/(utility)/space/learning/page.tsx b/web/app/(utility)/space/learning/page.tsxindex 543f2f6f2..689283b79 100644--- a/web/app/(utility)/space/learning/page.tsx+++ b/web/app/(utility)/space/learning/page.tsx@@ -1,6 +1,6 @@"use client";-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useMemo, useState } from "react";import { useRouter } from "next/navigation";import { useTranslation } from "react-i18next";import {@@ -8,9 +8,6 @@ import {Loader2,RotateCcw,Trash2,- CircleCheck,- CircleDot,- Circle,MessageSquare,} from "lucide-react";@@ -19,25 +16,29 @@ import {fetchMasteryMap,deleteProgress,redoProgress,+ skipPendingQuestion,type ProgressSummary,type MasteryMapResult,- type ObjectiveStatus,} from "@/lib/learning-api";-import { newMasteryPathChatUrl } from "@/lib/mastery-path-navigation";+import { newMasteryPathChatUrl } from "@/lib/chat-launch-intent";+import { useMasteryPathActivity } from "@/hooks/useMasteryPathActivity";+import { ActivityTimeline } from "@/components/space/learning/ActivityTimeline";+import { PathMap } from "@/components/space/learning/PathMap";+import { formatRelative } from "@/components/space/learning/format";/*** Mastery Path dashboard — the persistent "screen" of the mastery experience.** The tutoring itself runs on the chat agent loop (pick "Mastery Path" mode in- * Chat); this page is the map of where the learner stands. It reads the- * gate-accurate snapshot from ``/progress/{id}/map`` (per-type status computed- * by ``deeptutor.learning.policy``) so the colours here agree with the gate the- * tutor enforces. A path and a conversation have independent identities, so- * "Continue" starts a focused chat while retaining the selected path state.+ * Chat); this page is the map of where the learner stands, and it follows+ * along live: the engine's event feed is polled for anything past the revision+ * already on screen, and every read here re-runs when the path moves. So a+ * learner can keep this open beside a tutoring conversation and watch the gate+ * clear. "Continue" starts a focused chat while retaining the selected path.*/export default function MasteryPathPage() {const { i18n } = useTranslation();- const zh = i18n.language?.toLowerCase().startsWith("zh");+ const zh = !!i18n.language?.toLowerCase().startsWith("zh");const tr = useCallback((cn: string, en: string) => (zh ? cn : en), [zh]);const router = useRouter();@@ -46,9 +47,11 @@ export default function MasteryPathPage() {const [detail, setDetail] = useState<MasteryMapResult | null>(null);const [loadingList, setLoadingList] = useState(true);const [loadingDetail, setLoadingDetail] = useState(false);+ const [tab, setTab] = useState<"map" | "activity">("map");++ const { events, revision, refresh } = useMasteryPathActivity(selected);const loadList = useCallback(async () => {- setLoadingList(true);try {const result = await fetchAllProgress();const withContent = result.summaries@@ -63,31 +66,46 @@ export default function MasteryPathPage() {}}, []);+ /* The list carries per-path mastery, so it is as live as the map. */useEffect(() => {- loadList();- }, [loadList]);+ void loadList();+ }, [loadList, revision]);+ /* Re-read the map whenever the path advances — `revision` is that signal. */useEffect(() => {if (!selected) {setDetail(null);return;}- let cancelled = false;- setLoadingDetail(true);- fetchMasteryMap(selected)- .then((result) => {- if (!cancelled) setDetail(result);- })+ const controller = new AbortController();+ setLoadingDetail(+ (wasLoading) => wasLoading || detail?.book_id !== selected,+ );+ fetchMasteryMap(selected, { signal: controller.signal })+ .then(setDetail).catch(() => {- if (!cancelled) setDetail(null);+ if (!controller.signal.aborted) setDetail(null);})- .finally(() => {- if (!cancelled) setLoadingDetail(false);- });- return () => {- cancelled = true;- };- }, [selected]);+ .finally(() => setLoadingDetail(false));+ return () => controller.abort();+ // `detail` is read only to decide whether to show a spinner; depending on+ // it would refetch the map every time the map arrives.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [selected, revision]);++ /* Objective id → name, so the activity feed reads in the learner's terms. */+ const objectiveNames = useMemo(() => {+ const names: Record<string, string> = {};+ for (const group of detail?.map.modules ?? [])+ for (const kp of group.knowledge_points) names[kp.id] = kp.name;+ return names;+ }, [detail]);++ /* Mutations refresh through the same path as the tutor's own changes. */+ const afterMutation = useCallback(async () => {+ await loadList();+ refresh();+ }, [loadList, refresh]);const handleDelete = useCallback(async (pathId: string) => {@@ -98,10 +116,10 @@ export default function MasteryPathPage() {)return;await deleteProgress(pathId);- if (selected === pathId) setSelected(null);- await loadList();+ setSelected(null);+ await afterMutation();},- [selected, loadList, tr],+ [afterMutation, tr],);const handleRedo = useCallback(@@ -116,19 +134,35 @@ export default function MasteryPathPage() {)return;await redoProgress(pathId);- const result = await fetchMasteryMap(pathId);- setDetail(result);+ await afterMutation();},- [tr],+ [afterMutation, tr],+ );++ const handleSkipQuestion = useCallback(+ async (pathId: string) => {+ if (+ !window.confirm(+ tr(+ "跳过这道待回答的题目?已掌握的进度都会保留。",+ "Skip the question awaiting an answer? Mastery already earned is kept.",+ ),+ )+ )+ return;+ await skipPendingQuestion(pathId);+ await afterMutation();+ },+ [afterMutation, tr],);return (<div className="flex h-full">{/* Path list */}- <aside className="w-64 shrink-0 border-r border-[var(--border)] flex flex-col">- <header className="px-4 py-3 border-b border-[var(--border)]">+ <aside className="flex w-64 shrink-0 flex-col border-r border-[var(--border)]">+ <header className="border-b border-[var(--border)] px-4 py-3"><div className="flex items-center gap-2 text-[var(--foreground)]">- <GraduationCap className="w-4 h-4" />+ <GraduationCap className="h-4 w-4" /><h1 className="text-sm font-semibold">{tr("精通之路", "Mastery Path")}</h1>@@ -140,13 +174,13 @@ export default function MasteryPathPage() {)}</p></header>- <div className="flex-1 overflow-y-auto p-2 space-y-1">+ <div className="flex-1 space-y-1 overflow-y-auto p-2">{loadingList ? (<div className="flex items-center justify-center py-8 text-[var(--muted-foreground)]">- <Loader2 className="w-4 h-4 animate-spin" />+ <Loader2 className="h-4 w-4 animate-spin" /></div>) : paths.length === 0 ? (- <p className="px-2 py-3 text-xs text-[var(--muted-foreground)] leading-relaxed">+ <p className="px-2 py-3 text-xs leading-relaxed text-[var(--muted-foreground)]">{tr("还没有精通之路。去「对话」选择 Mastery Path 模式,让导师根据你的材料建一条。","No paths yet. Open Chat, pick Mastery Path mode, and ask the tutor to build one from your materials.",@@ -157,7 +191,7 @@ export default function MasteryPathPage() {<buttonkey={path.book_id}onClick={() => setSelected(path.book_id)}- className={`w-full text-left px-3 py-2 rounded-md transition-colors cursor-pointer ${+ className={`w-full cursor-pointer rounded-md px-3 py-2 text-left transition-colors ${selected === path.book_id? "bg-[var(--primary)]/10 ring-1 ring-[var(--primary)]/30": "hover:bg-[var(--accent)]"@@ -174,27 +208,27 @@ export default function MasteryPathPage() {)))}</div>- <footer className="p-2 border-t border-[var(--border)]">+ <footer className="border-t border-[var(--border)] p-2"><buttononClick={() => router.push("/home")}- className="w-full flex items-center justify-center gap-1.5 px-3 py-2 text-sm rounded-md bg-[var(--primary)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity cursor-pointer"+ className="flex w-full cursor-pointer items-center justify-center gap-1.5 rounded-md bg-[var(--primary)] px-3 py-2 text-sm text-[var(--primary-foreground)] transition-opacity hover:opacity-90">- <MessageSquare className="w-3.5 h-3.5" />+ <MessageSquare className="h-3.5 w-3.5" />{tr("新建(在对话中)", "New (in Chat)")}</button></footer></aside>- {/* Selected path map */}+ {/* Selected path */}<section className="flex-1 overflow-y-auto">- {loadingDetail ? (- <div className="flex items-center justify-center h-full text-[var(--muted-foreground)]">- <Loader2 className="w-5 h-5 animate-spin" />+ {loadingDetail && !detail ? (+ <div className="flex h-full items-center justify-center text-[var(--muted-foreground)]">+ <Loader2 className="h-5 w-5 animate-spin" /></div>- ) : !detail ? (- <div className="flex flex-col items-center justify-center h-full text-center px-6 text-[var(--muted-foreground)]">- <GraduationCap className="w-10 h-10 mb-3 opacity-40" />- <p className="text-sm max-w-sm leading-relaxed">+ ) : !detail || !selected ? (+ <div className="flex h-full flex-col items-center justify-center px-6 text-center text-[var(--muted-foreground)]">+ <GraduationCap className="mb-3 h-10 w-10 opacity-40" />+ <p className="max-w-sm text-sm leading-relaxed">{tr("选择一条精通之路查看进度地图,或在「对话」里用 Mastery Path 模式开始。","Select a path to see its progress map, or start one in Chat with Mastery Path mode.",@@ -202,15 +236,20 @@ export default function MasteryPathPage() {</p></div>) : (- <MapView+ <PathView+ pathId={selected}result={detail}- zh={!!zh}+ revision={revision}+ events={events}+ objectiveNames={objectiveNames}+ tab={tab}+ onTabChange={setTab}+ zh={zh}tr={tr}- onContinue={() =>- selected && router.push(newMasteryPathChatUrl(selected))- }- onRedo={() => selected && handleRedo(selected)}- onDelete={() => selected && handleDelete(selected)}+ onContinue={() => router.push(newMasteryPathChatUrl(selected))}+ onSkipQuestion={() => handleSkipQuestion(selected)}+ onRedo={() => handleRedo(selected)}+ onDelete={() => handleDelete(selected)}/>)}</section>@@ -218,19 +257,6 @@ export default function MasteryPathPage() {);}-const STATUS_META: Record<- ObjectiveStatus,- { cn: string; en: string; className: string }-> = {- mastered: { cn: "已掌握", en: "Mastered", className: "text-green-500" },- learning: { cn: "学习中", en: "Learning", className: "text-yellow-500" },- new: {- cn: "未开始",- en: "Not started",- className: "text-[var(--muted-foreground)]",- },-};-const ACTION_LABEL: Record<string, { cn: string; en: string }> = {probe: { cn: "先探查是否已掌握", en: "Probe — test out first" },practice: { cn: "练习直到达标", en: "Practice until the gate clears" },@@ -243,25 +269,32 @@ const ACTION_LABEL: Record<string, { cn: string; en: string }> = {complete: { cn: "已全部掌握 🎉", en: "All mastered 🎉" },};-function StatusIcon({ status }: { status: ObjectiveStatus }) {- const cls = `w-3 h-3 shrink-0 ${STATUS_META[status].className}`;- if (status === "mastered") return <CircleCheck className={cls} />;- if (status === "learning") return <CircleDot className={cls} />;- return <Circle className={cls} />;-}--function MapView({+function PathView({+ pathId,result,+ revision,+ events,+ objectiveNames,+ tab,+ onTabChange,zh,tr,onContinue,+ onSkipQuestion,onRedo,onDelete,}: {+ pathId: string;result: MasteryMapResult;+ revision: number;+ events: React.ComponentProps<typeof ActivityTimeline>["events"];+ objectiveNames: Record<string, string>;+ tab: "map" | "activity";+ onTabChange: (tab: "map" | "activity") => void;zh: boolean;tr: (cn: string, en: string) => string;onContinue: () => void;+ onSkipQuestion: () => void;onRedo: () => void;onDelete: () => void;}) {@@ -273,12 +306,13 @@ function MapView({cn: next.reason,en: next.reason,};+ const lastEvent = events.length ? events[events.length - 1] : null;return (- <div className="max-w-2xl mx-auto px-6 py-5">- {/* Header: progress + next + actions */}+ <div className="mx-auto max-w-2xl px-6 py-5">+ {/* Header: progress + actions */}<div className="flex items-start justify-between gap-4">- <div className="flex-1 min-w-0">+ <div className="min-w-0 flex-1"><div className="flex items-center gap-2 text-sm text-[var(--muted-foreground)]"><span>{map.counts.mastered}/{map.counts.total}{" "}@@ -289,37 +323,40 @@ function MapView({· {map.due_reviews} {tr("项待复习", "due for review")}</span>)}+ {lastEvent && (+ <span>+ · {tr("最近更新 ", "updated ")}+ {formatRelative(lastEvent.created_at, zh)}+ </span>+ )}</div>- <div className="mt-1.5 h-1.5 w-full rounded-full bg-[var(--accent)] overflow-hidden">+ <div className="mt-1.5 h-1.5 w-full overflow-hidden rounded-full bg-[var(--accent)]"><divclassName="h-full bg-green-500 transition-all"style={{ width: `${pct}%` }}/></div></div>- <div className="flex items-center gap-1.5 shrink-0">+ <div className="flex shrink-0 items-center gap-1.5"><buttononClick={onRedo}title={tr("重置进度", "Reset progress")}- className="p-1.5 rounded-md text-[var(--muted-foreground)] hover:bg-[var(--accent)] cursor-pointer"+ className="cursor-pointer rounded-md p-1.5 text-[var(--muted-foreground)] hover:bg-[var(--accent)]">- <RotateCcw className="w-4 h-4" />+ <RotateCcw className="h-4 w-4" /></button><buttononClick={onDelete}title={tr("删除", "Delete")}- className="p-1.5 rounded-md text-[var(--muted-foreground)] hover:bg-red-500/10 hover:text-red-500 cursor-pointer"+ className="cursor-pointer rounded-md p-1.5 text-[var(--muted-foreground)] hover:bg-red-500/10 hover:text-red-500">- <Trash2 className="w-4 h-4" />+ <Trash2 className="h-4 w-4" /></button></div></div>{/* Next step */}- <button- onClick={onContinue}- className="mt-4 w-full text-left rounded-lg border border-[var(--border)] hover:border-[var(--primary)]/40 hover:bg-[var(--accent)] p-3 transition-colors cursor-pointer"- >+ <div className="mt-4 rounded-lg border border-[var(--border)] p-3"><div className="text-xs text-[var(--muted-foreground)]">{tr("接下来", "Next")}</div>@@ -328,47 +365,79 @@ function MapView({? tr(action.cn, action.en): `${next.knowledge_point_name} — ${tr(action.cn, action.en)}`}</div>- <div className="mt-1 text-xs text-[var(--primary)]">- {tr("在对话中继续辅导 →", "Continue tutoring in Chat →")}+ {next.pending_prompt && (+ <p className="mt-1 text-xs text-[var(--muted-foreground)]">+ {next.pending_prompt}+ </p>+ )}+ <div className="mt-1.5 flex items-center gap-3">+ <button+ onClick={onContinue}+ className="cursor-pointer text-xs text-[var(--primary)] hover:underline"+ >+ {tr("在对话中继续辅导 →", "Continue tutoring in Chat →")}+ </button>+ {/* Only reachable escape from a question whose conversation is gone;+ unlike Reset it keeps every mastery level already earned. */}+ {next.action === "answer_pending" && (+ <button+ onClick={onSkipQuestion}+ className="cursor-pointer text-xs text-[var(--muted-foreground)] hover:text-[var(--foreground)] hover:underline"+ >+ {tr("跳过这道题", "Skip this question")}+ </button>+ )}</div>- </button>+ </div>- {/* Module / objective map */}- <div className="mt-5 space-y-4">- {map.modules.map((module) => (- <div key={module.id}>- <div className="flex items-center justify-between">- <h3 className="text-sm font-medium text-[var(--foreground)]">- {module.name}- </h3>- <span className="text-xs text-[var(--muted-foreground)]">- {module.mastered}/{module.total}+ {/* Map / activity */}+ <div className="mt-5 flex items-center gap-4 border-b border-[var(--border)]">+ {(+ [+ ["map", tr("地图", "Map")],+ ["activity", tr("活动", "Activity")],+ ] as const+ ).map(([value, label]) => (+ <button+ key={value}+ onClick={() => onTabChange(value)}+ className={`-mb-px cursor-pointer border-b-2 pb-1.5 text-xs transition-colors ${+ tab === value+ ? "border-[var(--primary)] text-[var(--foreground)]"+ : "border-transparent text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ }`}+ >+ {label}+ {value === "activity" && events.length > 0 && (+ <span className="ml-1 text-[var(--muted-foreground)]">+ {events.length}</span>- </div>- <div className="mt-1.5 space-y-1">- {module.knowledge_points.map((kp) => (- <div- key={kp.id}- className="flex items-center gap-2 px-2 py-1 rounded-md text-sm"- >- <StatusIcon status={kp.status} />- <span className="flex-1 truncate text-[var(--foreground)]">- {kp.name}- </span>- <span className="text-[10px] uppercase tracking-wide text-[var(--muted-foreground)]">- {kp.type}- </span>- <span- className={`text-xs ${STATUS_META[kp.status].className}`}- >- {zh ? STATUS_META[kp.status].cn : STATUS_META[kp.status].en}- </span>- </div>- ))}- </div>- </div>+ )}+ </button>))}</div>++ <div className="mt-4">+ {tab === "map" ? (+ /* Keyed by path: switching paths must drop whichever objective was+ open, since its id belongs to the path that is going away. */+ <PathMap+ key={pathId}+ pathId={pathId}+ map={map}+ revision={revision}+ tr={tr}+ zh={zh}+ />+ ) : (+ <ActivityTimeline+ events={events}+ objectiveNames={objectiveNames}+ tr={tr}+ zh={zh}+ />+ )}+ </div></div>);}diff --git a/web/app/(workspace)/book/components/BookChatPanel.tsx b/web/app/(workspace)/book/components/BookChatPanel.tsxindex 846690763..41b7bbcf2 100644--- a/web/app/(workspace)/book/components/BookChatPanel.tsx+++ b/web/app/(workspace)/book/components/BookChatPanel.tsx@@ -396,10 +396,15 @@ export default function BookChatPanel({content: userContent,session_id: sessionIdRef.current,capability: "chat",- tools: book.knowledge_bases?.length ? ["rag"] : [],+ // No `tools` field: the backend back-fills the reader's own Settings+ // selection when it is absent (turn_runtime treats an explicit list —+ // including []) as a deliberate override), and `rag` mounts itself from+ // `knowledge_bases`. Pinning ["rag"] here disabled every other tool the+ // reader had switched on.knowledge_bases: book.knowledge_bases || [],attachments: attachments.map(outgoingAttachment),- language: appLanguage,+ // The book, not the UI chrome, decides the language of this conversation.+ language: book.language || appLanguage,book_references: [{ book_id: book.id, page_ids: [page.id] }],};sendWithRetry(client, payload);diff --git a/web/app/(workspace)/book/components/BookCreator.tsx b/web/app/(workspace)/book/components/BookCreator.tsxindex 16f7025db..c78f1d7c6 100644--- a/web/app/(workspace)/book/components/BookCreator.tsx+++ b/web/app/(workspace)/book/components/BookCreator.tsx@@ -16,7 +16,7 @@ import {} from "lucide-react";import { useTranslation } from "react-i18next";import { useAppShell } from "@/context/AppShellContext";-import type { BookProposal } from "@/lib/book-types";+import type { Book, BookDepth, BookProposal } from "@/lib/book-types";import {listKnowledgeBases,type KnowledgeBaseSummary,@@ -40,6 +40,48 @@ import {type SourceTab = "knowledge" | "notebooks" | "questions" | "chats";+/**+ * Languages a book can be written in.+ *+ * Mirrors `_LANGUAGE_LABELS` in `deeptutor/services/prompt/language.py`, which+ * has always handled all of these — the picker offered only English and+ * Chinese, so everyone else got a book in a language they didn't ask for+ * (issue #471). Labels are endonyms: someone looking for their own language+ * scans for the word they'd write it in.+ */+const BOOK_LANGUAGES: Array<{ code: string; label: string }> = [+ { code: "en", label: "English" },+ { code: "zh", label: "简体中文" },+ { code: "zh-tw", label: "繁體中文" },+ { code: "ja", label: "日本語" },+ { code: "ko", label: "한국어" },+ { code: "es", label: "Español" },+ { code: "fr", label: "Français" },+ { code: "de", label: "Deutsch" },+ { code: "ru", label: "Русский" },+ { code: "pt", label: "Português" },+ { code: "it", label: "Italiano" },+];++const DEPTH_OPTIONS: Array<{ value: BookDepth; label: string; hint: string }> =+ [+ {+ value: "brief",+ label: "Brief",+ hint: "Roughly half the prose per chapter — a fast orientation.",+ },+ {+ value: "standard",+ label: "Standard",+ hint: "The default balance of explanation, examples and practice.",+ },+ {+ value: "deep",+ label: "Deep",+ hint: "Longer treatments with more worked detail. Takes noticeably longer.",+ },+ ];+type Translate = (key: string, options?: Record<string, unknown>) => string;type ParentSelection<TChild extends string | number> =@@ -61,8 +103,11 @@ export interface BookCreatorProps {question_categories: number[];question_entries: number[];language: string;+ depth: BookDepth;}) => void | Promise<void>;loading?: boolean;+ /** The draft being edited, when one was reopened from the library. */+ book?: Book | null;proposal?: BookProposal | null;onConfirmProposal?: (edited: BookProposal) => void | Promise<void>;confirmLoading?: boolean;@@ -71,6 +116,7 @@ export interface BookCreatorProps {export default function BookCreator({onCreate,loading = false,+ book = null,proposal = null,onConfirmProposal,confirmLoading = false,@@ -78,8 +124,9 @@ export default function BookCreator({const { t } = useTranslation();const { language: appLanguage } = useAppShell();const [intent, setIntent] = useState("");- const [language, setLanguage] = useState(appLanguage);+ const [language, setLanguage] = useState<string>(appLanguage);const languageTouchedRef = useRef(false);+ const [depth, setDepth] = useState<BookDepth>("standard");const [tab, setTab] = useState<SourceTab>("knowledge");// Knowledge bases (flat selection)@@ -143,6 +190,10 @@ export default function BookCreator({const id = proposal ? proposal.title || "_proposal_" : null;if (id && id !== lastSeenProposalIdRef.current) {setFormCollapsed(true);+ // A new proposal replaces the old one outright. Keeping the previous+ // edits would show text belonging to a proposal that no longer exists —+ // and confirming would submit it.+ setEditProposal(null);}lastSeenProposalIdRef.current = id;}, [proposal]);@@ -328,6 +379,7 @@ export default function BookCreator({await onCreate({user_intent: intent,+ depth,chat_session_id: "",chat_selections,knowledge_bases: Array.from(selectedKbs),@@ -711,21 +763,48 @@ export default function BookCreator({</div></div>- <div className="flex items-center justify-between gap-3">- <label className="text-xs text-[var(--muted-foreground)]">- {t("Language")}{" "}- <select- value={language}- onChange={(e) => {- languageTouchedRef.current = true;- setLanguage(e.target.value as "en" | "zh");- }}- className="ml-1 rounded-md border border-[var(--border)] bg-[var(--background)] px-1.5 py-0.5 text-xs text-[var(--foreground)]"- >- <option value="en">{t("language.english")}</option>- <option value="zh">{t("language.chinese")}</option>- </select>- </label>+ <div className="flex flex-wrap items-center justify-between gap-3">+ <div className="flex flex-wrap items-center gap-4">+ <label className="text-xs text-[var(--muted-foreground)]">+ {t("Language")}{" "}+ <select+ value={language}+ onChange={(e) => {+ languageTouchedRef.current = true;+ setLanguage(e.target.value);+ }}+ className="ml-1 rounded-md border border-[var(--border)] bg-[var(--background)] px-1.5 py-0.5 text-xs text-[var(--foreground)]"+ >+ {BOOK_LANGUAGES.map((option) => (+ <option key={option.code} value={option.code}>+ {option.label}+ </option>+ ))}+ </select>+ </label>++ <div className="flex items-center gap-1.5 text-xs text-[var(--muted-foreground)]">+ {t("Depth")}+ <div className="inline-flex overflow-hidden rounded-md border border-[var(--border)] text-[11px]">+ {DEPTH_OPTIONS.map((option) => (+ <button+ key={option.value}+ type="button"+ onClick={() => setDepth(option.value)}+ aria-pressed={depth === option.value}+ title={t(option.hint)}+ className={`px-2 py-0.5 font-medium transition-colors ${+ depth === option.value+ ? "bg-[var(--primary)]/12 text-[var(--foreground)]"+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/40 hover:text-[var(--foreground)]"+ }`}+ >+ {t(option.label)}+ </button>+ ))}+ </div>+ </div>+ </div><buttononClick={handleCreate}disabled={loading || !intent.trim()}@@ -759,6 +838,7 @@ export default function BookCreator({proposal={currentProposal}onChange={setEditProposal}selectedKbs={Array.from(selectedKbs)}+ savedKbs={book?.knowledge_bases}/><div className="flex justify-end"><button@@ -1072,12 +1152,17 @@ function ProposalForm({proposal,onChange,selectedKbs,+ savedKbs,}: {proposal: BookProposal;onChange: (p: BookProposal) => void;selectedKbs: string[];+ /** KBs already recorded on the book. Reopening a draft restores no local+ * picker state, so without this the form claims the book has no sources. */+ savedKbs?: string[];}) {const { t } = useTranslation();+ const effectiveKbs = selectedKbs.length > 0 ? selectedKbs : (savedKbs ?? []);const update = (patch: Partial<BookProposal>) =>onChange({ ...proposal, ...patch });return (@@ -1143,14 +1228,14 @@ function ProposalForm({{t("Knowledge bases used")}</span><div className="mt-1.5 flex flex-wrap gap-1.5">- {selectedKbs.length === 0 ? (+ {effectiveKbs.length === 0 ? (<span className="text-xs italic text-[var(--muted-foreground)]">{t("No knowledge bases selected. The book will rely on general knowledge.",)}</span>) : (- selectedKbs.map((kb) => (+ effectiveKbs.map((kb) => (<spankey={kb}className="inline-flex items-center rounded-full border border-[var(--border)] bg-[var(--muted)]/40 px-2.5 py-0.5 text-[11px] text-[var(--foreground)]"diff --git a/web/app/(workspace)/book/components/BookHealthBanner.tsx b/web/app/(workspace)/book/components/BookHealthBanner.tsxindex d5bbd988b..cc61ed988 100644--- a/web/app/(workspace)/book/components/BookHealthBanner.tsx+++ b/web/app/(workspace)/book/components/BookHealthBanner.tsx@@ -9,6 +9,9 @@ export interface BookHealthBannerProps {bookId: string | null;refreshKey?: number;onRecompile?: (pageId: string) => void;+ /** Retrieval failed while this book was planned — it was written from the+ * proposal alone, with none of the selected sources behind it. */+ explorationFailed?: boolean;}interface KbDrift {@@ -30,6 +33,7 @@ export default function BookHealthBanner({bookId,refreshKey,onRecompile,+ explorationFailed = false,}: BookHealthBannerProps) {const { t } = useTranslation();const [kbDrift, setKbDrift] = useState<KbDrift | null>(null);@@ -44,6 +48,10 @@ export default function BookHealthBanner({setLogHealth(null);return;}+ // `refreshKey` is the book's `updated_at`, undefined until the book has+ // loaded. Waiting for it avoids a duplicate check on every open — and this+ // one is expensive: it stats every raw file in the book's knowledge bases.+ if (refreshKey === undefined) return;setDismissed(false);(async () => {try {@@ -76,7 +84,7 @@ export default function BookHealthBanner({const blockFailures = logHealth?.block_failures || 0;const hasLogIssues = blockFailures >= 3 || repeated.length > 0;- if (!hasDrift && !hasLogIssues) return null;+ if (!hasDrift && !hasLogIssues && !explorationFailed) return null;// Convert technical signatures into a short human label.const humanizeSignature = (sig: string): string => {@@ -101,6 +109,18 @@ export default function BookHealthBanner({<div className="flex items-start gap-3"><AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" /><div className="flex-1 space-y-1.5">+ {explorationFailed && (+ <div>+ <strong>+ {t("This book was written without reading your sources.")}+ </strong>{" "}+ <span>+ {t(+ "Retrieval failed while planning it, so the chapters come from the proposal alone. Rebuilding will try your knowledge bases again.",+ )}+ </span>+ </div>+ )}{hasDrift && (<div><strong>diff --git a/web/app/(workspace)/book/components/BookLibrary.tsx b/web/app/(workspace)/book/components/BookLibrary.tsxindex b049e7adf..7ca5ebfe0 100644--- a/web/app/(workspace)/book/components/BookLibrary.tsx+++ b/web/app/(workspace)/book/components/BookLibrary.tsx@@ -18,6 +18,7 @@ import type { CSSProperties } from "react";import { useTranslation } from "react-i18next";import type { Book, BookStatus } from "@/lib/book-types";+import { formatRelativeTime } from "@/lib/relative-time";const STATUS_STYLES: Record<BookStatus,@@ -40,6 +41,12 @@ const STATUS_STYLES: Record<"bg-violet-50 text-violet-700 dark:bg-violet-500/10 dark:text-violet-300",dot: "bg-violet-500 animate-pulse",},+ paused: {+ label: "Paused",+ className:+ "bg-amber-50 text-amber-700 dark:bg-amber-500/10 dark:text-amber-300",+ dot: "bg-amber-500",+ },ready: {label: "Ready",className:@@ -60,24 +67,6 @@ const STATUS_STYLES: Record<},};-function relativeTime(- seconds: number,- t: (key: string, options?: Record<string, unknown>) => string,-): string {- if (!seconds || Number.isNaN(seconds)) return "";- const diff = Date.now() / 1000 - seconds;- if (diff < 60) return t("just now");- const mins = Math.floor(diff / 60);- if (mins < 60) return t("{{count}}m ago", { count: mins });- const hrs = Math.floor(mins / 60);- if (hrs < 24) return t("{{count}}h ago", { count: hrs });- const days = Math.floor(hrs / 24);- if (days < 30) return t("{{count}}d ago", { count: days });- const months = Math.floor(days / 30);- if (months < 12) return t("{{count}}mo ago", { count: months });- return t("{{count}}y ago", { count: Math.floor(months / 12) });-}-// Stable, deterministic palette per book id so each cover feels distinct// without resorting to placeholder letters.const COVER_PALETTES: Array<{@@ -138,7 +127,6 @@ export interface BookLibraryProps {onNewBook: () => void;onSelectBook: (id: string) => void;onDeleteBook: (id: string) => void;- onLearn?: (book: Book) => void;}export default function BookLibrary({@@ -147,9 +135,8 @@ export default function BookLibrary({onNewBook,onSelectBook,onDeleteBook,- onLearn,}: BookLibraryProps) {- const { t } = useTranslation();+ const { t, i18n } = useTranslation();const [query, setQuery] = useState("");const [pendingDeleteId, setPendingDeleteId] = useState<string | null>(null);@@ -169,6 +156,7 @@ export default function BookLibrary({const inProgress = books.filter((b) =>b.status === "compiling" ||+ b.status === "paused" ||b.status === "spine_ready" ||b.status === "draft",).length;@@ -385,6 +373,20 @@ export default function BookLibrary({</button></div>+ {(book.reading?.percent ?? 0) > 0 && (+ <div+ className="h-0.5 w-full bg-[var(--muted)]"+ title={t("{{percent}}% read", {+ percent: book.reading?.percent ?? 0,+ })}+ >+ <div+ className="h-full bg-[var(--primary)]"+ style={{ width: `${book.reading?.percent ?? 0}%` }}+ />+ </div>+ )}+{/* Body */}<div className="flex flex-1 flex-col gap-2 p-4"><div@@ -416,22 +418,27 @@ export default function BookLibrary({</div><span className="inline-flex items-center gap-1"><Clock3 size={11} />- {relativeTime(book.updated_at, t) || "—"}+ {formatRelativeTime(book.updated_at, i18n.language) ||+ "—"}</span></div>- {onLearn && book.status === "ready" && (- <button- type="button"- onClick={(e) => {- e.stopPropagation();- onLearn(book);- }}- className="mt-2 inline-flex items-center gap-1 rounded-md bg-[var(--primary)] px-3 py-1.5 text-xs font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90"- >- <GraduationCap size={13} />- {t("Start learning")}- </button>- )}+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ onSelectBook(book.id);+ }}+ className="mt-2 inline-flex items-center justify-center gap-1 rounded-md bg-[var(--primary)] px-3 py-1.5 text-xs font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90"+ >+ <GraduationCap size={13} />+ {/* Reading position is persisted, so the card can say+ what opening it will actually do. */}+ {book.status === "draft" || book.status === "spine_ready"+ ? t("Continue setup")+ : (book.reading?.visited_pages ?? 0) > 0+ ? t("Continue reading")+ : t("Start reading")}+ </button></div></div>);diff --git a/web/app/(workspace)/book/components/BookPausedBanner.tsx b/web/app/(workspace)/book/components/BookPausedBanner.tsxnew file mode 100644index 000000000..66d6f4c15--- /dev/null+++ b/web/app/(workspace)/book/components/BookPausedBanner.tsx@@ -0,0 +1,66 @@+"use client";++import { Loader2, PauseCircle, Play } from "lucide-react";+import { useTranslation } from "react-i18next";++import type { Book } from "@/lib/book-types";++export interface BookPausedBannerProps {+ book: Book | null;+ onResume: () => void;+ resuming?: boolean;+}++/**+ * Shown when compilation stopped itself after repeated provider failures.+ *+ * The reassurance is the point: the book stopped *early* precisely so the+ * remaining chapters weren't ground into half-generated debris, and picking up+ * where it left off costs only the work that is genuinely missing.+ */+export default function BookPausedBanner({+ book,+ onResume,+ resuming = false,+}: BookPausedBannerProps) {+ const { t } = useTranslation();+ if (!book || book.status !== "paused") return null;++ const reason = String(book.metadata?.pause_reason || "").trim();++ return (+ <div className="border-b border-amber-300/70 bg-amber-50 px-8 py-3 text-amber-950 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-100">+ <div className="mx-auto flex w-full max-w-[78ch] items-start gap-3">+ <PauseCircle className="mt-0.5 h-4 w-4 shrink-0" />+ <div className="min-w-0 flex-1">+ <div className="text-[13px] font-semibold">+ {t("Generation paused")}+ </div>+ <p className="mt-0.5 text-xs leading-relaxed opacity-90">+ {t(+ "Your model provider kept refusing requests, so the remaining chapters were left untouched rather than half-written. Everything generated so far is saved.",+ )}+ </p>+ {reason && (+ <code className="mt-1.5 block truncate rounded bg-white/50 px-1.5 py-0.5 text-[11px] dark:bg-white/10">+ {reason}+ </code>+ )}+ </div>+ <button+ type="button"+ onClick={onResume}+ disabled={resuming}+ className="inline-flex shrink-0 items-center gap-1.5 rounded-md border border-current px-2.5 py-1 text-xs font-medium hover:bg-white/40 disabled:cursor-not-allowed disabled:opacity-50 dark:hover:bg-white/10"+ >+ {resuming ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Play className="h-3.5 w-3.5" />+ )}+ {resuming ? t("Resuming…") : t("Resume generation")}+ </button>+ </div>+ </div>+ );+}diff --git a/web/app/(workspace)/book/components/BookSidebar.tsx b/web/app/(workspace)/book/components/BookSidebar.tsxindex 2f4d9f139..a1a9a4c46 100644--- a/web/app/(workspace)/book/components/BookSidebar.tsx+++ b/web/app/(workspace)/book/components/BookSidebar.tsx@@ -1,14 +1,16 @@"use client";-import { useState } from "react";+import { useEffect, useState } from "react";import {ArrowLeft,ChevronLeft,ChevronRight,Compass,+ Download,Loader2,RotateCcw,} from "lucide-react";+import { bookApi } from "@/lib/book-api";import { useTranslation } from "react-i18next";import type { Book, Page } from "@/lib/book-types";@@ -29,6 +31,8 @@ export interface BookSidebarProps {onSelectPage?: (id: string) => void;onRebuild?: () => void;rebuilding?: boolean;+ visitedPageIds?: string[];+ bookmarkedPageIds?: string[];}export default function BookSidebar({@@ -39,9 +43,20 @@ export default function BookSidebar({onSelectPage,onRebuild,rebuilding = false,+ visitedPageIds,+ bookmarkedPageIds,}: BookSidebarProps) {const { t } = useTranslation();const [collapsed, setCollapsed] = useState(false);+ const [confirmRebuild, setConfirmRebuild] = useState(false);++ // Destructive controls forget: an armed state that outlives the interaction+ // turns the next stray click into an unconfirmed rebuild.+ useEffect(() => {+ if (!confirmRebuild) return;+ const timer = setTimeout(() => setConfirmRebuild(false), 3500);+ return () => clearTimeout(timer);+ }, [confirmRebuild]);if (collapsed) {return (@@ -121,20 +136,59 @@ export default function BookSidebar({</div>)}- {onRebuild && (- <button- type="button"- onClick={onRebuild}- disabled={rebuilding}- className="inline-flex items-center justify-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--card)] px-2 py-1.5 text-xs font-medium text-[var(--muted-foreground)] hover:border-[var(--primary)]/40 hover:text-[var(--primary)] disabled:opacity-60"+ {book && (+ <a+ href={bookApi.exportUrl(book.id)}+ download+ className="inline-flex items-center justify-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--card)] px-2 py-1.5 text-xs font-medium text-[var(--muted-foreground)] hover:border-[var(--primary)]/40 hover:text-[var(--primary)]">- {rebuilding ? (- <Loader2 className="h-3.5 w-3.5 animate-spin" />- ) : (- <RotateCcw className="h-3.5 w-3.5" />+ <Download className="h-3.5 w-3.5" />+ {t("Export Markdown")}+ </a>+ )}++ {/* Rebuild deletes every page AND resets progress — reading position,+ bookmarks, quiz history, notes and in-place edits all go. It needs the+ same two-step confirmation the library uses for deleting a book. */}+ {onRebuild && (+ <div className="space-y-1">+ <button+ type="button"+ onClick={() => {+ if (confirmRebuild) {+ setConfirmRebuild(false);+ onRebuild();+ } else {+ setConfirmRebuild(true);+ }+ }}+ onBlur={() => setConfirmRebuild(false)}+ disabled={rebuilding}+ className={`inline-flex w-full items-center justify-center gap-1.5 rounded-md border px-2 py-1.5 text-xs font-medium disabled:opacity-60 ${+ confirmRebuild+ ? "border-rose-400/60 bg-rose-500/10 text-rose-600 dark:text-rose-300"+ : "border-[var(--border)] bg-[var(--card)] text-[var(--muted-foreground)] hover:border-[var(--primary)]/40 hover:text-[var(--primary)]"+ }`}+ >+ {rebuilding ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <RotateCcw className="h-3.5 w-3.5" />+ )}+ {rebuilding+ ? t("Rebuilding…")+ : confirmRebuild+ ? t("Click again to rebuild")+ : t("Rebuild book")}+ </button>+ {confirmRebuild && !rebuilding && (+ <p className="px-1 text-[10px] leading-snug text-[var(--muted-foreground)]">+ {t(+ "Replaces every generated chapter and clears your reading progress, bookmarks, notes and edits.",+ )}+ </p>)}- {t("Rebuild book")}- </button>+ </div>)}<section className="flex-1 overflow-y-auto">@@ -155,7 +209,9 @@ export default function BookSidebar({<li key={page.id}><buttononClick={() => onSelectPage?.(page.id)}- className={`flex w-full items-start justify-between gap-2 rounded-md px-2 py-1.5 text-left text-xs ${+ className={`flex w-full items-start justify-between gap-2 rounded-md py-1.5 pr-2 text-left text-xs ${+ page.parent_page_id ? "pl-5" : "pl-2"+ } ${active? "bg-[var(--primary)]/15 text-[var(--foreground)]": "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/40 hover:text-[var(--foreground)]"@@ -173,8 +229,32 @@ export default function BookSidebar({{page.title || t("Untitled")}</span></span>- <span className="shrink-0 rounded-full bg-[var(--muted)] px-1.5 py-0.5 text-[9px] uppercase tracking-wider text-[var(--muted-foreground)]">- {t(STATUS_LABEL[page.status] || page.status)}+ <span className="flex shrink-0 items-center gap-1">+ {bookmarkedPageIds?.includes(page.id) && (+ <span+ className="h-1.5 w-1.5 rounded-full bg-[var(--primary)]"+ title={t("Bookmarked")}+ />+ )}+ {page.status === "ready" && (+ <span+ className={+ visitedPageIds?.includes(page.id)+ ? "text-[var(--muted-foreground)]/70"+ : "text-[var(--primary)]"+ }+ title={+ visitedPageIds?.includes(page.id)+ ? t("Read")+ : t("Unread")+ }+ >+ {visitedPageIds?.includes(page.id) ? "✓" : "•"}+ </span>+ )}+ <span className="rounded-full bg-[var(--muted)] px-1.5 py-0.5 text-[9px] uppercase tracking-wider text-[var(--muted-foreground)]">+ {t(STATUS_LABEL[page.status] || page.status)}+ </span></span></button></li>diff --git a/web/app/(workspace)/book/components/PageOutlineNav.tsx b/web/app/(workspace)/book/components/PageOutlineNav.tsxindex b30e496ee..b3ec04d9b 100644--- a/web/app/(workspace)/book/components/PageOutlineNav.tsx+++ b/web/app/(workspace)/book/components/PageOutlineNav.tsx@@ -186,6 +186,10 @@ export default function PageOutlineNav({<navaria-label={headerText}aria-hidden={collapsed}+ // Not just aria-hidden: a collapsed panel still holds one button per+ // block, and without `inert` Tab lands inside something invisible.+ // Mirrors the parked-drawer treatment in AppShell.+ inert={collapsed ? true : undefined}className={["flex w-56 flex-col text-[12.5px]",collapsed ? "pointer-events-none" : "pointer-events-auto",diff --git a/web/app/(workspace)/book/components/PageReader.tsx b/web/app/(workspace)/book/components/PageReader.tsxindex 00ed7496d..9784a1a0f 100644--- a/web/app/(workspace)/book/components/PageReader.tsx+++ b/web/app/(workspace)/book/components/PageReader.tsx@@ -2,15 +2,20 @@import { useEffect, useRef, useState } from "react";import {+ Bookmark,+ BookmarkCheck,Loader2,RefreshCcw,Plus,ChevronDown,+ ChevronLeft,+ ChevronRight,ChevronUp,} from "lucide-react";import { useTranslation } from "react-i18next";-import type { Block, BlockType, Page } from "@/lib/book-types";+import type { Block, BlockType, Page, QuizAttempt } from "@/lib/book-types";import BlockRenderer from "./blocks/BlockRenderer";+import type { QuizAttemptArgs } from "./blocks/QuizBlock";import PageOutlineNav from "./PageOutlineNav";const INSERTABLE_TYPES: BlockType[] = [@@ -35,15 +40,25 @@ export interface PageReaderProps {onChangeBlockType?: (block: Block, newType: BlockType) => void;onInsertBlock?: (block_type: BlockType) => Promise<void> | void;onDeepDive?: (topic: string, blockId: string) => Promise<void> | void;- onQuizAttempt?: (- block: Block,- args: { questionId?: string; userAnswer?: string; isCorrect: boolean },- ) => void;+ onOpenPage?: (pageId: string) => void;+ onQuizAttempt?: (block: Block, args: QuizAttemptArgs) => void;+ /** Reader asked for extra practice on a quiz they got wrong. */+ onRequestSupplement?: (block: Block) => void;+ supplementingBlockId?: string | null;+ onUpdateBody?: (block: Block, body: string) => Promise<void> | void;+ /** Previous quiz answers, so they survive leaving and returning. */+ attempts?: QuizAttempt[];onRecompile?: () => void;pendingDeepDiveTopic?: string | null;loading?: boolean;bookId?: string;bookLanguage?: string;+ // ── Chapter navigation ──+ previousPage?: Page | null;+ nextPage?: Page | null;+ onNavigate?: (pageId: string) => void;+ bookmarked?: boolean;+ onToggleBookmark?: () => void;}export default function PageReader({@@ -54,12 +69,22 @@ export default function PageReader({onChangeBlockType,onInsertBlock,onDeepDive,+ onOpenPage,onQuizAttempt,+ onRequestSupplement,+ supplementingBlockId,+ onUpdateBody,+ attempts,onRecompile,pendingDeepDiveTopic,loading = false,bookId,bookLanguage,+ previousPage,+ nextPage,+ onNavigate,+ bookmarked = false,+ onToggleBookmark,}: PageReaderProps) {const { t } = useTranslation();const [showInsertMenu, setShowInsertMenu] = useState(false);@@ -105,6 +130,29 @@ export default function PageReader({return () => scrollContainer.removeEventListener("scroll", handler);}, [scrollContainer, userToggled]);+ useEffect(() => {+ if (!onNavigate) return;+ const handler = (event: KeyboardEvent) => {+ if (event.metaKey || event.ctrlKey || event.altKey) return;+ const target = event.target as HTMLElement | null;+ // Never steal arrow keys from a field the reader is typing in.+ if (+ target &&+ (target.isContentEditable ||+ ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName))+ ) {+ return;+ }+ if (event.key === "ArrowLeft" && previousPage) {+ onNavigate(previousPage.id);+ } else if (event.key === "ArrowRight" && nextPage) {+ onNavigate(nextPage.id);+ }+ };+ window.addEventListener("keydown", handler);+ return () => window.removeEventListener("keydown", handler);+ }, [onNavigate, previousPage, nextPage]);+if (!page) {return (<div className="flex h-full items-center justify-center text-[var(--muted-foreground)]">@@ -154,6 +202,27 @@ export default function PageReader({{t(page.status)}</span>)}+ {onToggleBookmark && (+ <button+ type="button"+ onClick={onToggleBookmark}+ title={+ bookmarked ? t("Remove bookmark") : t("Bookmark this chapter")+ }+ aria-pressed={bookmarked}+ className={`inline-flex h-6 w-6 items-center justify-center rounded-md transition-colors ${+ bookmarked+ ? "text-[var(--primary)]"+ : "text-[var(--muted-foreground)] hover:bg-[var(--background)] hover:text-[var(--foreground)]"+ }`}+ >+ {bookmarked ? (+ <BookmarkCheck className="h-3.5 w-3.5" />+ ) : (+ <Bookmark className="h-3.5 w-3.5" />+ )}+ </button>+ )}{!headerCollapsed && onRecompile && (<buttononClick={onRecompile}@@ -272,7 +341,12 @@ export default function PageReader({onMove={onMoveBlock}onChangeType={onChangeBlockType}onDeepDive={onDeepDive}+ onOpenPage={onOpenPage}onQuizAttempt={onQuizAttempt}+ onRequestSupplement={onRequestSupplement}+ supplementing={supplementingBlockId === block.id}+ onUpdateBody={onUpdateBody}+ attempts={attempts}pendingDeepDiveTopic={pendingDeepDiveTopic}bookId={bookId}currentPageId={page.id}@@ -327,6 +401,28 @@ export default function PageReader({)}</div>+ {(previousPage || nextPage) && onNavigate && (+ <footer className="border-t border-[var(--border)] bg-[var(--card)]/60 px-8 py-2.5">+ <div className="mx-auto flex w-full max-w-[78ch] items-center justify-between gap-3">+ <NavButton+ page={previousPage}+ direction="previous"+ label={t("Previous chapter")}+ onNavigate={onNavigate}+ />+ <span className="shrink-0 text-[10px] uppercase tracking-wider text-[var(--muted-foreground)]/70">+ {t("← / → to turn pages")}+ </span>+ <NavButton+ page={nextPage}+ direction="next"+ label={t("Next chapter")}+ onNavigate={onNavigate}+ />+ </div>+ </footer>+ )}+{/* Floating outline lives outside the scroll container so it stayspinned to the viewport regardless of page scrolling. */}<PageOutlineNav@@ -338,3 +434,37 @@ export default function PageReader({</div>);}++function NavButton({+ page,+ direction,+ label,+ onNavigate,+}: {+ page: Page | null | undefined;+ direction: "previous" | "next";+ label: string;+ onNavigate: (pageId: string) => void;+}) {+ if (!page) return <span className="min-w-0 flex-1" />;+ const isNext = direction === "next";+ return (+ <button+ type="button"+ onClick={() => onNavigate(page.id)}+ className={`group inline-flex min-w-0 flex-1 items-center gap-1.5 rounded-md px-2 py-1 text-xs text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)]/40 hover:text-[var(--foreground)] ${+ isNext ? "justify-end text-right" : "justify-start text-left"+ }`}+ title={page.title}+ >+ {!isNext && <ChevronLeft className="h-3.5 w-3.5 shrink-0" />}+ <span className="min-w-0">+ <span className="block text-[10px] uppercase tracking-wider opacity-70">+ {label}+ </span>+ <span className="block truncate">{page.title}</span>+ </span>+ {isNext && <ChevronRight className="h-3.5 w-3.5 shrink-0" />}+ </button>+ );+}diff --git a/web/app/(workspace)/book/components/SpineEditor.tsx b/web/app/(workspace)/book/components/SpineEditor.tsxindex 2adee0463..5b0914929 100644--- a/web/app/(workspace)/book/components/SpineEditor.tsx+++ b/web/app/(workspace)/book/components/SpineEditor.tsx@@ -6,11 +6,15 @@ import {Plus,Trash2,CheckCircle2,+ Clock3,+ FileText,+ Layers,Loader2,} from "lucide-react";-import { useState } from "react";+import { useEffect, useMemo, useState } from "react";import { useTranslation } from "react-i18next";-import type { Chapter, ContentType, Spine } from "@/lib/book-types";+import { bookApi, type EstimateBasis } from "@/lib/book-api";+import type { BookDepth, Chapter, ContentType, Spine } from "@/lib/book-types";/*** Each chapter declares a *content type* — a hint to the SectionArchitect@@ -26,6 +30,31 @@ interface ContentTypeOption {description: string;}+function ScopeOption({+ active,+ label,+ onClick,+}: {+ active: boolean;+ label: string;+ onClick: () => void;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ aria-pressed={active}+ className={`px-2.5 py-1.5 font-medium transition-colors ${+ active+ ? "bg-[var(--primary)]/12 text-[var(--foreground)]"+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/40 hover:text-[var(--foreground)]"+ }`}+ >+ {label}+ </button>+ );+}+const CONTENT_TYPE_OPTIONS: ContentTypeOption[] = [{value: "theory",@@ -58,17 +87,58 @@ const CONTENT_TYPE_OPTIONS: ContentTypeOption[] = [export interface SpineEditorProps {spine: Spine;- onConfirm: (spine: Spine) => void | Promise<void>;+ onConfirm: (spine: Spine, autoCompile: boolean) => void | Promise<void>;loading?: boolean;+ /** Book depth, so the estimate matches what will actually be generated. */+ depth?: BookDepth;}export default function SpineEditor({spine,onConfirm,loading = false,+ depth = "standard",}: SpineEditorProps) {const { t } = useTranslation();- const [chapters, setChapters] = useState<Chapter[]>(spine.chapters);+ // Engine-injected chapters (the overview, deep-dive sub-pages) are not part+ // of the structure the reader authors, so they stay out of the editor.+ const [chapters, setChapters] = useState<Chapter[]>(() =>+ spine.chapters.filter((c) => !c.auto_overview && !c.deep_dive),+ );+ const [autoCompile, setAutoCompile] = useState(true);+ const [basis, setBasis] = useState<EstimateBasis | null>(null);++ useEffect(() => {+ let cancelled = false;+ void bookApi+ .estimateBasis(depth)+ .then((result) => {+ if (!cancelled) setBasis(result.basis);+ })+ .catch(() => {+ // An estimate is a courtesy; its absence must not block confirming.+ });+ return () => {+ cancelled = true;+ };+ }, [depth]);++ const estimate = useMemo(() => {+ if (!basis) return null;+ let words = 0;+ let seconds = 0;+ for (const chapter of chapters) {+ const cost = basis[chapter.content_type] || basis.theory;+ if (!cost) continue;+ words += cost.words;+ seconds += cost.seconds;+ }+ return {+ chapters: chapters.length,+ words,+ minutes: Math.ceil(seconds / 60),+ };+ }, [basis, chapters]);const updateChapter = (idx: number, patch: Partial<Chapter>) => {setChapters((prev) =>@@ -110,10 +180,20 @@ export default function SpineEditor({};const handleConfirm = async () => {- const cleaned = chapters- .filter((c) => c.title.trim())- .map((c, i) => ({ ...c, order: i }));- await onConfirm({ ...spine, chapters: cleaned });+ const edited = chapters.filter((c) => c.title.trim());+ // Re-attach what the editor hid, so confirming never silently deletes an+ // overview or a deep dive — but in their proper places: the overview leads+ // the book, deep dives trail it. Appending everything to the end left the+ // overview out of position and carrying a stale `order`.+ const overview = spine.chapters.filter((c) => c.auto_overview);+ const deepDives = spine.chapters.filter(+ (c) => c.deep_dive && !c.auto_overview,+ );+ const merged = [...overview, ...edited, ...deepDives].map((c, i) => ({+ ...c,+ order: i,+ }));+ await onConfirm({ ...spine, chapters: merged }, autoCompile);};return (@@ -246,19 +326,68 @@ export default function SpineEditor({</div></div>- <footer className="flex items-center justify-end gap-3 border-t border-[var(--border)] bg-[var(--card)]/60 px-6 py-3">- <button- onClick={handleConfirm}- disabled={loading}- className="inline-flex items-center gap-2 rounded-xl bg-[var(--primary)] px-4 py-2 text-sm font-medium text-[var(--primary-foreground)] hover:opacity-90 disabled:opacity-50"- >- {loading ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : (- <CheckCircle2 className="h-4 w-4" />- )}- {t("Confirm spine & start compiling")}- </button>+ <footer className="border-t border-[var(--border)] bg-[var(--card)]/60 px-6 py-3">+ <div className="mx-auto flex w-full max-w-3xl flex-wrap items-center justify-between gap-3">+ {/* Confirming here starts dozens of model calls. Say so first. */}+ <div className="flex items-center gap-3 text-[11px] text-[var(--muted-foreground)]">+ <span className="inline-flex items-center gap-1">+ <Layers className="h-3 w-3" />+ {t("{{count}} chapters", { count: chapters.length })}+ </span>+ {estimate && estimate.words > 0 && (+ <>+ <span className="inline-flex items-center gap-1">+ <FileText className="h-3 w-3" />+ {t("~{{count}} words", {+ count: Math.round(estimate.words / 100) * 100,+ })}+ </span>+ <span className="inline-flex items-center gap-1">+ <Clock3 className="h-3 w-3" />+ {t("~{{count}} min to generate", { count: estimate.minutes })}+ </span>+ </>+ )}+ </div>++ <div className="flex items-center gap-2">+ {/* #655: the backend always supported deferring compilation; only+ the UI insisted on building everything up front. */}+ <div className="inline-flex overflow-hidden rounded-lg border border-[var(--border)] text-[11px]">+ <ScopeOption+ active={autoCompile}+ label={t("Generate all chapters")}+ onClick={() => setAutoCompile(true)}+ />+ <ScopeOption+ active={!autoCompile}+ label={t("First chapter only")}+ onClick={() => setAutoCompile(false)}+ />+ </div>+ <button+ onClick={handleConfirm}+ disabled={loading}+ className="inline-flex items-center gap-2 rounded-xl bg-[var(--primary)] px-4 py-2 text-sm font-medium text-[var(--primary-foreground)] hover:opacity-90 disabled:opacity-50"+ >+ {loading ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <CheckCircle2 className="h-4 w-4" />+ )}+ {autoCompile+ ? t("Confirm spine & start compiling")+ : t("Confirm spine")}+ </button>+ </div>+ </div>+ {!autoCompile && (+ <p className="mx-auto mt-2 w-full max-w-3xl text-[11px] text-[var(--muted-foreground)]">+ {t(+ "Chapters will be generated the first time you open them — useful when you want to read as you go, or keep an eye on model usage.",+ )}+ </p>+ )}</footer></div>);diff --git a/web/app/(workspace)/book/components/blocks/BlockBodyEditor.tsx b/web/app/(workspace)/book/components/blocks/BlockBodyEditor.tsxnew file mode 100644index 000000000..9306b45e8--- /dev/null+++ b/web/app/(workspace)/book/components/blocks/BlockBodyEditor.tsx@@ -0,0 +1,98 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { Check, Loader2, X } from "lucide-react";+import { useTranslation } from "react-i18next";++export interface BlockBodyEditorProps {+ initialValue: string;+ onSave: (value: string) => Promise<void> | void;+ onCancel: () => void;+}++/**+ * Inline prose editor for a single block.+ *+ * Intentionally plain. Fixing a wrong sentence should feel like correcting a+ * document, not like operating a CMS — and anything more ambitious than a+ * touch-up belongs in Co-Writer, not in the reader.+ */+export default function BlockBodyEditor({+ initialValue,+ onSave,+ onCancel,+}: BlockBodyEditorProps) {+ const { t } = useTranslation();+ const [draft, setDraft] = useState(initialValue);+ const [saving, setSaving] = useState(false);+ const textareaRef = useRef<HTMLTextAreaElement | null>(null);++ useEffect(() => {+ const node = textareaRef.current;+ if (!node) return;+ node.focus();+ node.setSelectionRange(node.value.length, node.value.length);+ // Grow to fit so a long section doesn't open as a four-line slot.+ node.style.height = "auto";+ node.style.height = `${Math.min(node.scrollHeight, 640)}px`;+ }, []);++ const commit = async () => {+ if (saving) return;+ setSaving(true);+ try {+ await onSave(draft);+ } finally {+ setSaving(false);+ }+ };++ return (+ <div className="space-y-2 rounded-xl border border-[var(--primary)]/40 bg-[var(--card)] p-2">+ <textarea+ ref={textareaRef}+ value={draft}+ onChange={(event) => setDraft(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Escape") {+ event.preventDefault();+ onCancel();+ } else if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {+ event.preventDefault();+ void commit();+ }+ }}+ className="w-full resize-y rounded-md border border-[var(--border)] bg-[var(--background)] px-3 py-2 font-mono text-[13px] leading-relaxed text-[var(--foreground)] outline-none focus:border-[var(--primary)]/50"+ />+ <div className="flex items-center justify-between gap-2">+ <span className="text-[11px] text-[var(--muted-foreground)]">+ {t("Markdown supported. ⌘/Ctrl + Enter to save, Esc to cancel.")}+ </span>+ <div className="flex items-center gap-1.5">+ <button+ type="button"+ onClick={onCancel}+ disabled={saving}+ className="inline-flex items-center gap-1 rounded-md border border-[var(--border)] bg-[var(--card)] px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)] hover:text-[var(--foreground)] disabled:opacity-50"+ >+ <X className="h-3 w-3" />+ {t("Cancel")}+ </button>+ <button+ type="button"+ onClick={() => void commit()}+ disabled={saving}+ className="inline-flex items-center gap-1 rounded-md bg-[var(--primary)] px-2.5 py-1 text-[11px] font-medium text-[var(--primary-foreground)] hover:opacity-90 disabled:opacity-50"+ >+ {saving ? (+ <Loader2 className="h-3 w-3 animate-spin" />+ ) : (+ <Check className="h-3 w-3" />+ )}+ {t("Save")}+ </button>+ </div>+ </div>+ </div>+ );+}diff --git a/web/app/(workspace)/book/components/blocks/BlockRenderer.tsx b/web/app/(workspace)/book/components/blocks/BlockRenderer.tsxindex af2b8dc95..006b850b7 100644--- a/web/app/(workspace)/book/components/blocks/BlockRenderer.tsx+++ b/web/app/(workspace)/book/components/blocks/BlockRenderer.tsx@@ -1,9 +1,10 @@"use client";-import { useState } from "react";+import { useEffect, useState } from "react";import {AlertTriangle,Loader2,+ Pencil,RefreshCw,Trash2,ArrowUp,@@ -11,12 +12,13 @@ import {Replace,} from "lucide-react";import { useTranslation } from "react-i18next";-import type { Block, BlockType } from "@/lib/book-types";+import type { Block, BlockType, QuizAttempt } from "@/lib/book-types";import MarkdownRenderer from "@/components/common/MarkdownRenderer";+import BlockBodyEditor from "./BlockBodyEditor";import TextBlock from "./TextBlock";import CalloutBlock from "./CalloutBlock";-import QuizBlock from "./QuizBlock";+import QuizBlock, { type QuizAttemptArgs } from "./QuizBlock";import UserNoteBlock from "./UserNoteBlock";import FigureBlock from "./FigureBlock";import InteractiveBlock from "./InteractiveBlock";@@ -29,6 +31,21 @@ import ConceptGraphBlock from "./ConceptGraphBlock";import SectionBlock from "./SectionBlock";import PlaceholderBlock from "./PlaceholderBlock";+// How long a destructive control stays armed before it forgets.+const CONFIRM_WINDOW_MS = 3500;++// Blocks that are a single run of prose, so a plain text box can edit them+// without destroying structure the renderer depends on. Mirrors+// `_EDITABLE_BLOCK_TYPES` on the backend.+const EDITABLE_BODY_TYPES: BlockType[] = ["text", "callout"];++/** Where a block keeps its prose — `text` blocks use both keys, historically. */+function bodyKeyFor(block: Block): "body" | "content" {+ return block.type === "text" && "content" in (block.payload || {})+ ? "content"+ : "body";+}+const CHANGEABLE_TYPES: BlockType[] = ["text","section",@@ -50,10 +67,14 @@ export interface BlockRendererProps {onMove?: (block: Block, direction: "up" | "down") => void;onChangeType?: (block: Block, newType: BlockType) => void;onDeepDive?: (topic: string, blockId: string) => Promise<void> | void;- onQuizAttempt?: (- block: Block,- args: { questionId?: string; userAnswer?: string; isCorrect: boolean },- ) => void;+ onOpenPage?: (pageId: string) => void;+ onQuizAttempt?: (block: Block, args: QuizAttemptArgs) => void;+ onRequestSupplement?: (block: Block) => void;+ supplementing?: boolean;+ /** Previous quiz answers, passed through to `QuizBlock`. */+ attempts?: QuizAttempt[];+ /** Save edited prose. Omit to render the block read-only. */+ onUpdateBody?: (block: Block, body: string) => Promise<void> | void;pendingDeepDiveTopic?: string | null;bookId?: string;currentPageId?: string;@@ -67,7 +88,12 @@ export default function BlockRenderer({onMove,onChangeType,onDeepDive,+ onOpenPage,onQuizAttempt,+ onRequestSupplement,+ supplementing = false,+ attempts,+ onUpdateBody,pendingDeepDiveTopic,bookId,currentPageId,@@ -75,6 +101,17 @@ export default function BlockRenderer({}: BlockRendererProps) {const { t } = useTranslation();const [showTypeMenu, setShowTypeMenu] = useState(false);+ const [editingBody, setEditingBody] = useState(false);+ const [confirmDelete, setConfirmDelete] = useState(false);++ // The delete control lives in a toolbar that only exists while the pointer is+ // over the block. Auto-disarm so an armed state can never outlive the+ // interaction that created it and surprise the next click.+ useEffect(() => {+ if (!confirmDelete) return;+ const timer = setTimeout(() => setConfirmDelete(false), CONFIRM_WINDOW_MS);+ return () => clearTimeout(timer);+ }, [confirmDelete]);if (block.status === "pending" || block.status === "generating") {return (@@ -127,10 +164,30 @@ export default function BlockRenderer({body = <CalloutBlock block={block} />;break;case "quiz":- body = <QuizBlock block={block} onAttempt={onQuizAttempt} />;+ body = (+ <QuizBlock+ block={block}+ onAttempt={onQuizAttempt}+ attempts={attempts}+ onRequestSupplement={+ onRequestSupplement ? () => onRequestSupplement(block) : undefined+ }+ supplementing={supplementing}+ />+ );break;case "user_note":- body = <UserNoteBlock block={block} />;+ body = (+ <UserNoteBlock+ block={block}+ onSave={+ onUpdateBody ? (value) => onUpdateBody(block, value) : undefined+ }+ // A note the reader just inserted is empty by definition — drop+ // them straight into it rather than making them find the pencil.+ autoEdit={!String(block.payload?.body || "").trim()}+ />+ );break;case "figure":body = <FigureBlock block={block} />;@@ -155,6 +212,7 @@ export default function BlockRenderer({<DeepDiveBlockblock={block}onDeepDive={onDeepDive}+ onOpenPage={onOpenPage}pendingTopic={pendingDeepDiveTopic}/>);@@ -173,7 +231,29 @@ export default function BlockRenderer({body = <PlaceholderBlock block={block} />;}- const hasActions = !!onRegenerate || !!onDelete || !!onMove || !!onChangeType;+ const canEditBody =+ !!onUpdateBody && EDITABLE_BODY_TYPES.includes(block.type);+ const currentBody = String(+ (block.payload as Record<string, unknown> | undefined)?.[+ bodyKeyFor(block)+ ] ?? "",+ );++ if (editingBody && onUpdateBody) {+ body = (+ <BlockBodyEditor+ initialValue={currentBody}+ onSave={async (value) => {+ await onUpdateBody(block, value);+ setEditingBody(false);+ }}+ onCancel={() => setEditingBody(false)}+ />+ );+ }++ const hasActions =+ !!onRegenerate || !!onDelete || !!onMove || !!onChangeType || canEditBody;const bridgeText = String((block.payload as Record<string, unknown> | undefined)?.bridge_text ?? "",@@ -236,6 +316,15 @@ export default function BlockRenderer({)}</div>)}+ {canEditBody && !editingBody && (+ <button+ onClick={() => setEditingBody(true)}+ className="pointer-events-auto rounded p-1 hover:bg-[var(--background)] hover:text-[var(--foreground)]"+ title={t("Edit text")}+ >+ <Pencil className="h-3.5 w-3.5" />+ </button>+ )}{onRegenerate && (<buttononClick={() => onRegenerate(block)}@@ -247,9 +336,25 @@ export default function BlockRenderer({)}{onDelete && (<button- onClick={() => onDelete(block)}- className="pointer-events-auto rounded p-1 hover:bg-rose-100 hover:text-rose-700 dark:hover:bg-rose-500/10 dark:hover:text-rose-200"- title={t("Delete")}+ onClick={() => {+ if (confirmDelete) {+ setConfirmDelete(false);+ onDelete(block);+ } else {+ setConfirmDelete(true);+ }+ }}+ onBlur={() => setConfirmDelete(false)}+ className={`pointer-events-auto rounded p-1 ${+ confirmDelete+ ? "bg-rose-500/15 text-rose-600 dark:text-rose-300"+ : "hover:bg-rose-100 hover:text-rose-700 dark:hover:bg-rose-500/10 dark:hover:text-rose-200"+ }`}+ title={+ confirmDelete+ ? t("Click again to delete this block")+ : t("Delete")+ }><Trash2 className="h-3.5 w-3.5" /></button>diff --git a/web/app/(workspace)/book/components/blocks/ConceptGraphBlock.tsx b/web/app/(workspace)/book/components/blocks/ConceptGraphBlock.tsxindex 986bd7806..fa9c94c7a 100644--- a/web/app/(workspace)/book/components/blocks/ConceptGraphBlock.tsx+++ b/web/app/(workspace)/book/components/blocks/ConceptGraphBlock.tsx@@ -132,7 +132,7 @@ export default function ConceptGraphBlock({return (<li key={chapter.id}><Link- href={`/book/${bookId}?page=${chapter.page_id}`}+ href={`/book?book=${encodeURIComponent(bookId)}&page=${encodeURIComponent(chapter.page_id)}`}title={chapter.title}className="block rounded-md px-2 py-1.5 hover:bg-[var(--background)]">diff --git a/web/app/(workspace)/book/components/blocks/DeepDiveBlock.tsx b/web/app/(workspace)/book/components/blocks/DeepDiveBlock.tsxindex 76a05e3ce..319d76b52 100644--- a/web/app/(workspace)/book/components/blocks/DeepDiveBlock.tsx+++ b/web/app/(workspace)/book/components/blocks/DeepDiveBlock.tsx@@ -1,7 +1,7 @@"use client";import { useState } from "react";-import { ChevronRight, Sparkles, Loader2 } from "lucide-react";+import { ArrowUpRight, ChevronRight, Sparkles, Loader2 } from "lucide-react";import { useTranslation } from "react-i18next";import type { Block } from "@/lib/book-types";@@ -13,22 +13,38 @@ interface Suggestion {export interface DeepDiveBlockProps {block: Block;onDeepDive?: (topic: string, blockId: string) => Promise<void> | void;+ onOpenPage?: (pageId: string) => void;pendingTopic?: string | null;}export default function DeepDiveBlock({block,onDeepDive,+ onOpenPage,pendingTopic,}: DeepDiveBlockProps) {const { t } = useTranslation();const suggestions =(block.payload?.suggestions as Suggestion[] | undefined) || [];- const linkedPageId = block.metadata?.deep_dive_page_id as string | undefined;++ // Each suggested topic tracks its own sub-page. Books written before this was+ // keyed by topic carry a single `deep_dive_page_id`; treat that as belonging+ // to the first topic rather than to all of them.+ const pagesByTopic =+ (block.metadata?.deep_dive_pages as Record<string, string> | undefined) ||+ {};+ const legacyPageId = block.metadata?.deep_dive_page_id as string | undefined;+const [busy, setBusy] = useState<string | null>(null);if (suggestions.length === 0) return null;+ const pageFor = (topic: string, index: number): string | undefined =>+ pagesByTopic[topic] ||+ (index === 0 && Object.keys(pagesByTopic).length === 0+ ? legacyPageId+ : undefined);+return (<div className="rounded-2xl border border-[var(--primary)]/30 bg-gradient-to-br from-[var(--primary)]/5 to-transparent p-4 shadow-sm"><div className="mb-3 flex items-center gap-2">@@ -41,11 +57,20 @@ export default function DeepDiveBlock({{suggestions.map((s, i) => {const topic = s.topic || "";const isPending = busy === topic || pendingTopic === topic;+ const existingPageId = pageFor(topic, i);+ const anyPending = !!busy || !!pendingTopic;+return (- <li key={i}>+ <li key={topic || i}><buttononClick={async () => {- if (!onDeepDive || !topic) return;+ if (!topic) return;+ // Already expanded → this is the way back to that chapter.+ if (existingPageId) {+ onOpenPage?.(existingPageId);+ return;+ }+ if (!onDeepDive) return;setBusy(topic);try {await onDeepDive(topic, block.id);@@ -53,12 +78,24 @@ export default function DeepDiveBlock({setBusy(null);}}}- disabled={isPending || !!linkedPageId}+ // Only the topic being generated locks, plus the others while a+ // generation is in flight. Choosing one no longer retires the rest.+ disabled={isPending || (anyPending && !existingPageId)}+ title={+ existingPageId+ ? t("Open the chapter this created")+ : t("Generate a chapter on this")+ }className="group flex w-full items-start justify-between gap-3 rounded-xl border border-[var(--border)] bg-[var(--card)] px-3 py-2 text-left transition hover:border-[var(--primary)]/40 disabled:opacity-60"><div className="flex-1">- <div className="text-sm font-medium text-[var(--foreground)]">+ <div className="flex items-center gap-1.5 text-sm font-medium text-[var(--foreground)]">{topic}+ {existingPageId && (+ <span className="rounded-full bg-[var(--primary)]/10 px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wider text-[var(--primary)]">+ {t("Created")}+ </span>+ )}</div>{s.rationale && (<div className="mt-0.5 text-xs leading-relaxed text-[var(--muted-foreground)]">@@ -68,6 +105,8 @@ export default function DeepDiveBlock({</div>{isPending ? (<Loader2 className="h-4 w-4 shrink-0 animate-spin text-[var(--primary)]" />+ ) : existingPageId ? (+ <ArrowUpRight className="h-4 w-4 shrink-0 text-[var(--primary)]" />) : (<ChevronRight className="h-4 w-4 shrink-0 text-[var(--muted-foreground)] transition group-hover:translate-x-0.5 group-hover:text-[var(--primary)]" />)}@@ -76,11 +115,6 @@ export default function DeepDiveBlock({);})}</ul>- {linkedPageId && (- <p className="mt-2 text-[11px] text-[var(--muted-foreground)]">- {t("Linked sub-page already exists.")}- </p>- )}</div>);}diff --git a/web/app/(workspace)/book/components/blocks/QuizBlock.tsx b/web/app/(workspace)/book/components/blocks/QuizBlock.tsxindex df0c054d5..f770f2b7e 100644--- a/web/app/(workspace)/book/components/blocks/QuizBlock.tsx+++ b/web/app/(workspace)/book/components/blocks/QuizBlock.tsx@@ -1,11 +1,18 @@"use client";-import { useEffect, useRef, useState } from "react";-import { CheckCircle2, Eye, EyeOff, XCircle } from "lucide-react";+import { useEffect, useMemo, useRef, useState } from "react";+import {+ CheckCircle2,+ Eye,+ EyeOff,+ Loader2,+ Sparkles,+ XCircle,+} from "lucide-react";import { useTranslation } from "react-i18next";import MarkdownRenderer from "@/components/common/MarkdownRenderer";-import type { Block } from "@/lib/book-types";+import type { Block, QuizAttempt } from "@/lib/book-types";import {isChoiceQuizQuestion,normalizeQuizQuestionType,@@ -15,7 +22,8 @@ import {export interface QuizAttemptArgs {questionId?: string;userAnswer?: string;- isCorrect: boolean;+ /** `undefined` when the reader revealed a written answer without self-grading. */+ isCorrect?: boolean;}interface QuizQuestion {@@ -31,12 +39,41 @@ interface QuizQuestion {export interface QuizBlockProps {block: Block;onAttempt?: (block: Block, args: QuizAttemptArgs) => void;+ /** Previous attempts, so answering survives a page switch or a refresh. */+ attempts?: QuizAttempt[];+ onRequestSupplement?: () => void;+ supplementing?: boolean;}-export default function QuizBlock({ block, onAttempt }: QuizBlockProps) {+export default function QuizBlock({+ block,+ onAttempt,+ attempts,+ onRequestSupplement,+ supplementing = false,+}: QuizBlockProps) {const { t } = useTranslation();const questions =(block.payload?.questions as QuizQuestion[] | undefined) || [];++ // Latest attempt per question — what the reader last did here.+ const lastAttempts = useMemo(() => {+ const byQuestion = new Map<string, QuizAttempt>();+ for (const attempt of attempts ?? []) {+ if (attempt.block_id !== block.id) continue;+ byQuestion.set(attempt.question_id, attempt);+ }+ return byQuestion;+ }, [attempts, block.id]);++ const [gotSomethingWrong, setGotSomethingWrong] = useState(false);+ const hasRecordedMiss = useMemo(+ () => [...lastAttempts.values()].some((a) => a.is_correct === false),+ [lastAttempts],+ );+ const offerSupplement =+ !!onRequestSupplement && (gotSomethingWrong || hasRecordedMiss);+if (questions.length === 0) {return (<div className="text-sm text-[var(--muted-foreground)]">@@ -44,6 +81,7 @@ export default function QuizBlock({ block, onAttempt }: QuizBlockProps) {</div>);}+return (<section><div className="mb-3 flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-[var(--primary)]">@@ -57,10 +95,35 @@ export default function QuizBlock({ block, onAttempt }: QuizBlockProps) {key={q.question_id || idx}index={idx}question={q}- onAttempt={(args) => onAttempt?.(block, args)}+ previous={lastAttempts.get(q.question_id || "")}+ onAttempt={(args) => {+ if (args.isCorrect === false) setGotSomethingWrong(true);+ onAttempt?.(block, args);+ }}/>))}</div>++ {offerSupplement && (+ <div className="mt-3 flex items-center justify-between gap-3 rounded-xl border border-dashed border-[var(--primary)]/40 bg-[var(--primary)]/[0.04] px-3 py-2">+ <span className="text-xs text-[var(--muted-foreground)]">+ {t("Missed one? I can add a worked explanation and an easier set.")}+ </span>+ <button+ type="button"+ onClick={onRequestSupplement}+ disabled={supplementing}+ className="inline-flex shrink-0 items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--card)] px-2.5 py-1 text-xs font-medium text-[var(--muted-foreground)] hover:border-[var(--primary)]/40 hover:text-[var(--primary)] disabled:cursor-not-allowed disabled:opacity-60"+ >+ {supplementing ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Sparkles className="h-3.5 w-3.5" />+ )}+ {supplementing ? t("Adding…") : t("Add extra practice")}+ </button>+ </div>+ )}</section>);}@@ -68,46 +131,67 @@ export default function QuizBlock({ block, onAttempt }: QuizBlockProps) {function QuizQuestionCard({index,question,+ previous,onAttempt,}: {index: number;question: QuizQuestion;+ previous?: QuizAttempt;onAttempt?: (args: QuizAttemptArgs) => void;}) {const { t } = useTranslation();- const [selected, setSelected] = useState<string | null>(null);- const [revealed, setRevealed] = useState(false);- const reportedRef = useRef<string | null>(null);const normalizedType = normalizeQuizQuestionType(question.question_type);const options = question.options || {};const isChoice = isChoiceQuizQuestion(normalizedType);const correct = String(question.correct_answer || "").trim();const correctChoiceKey = resolveChoiceAnswerKey(correct, options);- const reportKey = `${question.question_id || index}:${selected || ""}`;+ // Restore what the reader last did, so leaving and coming back doesn't wipe+ // their answers — the attempts were always persisted, just never read back.+ const [selected, setSelected] = useState<string | null>(+ previous && isChoice ? previous.user_answer || null : null,+ );+ const [revealed, setRevealed] = useState(!!previous);+ const [selfGraded, setSelfGraded] = useState<boolean | null>(+ previous && !isChoice ? previous.is_correct : null,+ );++ const reportedRef = useRef<string | null>(+ previous+ ? `${question.question_id || index}:${previous.user_answer || ""}`+ : null,+ );++ // Choice questions grade themselves the moment the answer is revealed.useEffect(() => {- if (- revealed &&- selected &&- reportedRef.current !== reportKey &&- onAttempt- ) {- reportedRef.current = reportKey;- onAttempt({- questionId: question.question_id,- userAnswer: selected,- isCorrect: selected.toUpperCase() === correctChoiceKey,- });- }+ if (!isChoice || !revealed || !selected || !onAttempt) return;+ const reportKey = `${question.question_id || index}:${selected}`;+ if (reportedRef.current === reportKey) return;+ reportedRef.current = reportKey;+ onAttempt({+ questionId: question.question_id,+ userAnswer: selected,+ isCorrect: selected.toUpperCase() === correctChoiceKey,+ });}, [- reportKey,+ isChoice,revealed,selected,onAttempt,question.question_id,correctChoiceKey,+ index,]);+ const recordSelfGrade = (isCorrect: boolean) => {+ setSelfGraded(isCorrect);+ onAttempt?.({+ questionId: question.question_id,+ userAnswer: isCorrect ? "self:correct" : "self:incorrect",+ isCorrect,+ });+ };+return (<div className="rounded-xl border border-[var(--border)] bg-[var(--background)] p-3"><div className="flex items-start justify-between gap-2">@@ -207,6 +291,30 @@ function QuizQuestionCard({</div>)}+ {/* Written answers can only be graded by the reader. Without this they+ were invisible to progress entirely — practice chapters scored zero. */}+ {revealed && !isChoice && (+ <div className="mt-2 flex items-center justify-between gap-2 rounded-lg bg-[var(--muted)]/30 px-2.5 py-1.5">+ <span className="text-xs text-[var(--muted-foreground)]">+ {t("How did you do?")}+ </span>+ <div className="flex items-center gap-1.5">+ <SelfGradeButton+ active={selfGraded === true}+ tone="correct"+ label={t("Got it right")}+ onClick={() => recordSelfGrade(true)}+ />+ <SelfGradeButton+ active={selfGraded === false}+ tone="incorrect"+ label={t("Missed it")}+ onClick={() => recordSelfGrade(false)}+ />+ </div>+ </div>+ )}+{revealed && question.explanation && (<div className="mt-2 rounded-lg border border-[var(--border)] bg-[var(--muted)]/40 p-2"><MarkdownRenderer@@ -218,3 +326,38 @@ function QuizQuestionCard({</div>);}++function SelfGradeButton({+ active,+ tone,+ label,+ onClick,+}: {+ active: boolean;+ tone: "correct" | "incorrect";+ label: string;+ onClick: () => void;+}) {+ const activeClass =+ tone === "correct"+ ? "border-emerald-300 bg-emerald-50 text-emerald-800 dark:border-emerald-500/40 dark:bg-emerald-500/10 dark:text-emerald-200"+ : "border-rose-300 bg-rose-50 text-rose-800 dark:border-rose-500/40 dark:bg-rose-500/10 dark:text-rose-200";+ return (+ <button+ type="button"+ onClick={onClick}+ className={`inline-flex items-center gap-1 rounded-md border px-2 py-0.5 text-[11px] font-medium transition-colors ${+ active+ ? activeClass+ : "border-[var(--border)] bg-[var(--card)] text-[var(--muted-foreground)] hover:border-[var(--primary)]/40 hover:text-[var(--foreground)]"+ }`}+ >+ {tone === "correct" ? (+ <CheckCircle2 className="h-3 w-3" />+ ) : (+ <XCircle className="h-3 w-3" />+ )}+ {label}+ </button>+ );+}diff --git a/web/app/(workspace)/book/components/blocks/TextBlock.tsx b/web/app/(workspace)/book/components/blocks/TextBlock.tsxindex df2e50856..014739011 100644--- a/web/app/(workspace)/book/components/blocks/TextBlock.tsx+++ b/web/app/(workspace)/book/components/blocks/TextBlock.tsx@@ -8,7 +8,10 @@ export interface TextBlockProps {}export default function TextBlock({ block }: TextBlockProps) {- const body = String(block.payload?.body ?? "");+ // Generated text blocks store prose under `body`; the deterministically+ // built overview blocks use `content`. Accept both — reading only one meant+ // the overview intro and chapter index rendered as empty divs.+ const body = String(block.payload?.body ?? block.payload?.content ?? "");return (<div className="text-[var(--foreground)]">diff --git a/web/app/(workspace)/book/components/blocks/UserNoteBlock.tsx b/web/app/(workspace)/book/components/blocks/UserNoteBlock.tsxindex ae084c821..8238e9d34 100644--- a/web/app/(workspace)/book/components/blocks/UserNoteBlock.tsx+++ b/web/app/(workspace)/book/components/blocks/UserNoteBlock.tsx@@ -1,30 +1,150 @@"use client";-import { StickyNote } from "lucide-react";+import { useEffect, useRef, useState } from "react";+import { Check, Loader2, Pencil, StickyNote, X } from "lucide-react";import { useTranslation } from "react-i18next";+import MarkdownRenderer from "@/components/common/MarkdownRenderer";import type { Block } from "@/lib/book-types";export interface UserNoteBlockProps {block: Block;+ /** Omit to render read-only (e.g. in a preview context). */+ onSave?: (body: string) => Promise<void> | void;+ /** Start in edit mode — used when the note was just inserted. */+ autoEdit?: boolean;}-export default function UserNoteBlock({ block }: UserNoteBlockProps) {+/**+ * The reader's own margin note.+ *+ * Previously this rendered the invitation "start writing your own annotation"+ * with nowhere to write: the block type, the payload field and the insert+ * action all existed, but no editor was ever wired up.+ */+export default function UserNoteBlock({+ block,+ onSave,+ autoEdit = false,+}: UserNoteBlockProps) {const { t } = useTranslation();const body = String(block.payload?.body || "");+ const editable = !!onSave;++ const [editing, setEditing] = useState(autoEdit && editable);+ const [draft, setDraft] = useState(body);+ const [saving, setSaving] = useState(false);+ const textareaRef = useRef<HTMLTextAreaElement | null>(null);++ // Re-sync when the block changes underneath us (a refresh, another device).+ useEffect(() => {+ if (!editing) setDraft(body);+ }, [body, editing]);++ useEffect(() => {+ if (!editing) return;+ const node = textareaRef.current;+ if (!node) return;+ node.focus();+ node.setSelectionRange(node.value.length, node.value.length);+ }, [editing]);++ const commit = async () => {+ if (!onSave || saving) return;+ setSaving(true);+ try {+ await onSave(draft);+ setEditing(false);+ } finally {+ setSaving(false);+ }+ };++ const cancel = () => {+ setDraft(body);+ setEditing(false);+ };+return (- <aside className="flex gap-3 border-l-[3px] border-dashed border-[var(--primary)]/50 bg-[var(--primary)]/[0.04] py-2 pl-4 pr-3">+ <aside className="group/note flex gap-3 border-l-[3px] border-dashed border-[var(--primary)]/50 bg-[var(--primary)]/[0.04] py-2 pl-4 pr-3"><StickyNote className="mt-[3px] h-4 w-4 shrink-0 text-[var(--primary)]" />- <div className="min-w-0 space-y-1">- <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-[var(--primary)]">- {t("Your note")}+ <div className="min-w-0 flex-1 space-y-1">+ <div className="flex items-center justify-between gap-2">+ <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-[var(--primary)]">+ {t("Your note")}+ </div>+ {editable && !editing && (+ <button+ type="button"+ onClick={() => setEditing(true)}+ title={t("Edit note")}+ className="inline-flex h-6 w-6 items-center justify-center rounded-md text-[var(--muted-foreground)] opacity-0 transition-opacity hover:bg-[var(--background)] hover:text-[var(--foreground)] group-hover/note:opacity-100"+ >+ <Pencil className="h-3 w-3" />+ </button>+ )}</div>- {body ? (++ {editing ? (+ <div className="space-y-1.5">+ <textarea+ ref={textareaRef}+ value={draft}+ onChange={(event) => setDraft(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Escape") {+ event.preventDefault();+ cancel();+ } else if (+ event.key === "Enter" &&+ (event.metaKey || event.ctrlKey)+ ) {+ event.preventDefault();+ void commit();+ }+ }}+ rows={4}+ placeholder={t("Markdown supported. ⌘/Ctrl + Enter to save.")}+ className="w-full resize-y rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1.5 text-sm text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]/60 focus:border-[var(--primary)]/50"+ />+ <div className="flex items-center justify-end gap-1.5">+ <button+ type="button"+ onClick={cancel}+ disabled={saving}+ className="inline-flex items-center gap-1 rounded-md border border-[var(--border)] bg-[var(--card)] px-2 py-0.5 text-[11px] font-medium text-[var(--muted-foreground)] hover:text-[var(--foreground)] disabled:opacity-50"+ >+ <X className="h-3 w-3" />+ {t("Cancel")}+ </button>+ <button+ type="button"+ onClick={() => void commit()}+ disabled={saving}+ className="inline-flex items-center gap-1 rounded-md bg-[var(--primary)] px-2 py-0.5 text-[11px] font-medium text-[var(--primary-foreground)] hover:opacity-90 disabled:opacity-50"+ >+ {saving ? (+ <Loader2 className="h-3 w-3 animate-spin" />+ ) : (+ <Check className="h-3 w-3" />+ )}+ {t("Save")}+ </button>+ </div>+ </div>+ ) : body ? (<MarkdownRenderer content={body} variant="compact" />) : (- <div className="text-xs text-[var(--muted-foreground)]">- {t("Empty note – start writing your own annotation.")}- </div>+ <button+ type="button"+ onClick={() => editable && setEditing(true)}+ disabled={!editable}+ className="text-left text-xs text-[var(--muted-foreground)] hover:text-[var(--foreground)] disabled:cursor-default disabled:hover:text-[var(--muted-foreground)]"+ >+ {editable+ ? t("Empty note — click to start writing your own annotation.")+ : t("Empty note.")}+ </button>)}</div></aside>diff --git a/web/app/(workspace)/book/page.tsx b/web/app/(workspace)/book/page.tsxindex ffc5b37fa..2318f3654 100644--- a/web/app/(workspace)/book/page.tsx+++ b/web/app/(workspace)/book/page.tsx@@ -19,29 +19,70 @@ import type {Block,BlockType,Book,+ BookDepth,BookDetail,BookProposal,Page,Spine,} from "@/lib/book-types";import {+ RESET_BOOK_PROGRESS,emptyBookProgress,progressHasActivity,progressIsComplete,reduceBookEvent,} from "@/lib/book-progress";+import {+ bookEventKind,+ bookEventPageId,+ useBookStream,+} from "@/lib/use-book-stream";import BookChatPanel from "./components/BookChatPanel";import BookCreator from "./components/BookCreator";import BookHealthBanner from "./components/BookHealthBanner";import BookLibrary from "./components/BookLibrary";+import BookPausedBanner from "./components/BookPausedBanner";import BookProgressTimeline from "./components/BookProgressTimeline";import BookSidebar from "./components/BookSidebar";import PageReader from "./components/PageReader";import SpineEditor from "./components/SpineEditor";+import type { QuizAttemptArgs } from "./components/blocks/QuizBlock";type View = "list" | "creator" | "spine" | "reader";+// Blocks land one at a time during compilation. Coalescing a burst into a+// single fetch keeps a page that is actively generating from issuing one+// request per block, while still feeling immediate to a reader watching it.+const PAGE_REFRESH_DEBOUNCE_MS = 250;++// Book-level events arrive in bursts too — several stages finishing together,+// or the whole recent history replayed when a subscriber (re)connects. One+// burst should cost one refresh, not one per event.+const BOOK_REFRESH_DEBOUNCE_MS = 300;++/** A page fetched as a summary has its blocks stripped; hydrate before reading. */+function needsHydration(page: Page | null): boolean {+ return !!page && page.blocks.length === 0 && (page.block_count ?? 0) > 0;+}++/** Events that only change one chapter — refetch that page alone. */+const PAGE_SCOPED_EVENTS = new Set([+ "page_planned",+ "page_compile_started",+ "block_ready",+ "block_error",+ "page_compiled",+]);++/** Events that change the book itself — chapter list, status, or both. */+const BOOK_SCOPED_EVENTS = new Set([+ "spine_ready",+ "overview_ready",+ "book_ready",+ "compilation_paused",+]);+export default function BookPage() {// `useSearchParams()` requires a Suspense boundary during static prerender// (Next.js CSR bailout). Wrap the actual page implementation here so the@@ -49,7 +90,7 @@ export default function BookPage() {return (<Suspensefallback={- <div className="flex h-screen w-full items-center justify-center text-[var(--muted-foreground)]">+ <div className="flex h-full w-full items-center justify-center text-[var(--muted-foreground)]"><Loader2 className="mr-2 h-4 w-4 animate-spin" /> <BookLoadingText /></div>}@@ -70,7 +111,6 @@ function BookPageInner() {const [books, setBooks] = useState<Book[]>([]);const [loadingBooks, setLoadingBooks] = useState(false);const [view, setView] = useState<View>("list");- const [toast, setToast] = useState("");const [selectedBookId, setSelectedBookId] = useState<string | null>(null);const [detail, setDetail] = useState<BookDetail | null>(null);@@ -96,6 +136,10 @@ function BookPageInner() {>(null);const [chatOpen, setChatOpen] = useState(false);const [rebuildingBook, setRebuildingBook] = useState(false);+ const [resumingBook, setResumingBook] = useState(false);+ const [supplementingBlockId, setSupplementingBlockId] = useState<+ string | null+ >(null);// Phase 5 — live BookEngine progress timeline state.const [progress, dispatchProgress] = useReducer(@@ -106,6 +150,23 @@ function BookPageInner() {// ── Data loaders ───────────────────────────────────────────────────+ /** Run a mutation, surfacing failures instead of dropping them. */+ const guard = useCallback(+ async (action: string, run: () => Promise<void>): Promise<void> => {+ try {+ await run();+ } catch (err) {+ const reason = err instanceof Error ? err.message : String(err);+ notify(t("{{action}} failed: {{reason}}", { action, reason }), {+ tone: "error",+ durationMs: 8000,+ });+ console.error(`${action} failed:`, err);+ }+ },+ [t],+ );+const refreshBooks = useCallback(async () => {setLoadingBooks(true);try {@@ -116,49 +177,135 @@ function BookPageInner() {}}, []);+ /**+ * Load a book without its block payloads.+ *+ * Only the page being read needs its blocks; fetching every page's rendered+ * content to draw a sidebar meant a multi-chapter book cost hundreds of+ * kilobytes per refresh. `hydratePage` fills in the one page that matters.+ */const loadBookDetail = useCallback(async (id: string) => {- const data = await bookApi.get(id);+ const data = await bookApi.get(id, { includeBlocks: false });setDetail(data);return data;}, []);+ /** Replace one page in-place, leaving the rest of the book untouched. */+ const mergePage = useCallback((page: Page) => {+ setDetail((current) => {+ if (!current || current.book.id !== page.book_id) return current;+ const index = current.pages.findIndex((p) => p.id === page.id);+ if (index < 0) return current;+ const pages = [...current.pages];+ pages[index] = page;+ return { ...current, pages };+ });+ }, []);++ const hydratePage = useCallback(+ async (pageId: string) => {+ if (!selectedBookId) return;+ try {+ const { page } = await bookApi.getPage(selectedBookId, pageId);+ mergePage(page);+ } catch (err) {+ console.error("hydratePage failed:", err);+ }+ },+ [selectedBookId, mergePage],+ );++ // Debounced per page, so a burst of block events costs one fetch.+ const pageRefreshTimers = useRef(+ new Map<string, ReturnType<typeof setTimeout>>(),+ );+ const schedulePageRefresh = useCallback(+ (pageId: string) => {+ const timers = pageRefreshTimers.current;+ const pending = timers.get(pageId);+ if (pending) clearTimeout(pending);+ timers.set(+ pageId,+ setTimeout(() => {+ timers.delete(pageId);+ void hydratePage(pageId);+ }, PAGE_REFRESH_DEBOUNCE_MS),+ );+ },+ [hydratePage],+ );++ const bookRefreshTimer = useRef<ReturnType<typeof setTimeout> | undefined>(+ undefined,+ );+ const scheduleBookRefresh = useCallback(() => {+ if (bookRefreshTimer.current) clearTimeout(bookRefreshTimer.current);+ bookRefreshTimer.current = setTimeout(() => {+ bookRefreshTimer.current = undefined;+ if (selectedBookId) void loadBookDetail(selectedBookId);+ void refreshBooks();+ }, BOOK_REFRESH_DEBOUNCE_MS);+ }, [selectedBookId, loadBookDetail, refreshBooks]);++ useEffect(() => {+ const timers = pageRefreshTimers.current;+ return () => {+ timers.forEach((timer) => clearTimeout(timer));+ timers.clear();+ if (bookRefreshTimer.current) clearTimeout(bookRefreshTimer.current);+ };+ }, []);+useEffect(() => {void refreshBooks();}, [refreshBooks]);+ // The generation timeline describes one book's run. Clear it when the reader+ // moves to another book, or the previous book's stages stay on screen.useEffect(() => {- if (!toast) return;- const timer = setTimeout(() => setToast(""), 3500);- return () => clearTimeout(timer);- }, [toast]);+ dispatchProgress(RESET_BOOK_PROGRESS);+ }, [selectedBookId]);- // ── Live WS event handling ─────────────────────────────────────────+ // ── Live event handling ────────────────────────────────────────────- const handleBookOperationEvent = useCallback(+ const handleBookEvent = useCallback((event: BookWsEvent) => {- // Each long-running operation owns its WebSocket. Feed those streamed- // events into the shared timeline and refresh persisted milestones.dispatchProgress(event);- const meta =- (event.metadata as Record<string, unknown> | undefined) || {};- const kind = String(- (event.content as string) || (meta.kind as string) || "",- );- if (- selectedBookId &&- (kind === "block_ready" ||- kind === "block_error" ||- kind === "page_compiled" ||- kind === "page_planned" ||- kind === "spine_ready")- ) {- void loadBookDetail(selectedBookId);+ const kind = bookEventKind(event);+ const pageId = bookEventPageId(event);++ // Page-scoped: refetch just that chapter. Refetching the whole book on+ // every block was the single most expensive thing this screen did.+ if (pageId && PAGE_SCOPED_EVENTS.has(kind)) {+ schedulePageRefresh(pageId);+ return;+ }++ // Book-scoped: the chapter list or the book's own state moved.+ if (BOOK_SCOPED_EVENTS.has(kind)) {+ scheduleBookRefresh();}++ // Deliberately no toast here: `compilation_paused` is replayed to every+ // new subscriber, so a book that was paused once and resumed would pop a+ // stale alert on each reconnect. Pausing is durable state, and+ // BookPausedBanner renders it from `book.status`, which the refresh+ // above has just brought up to date.},- [selectedBookId, loadBookDetail],+ [scheduleBookRefresh, schedulePageRefresh],);+ // One connection per open book, independent of any action in flight —+ // background compilation keeps streaming long after the call that queued it.+ useBookStream(selectedBookId, handleBookEvent);++ // Ideation runs before the book exists, so it has no stream of its own to+ // subscribe to; those events arrive on the creating socket instead.+ const handleCreationEvent = useCallback((event: BookWsEvent) => {+ dispatchProgress(event);+ }, []);+// ── Selectors ──────────────────────────────────────────────────────const selectedPage: Page | null = useMemo(() => {@@ -166,6 +313,17 @@ function BookPageInner() {return detail.pages.find((p) => p.id === selectedPageId) || null;}, [detail, selectedPageId]);+ // Reading order is the page order — the sidebar shows the same sequence.+ const pageNeighbours = useMemo(() => {+ if (!detail || !selectedPageId) return { previous: null, next: null };+ const index = detail.pages.findIndex((p) => p.id === selectedPageId);+ if (index < 0) return { previous: null, next: null };+ return {+ previous: detail.pages[index - 1] || null,+ next: detail.pages[index + 1] || null,+ };+ }, [detail, selectedPageId]);+const selectedPageChatSessionId = useMemo(() => {if (!detail?.book || !selectedPage) return null;const sessions = detail.book.metadata?.page_chat_sessions;@@ -187,7 +345,7 @@ function BookPageInner() {const lastDeepLinkedBookId = useRef<string | null>(null);const handleSelectBook = useCallback(- async (id: string | null) => {+ async (id: string | null, openPageId?: string | null) => {if (!id) {setSelectedBookId(null);setDetail(null);@@ -196,67 +354,98 @@ function BookPageInner() {}setSelectedBookId(id);const data = await loadBookDetail(id);+ const hasReadableContent = data.pages.some(+ (p) => p.status !== "pending" || (p.block_count ?? p.blocks.length) > 0,+ );if (data.book.status === "draft" && data.book.proposal) {setPendingBook(data.book);setPendingProposal(data.book.proposal);setView("creator");- } else if (data.book.status === "spine_ready" && data.spine) {+ } else if (+ data.book.status === "spine_ready" &&+ data.spine &&+ !hasReadableContent+ ) {+ // Spine confirmed but nothing built yet — the editor is still the right+ // place. Once any chapter exists, the reader is.setView("spine");} else {- const firstReady = data.pages.find((p) => p.status === "ready");- const firstAny = data.pages[0] || null;- setSelectedPageId((firstReady || firstAny)?.id || null);+ // Resume where the reader left off — that's what `current_page_id` is+ // for, and until now nothing ever read it.+ const requested =+ (openPageId && data.pages.find((p) => p.id === openPageId)) || null;+ const resumed =+ data.pages.find((p) => p.id === data.progress.current_page_id) ||+ null;+ const firstReady = data.pages.find((p) => p.status === "ready") || null;+ const target =+ requested || resumed || firstReady || data.pages[0] || null;+ setSelectedPageId(target?.id || null);setView("reader");}},[loadBookDetail],);- // Allow deep-linking via /book?book=<id> (e.g. from the global sidebar).+ // Deep links: /book?book=<id>[&page=<id>] — used by the global sidebar and+ // by the overview chapter index (which previously pointed at /book/<id>, a+ // route that does not exist, so every entry 404'd).const searchParams = useSearchParams();const requestedBookId = searchParams?.get("book") || null;+ const requestedPageId = searchParams?.get("page") || null;useEffect(() => {if (!requestedBookId) return;if (requestedBookId === selectedBookId) return;if (requestedBookId === lastDeepLinkedBookId.current) return;lastDeepLinkedBookId.current = requestedBookId;- void handleSelectBook(requestedBookId);- }, [requestedBookId, selectedBookId, handleSelectBook]);-- const handleDeleteBook = async (id: string) => {- if (!confirm(t("Delete this book? This cannot be undone."))) return;- await bookApi.delete(id);- if (selectedBookId === id) {- setSelectedBookId(null);- setDetail(null);- setView("list");- }- await refreshBooks();- };+ void handleSelectBook(requestedBookId, requestedPageId);+ }, [requestedBookId, requestedPageId, selectedBookId, handleSelectBook]);++ const handleDeleteBook = async (id: string) =>+ guard("Delete book", async () => {+ // The library card already requires a second click to confirm.+ await bookApi.delete(id);+ if (selectedBookId === id) {+ setSelectedBookId(null);+ setDetail(null);+ setView("list");+ }+ await refreshBooks();+ });- const handleRebuildBook = async () => {+ const handleResumeBook = async () => {if (!detail) return;- if (- !confirm(- t(- "Rebuild this book using the current chapter structure? Existing generated pages will be replaced.",- ),- )- ) {- return;- }- setRebuildingBook(true);+ setResumingBook(true);try {- await bookApi.rebuild(detail.book.id, true);- const refreshed = await loadBookDetail(detail.book.id);- setSelectedPageId(refreshed.pages[0]?.id || null);- setView("reader");+ await bookApi.resume(detail.book.id);+ await loadBookDetail(detail.book.id);await refreshBooks();+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ notify(t("Could not resume: {{message}}", { message: msg }), {+ tone: "error",+ durationMs: 8000,+ });} finally {- setRebuildingBook(false);+ setResumingBook(false);}};+ const handleRebuildBook = async () =>+ guard("Rebuild book", async () => {+ if (!detail) return;+ setRebuildingBook(true);+ try {+ await bookApi.rebuild(detail.book.id, true);+ const refreshed = await loadBookDetail(detail.book.id);+ setSelectedPageId(refreshed.pages[0]?.id || null);+ setView("reader");+ await refreshBooks();+ } finally {+ setRebuildingBook(false);+ }+ });+const handleCreate = async (payload: {user_intent: string;chat_session_id: string;@@ -266,10 +455,11 @@ function BookPageInner() {question_categories: number[];question_entries: number[];language: string;+ depth: BookDepth;}) => {setCreating(true);try {- const result = await bookApi.create(payload, handleBookOperationEvent);+ const result = await bookApi.create(payload, handleCreationEvent);setPendingBook(result.book);setPendingProposal(result.proposal);setSelectedBookId(result.book.id);@@ -283,11 +473,10 @@ function BookPageInner() {if (!pendingBook) return;setConfirmingProposal(true);try {- const result = await bookApi.confirmProposal(- pendingBook.id,- edited,- handleBookOperationEvent,- );+ // No per-action event callback: the book now has a stream of its own,+ // and `useBookStream` is already listening. Passing one too would feed+ // the timeline every event twice.+ const result = await bookApi.confirmProposal(pendingBook.id, edited);setPendingBook(result.book);setPendingProposal(null);await loadBookDetail(result.book.id);@@ -298,11 +487,11 @@ function BookPageInner() {}};- const handleConfirmSpine = async (spine: Spine) => {+ const handleConfirmSpine = async (spine: Spine, autoCompile: boolean) => {if (!detail) return;setConfirmingSpine(true);try {- await bookApi.confirmSpine(detail.book.id, spine, true);+ await bookApi.confirmSpine(detail.book.id, spine, autoCompile);const refreshed = await loadBookDetail(detail.book.id);const firstPage = refreshed.pages[0] || null;setSelectedPageId(firstPage?.id || null);@@ -321,167 +510,284 @@ function BookPageInner() {if (!selectedBookId) return;setCompilingPageId(pageId);try {- await bookApi.compilePage(+ // Progress arrives on the book's stream; this call just awaits the+ // finished page. The engine coalesces it with any run already in+ // flight, so opening a page the worker reached first is free.+ const { page } = await bookApi.compilePage(selectedBookId,pageId,force,- handleBookOperationEvent,);+ mergePage(page);} catch (err) {const msg = err instanceof Error ? err.message : String(err);- notify(`Compile failed: ${msg}`, { tone: "error", durationMs: 8000 });+ notify(t("Compile failed: {{message}}", { message: msg }), {+ tone: "error",+ durationMs: 8000,+ });console.error("compilePage failed:", err);+ void hydratePage(pageId);} finally {setCompilingPageId((current) => (current === pageId ? null : current));- await loadBookDetail(selectedBookId);}},- [selectedBookId, loadBookDetail, handleBookOperationEvent],+ [selectedBookId, mergePage, hydratePage, t],);- const handleSelectPage = (pageId: string) => {- setSelectedPageId(pageId);- if (!detail) return;- const page = detail.pages.find((p) => p.id === pageId);- if (page && page.status !== "ready" && page.status !== "generating") {- void compilePage(pageId);+ const handleSelectPage = useCallback(+ (pageId: string) => {+ setSelectedPageId(pageId);+ if (!detail) return;++ const page = detail.pages.find((p) => p.id === pageId);+ if (!page) return;+ // Hydration is handled by the reader effect below, which fires for+ // every route into a page — including the one that opens the book.+ if (page.status !== "ready" && page.status !== "generating") {+ void compilePage(pageId);+ }+ },+ [detail, compilePage],+ );++ // A ?page= change on a book that is already open just moves the reader.+ const lastDeepLinkedPageId = useRef<string | null>(null);+ useEffect(() => {+ if (!requestedPageId || !requestedBookId) return;+ if (requestedBookId !== selectedBookId) return;+ if (requestedPageId === lastDeepLinkedPageId.current) return;+ lastDeepLinkedPageId.current = requestedPageId;+ if (requestedPageId !== selectedPageId) handleSelectPage(requestedPageId);+ // Consume the parameter so following the same link again re-triggers it.+ router.replace(`/book?book=${encodeURIComponent(requestedBookId)}`, {+ scroll: false,+ });+ }, [+ requestedPageId,+ requestedBookId,+ selectedBookId,+ selectedPageId,+ handleSelectPage,+ router,+ ]);++ // Opening a book lands on a page without going through `handleSelectPage`,+ // so hydrate and record the visit here too. The ref keeps recording a visit+ // from re-triggering itself when the updated progress comes back.+ const recordedVisitRef = useRef<string | null>(null);+ useEffect(() => {+ if (view !== "reader" || !selectedBookId || !selectedPage) return;+ if (needsHydration(selectedPage)) void hydratePage(selectedPage.id);++ const key = `${selectedBookId}:${selectedPage.id}`;+ if (recordedVisitRef.current === key) return;+ recordedVisitRef.current = key;+ const bookId = selectedBookId;+ void bookApi+ .markVisited(bookId, selectedPage.id)+ .then(({ progress }) =>+ setDetail((current) =>+ current && current.book.id === bookId+ ? { ...current, progress }+ : current,+ ),+ )+ .catch(() => {+ // Position tracking is best-effort.+ });+ }, [view, selectedBookId, selectedPage, hydratePage]);++ const handleUpdateBody = async (block: Block, body: string) => {+ if (!detail || !selectedPage) return;+ const pageId = selectedPage.id;+ try {+ await bookApi.updateBlock({+ book_id: detail.book.id,+ page_id: pageId,+ block_id: block.id,+ body,+ });+ await hydratePage(pageId);+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ notify(t("Could not save your edit: {{message}}", { message: msg }), {+ tone: "error",+ durationMs: 8000,+ });+ throw err;}};+ const handleToggleBookmark = async () =>+ guard("Bookmark", async () => {+ if (!detail || !selectedPage) return;+ const bookId = detail.book.id;+ const { progress } = await bookApi.toggleBookmark(+ bookId,+ selectedPage.id,+ );+ setDetail((current) =>+ current && current.book.id === bookId+ ? { ...current, progress }+ : current,+ );+ });+const handleRegenerateBlock = async (block: Block) => {if (!detail || !selectedPage) return;+ const pageId = selectedPage.id;try {- await bookApi.regenerateBlock(- detail.book.id,- selectedPage.id,- block.id,- undefined,- handleBookOperationEvent,- );+ await bookApi.regenerateBlock(detail.book.id, pageId, block.id);} catch (err) {const msg = err instanceof Error ? err.message : String(err);- notify(`Regenerate block failed: ${msg}`, {+ notify(t("Regenerate block failed: {{message}}", { message: msg }), {tone: "error",durationMs: 8000,});console.error("regenerateBlock failed:", err);} finally {- await loadBookDetail(detail.book.id);+ await hydratePage(pageId);}};- const handleDeleteBlock = async (block: Block) => {- if (!detail || !selectedPage) return;- if (!confirm(t("Delete this {{type}} block?", { type: block.type })))- return;- await bookApi.deleteBlock(detail.book.id, selectedPage.id, block.id);- await loadBookDetail(detail.book.id);- };+ const handleDeleteBlock = async (block: Block) =>+ guard("Delete block", async () => {+ if (!detail || !selectedPage) return;+ await bookApi.deleteBlock(detail.book.id, selectedPage.id, block.id);+ await hydratePage(selectedPage.id);+ });- const handleMoveBlock = async (block: Block, direction: "up" | "down") => {- if (!detail || !selectedPage) return;- const idx = selectedPage.blocks.findIndex((b) => b.id === block.id);- if (idx < 0) return;- const newPos = direction === "up" ? idx - 1 : idx + 1;- if (newPos < 0 || newPos >= selectedPage.blocks.length) return;- await bookApi.moveBlock(detail.book.id, selectedPage.id, block.id, newPos);- await loadBookDetail(detail.book.id);- };+ const handleMoveBlock = async (block: Block, direction: "up" | "down") =>+ guard("Move block", async () => {+ if (!detail || !selectedPage) return;+ const idx = selectedPage.blocks.findIndex((b) => b.id === block.id);+ if (idx < 0) return;+ const newPos = direction === "up" ? idx - 1 : idx + 1;+ if (newPos < 0 || newPos >= selectedPage.blocks.length) return;+ await bookApi.moveBlock(+ detail.book.id,+ selectedPage.id,+ block.id,+ newPos,+ );+ await hydratePage(selectedPage.id);+ });- const handleChangeBlockType = async (block: Block, newType: BlockType) => {- if (!detail || !selectedPage) return;- await bookApi.changeBlockType({- book_id: detail.book.id,- page_id: selectedPage.id,- block_id: block.id,- new_type: newType,+ const handleChangeBlockType = async (block: Block, newType: BlockType) =>+ guard("Change block type", async () => {+ if (!detail || !selectedPage) return;+ await bookApi.changeBlockType({+ book_id: detail.book.id,+ page_id: selectedPage.id,+ block_id: block.id,+ new_type: newType,+ });+ await hydratePage(selectedPage.id);});- await loadBookDetail(detail.book.id);- };- const handleInsertBlock = async (block_type: BlockType) => {- if (!detail || !selectedPage) return;- await bookApi.insertBlock({- book_id: detail.book.id,- page_id: selectedPage.id,- block_type,+ const handleInsertBlock = async (block_type: BlockType) =>+ guard("Insert block", async () => {+ if (!detail || !selectedPage) return;+ await bookApi.insertBlock({+ book_id: detail.book.id,+ page_id: selectedPage.id,+ block_type,+ });+ await hydratePage(selectedPage.id);+ });++ const handleDeepDive = async (topic: string, blockId: string) =>+ guard("Deep dive", async () => {+ if (!detail || !selectedPage) return;+ setPendingDeepDiveTopic(topic);+ try {+ const result = await bookApi.deepDive({+ book_id: detail.book.id,+ parent_page_id: selectedPage.id,+ topic,+ block_id: blockId,+ });+ // A deep dive adds a page, so the chapter list itself changed.+ const refreshed = await loadBookDetail(detail.book.id);+ const newPage = refreshed.pages.find((p) => p.id === result.page.id);+ if (newPage) {+ setSelectedPageId(newPage.id);+ mergePage(result.page);+ }+ } finally {+ setPendingDeepDiveTopic(null);+ }+ });++ const handleQuizAttempt = async (block: Block, args: QuizAttemptArgs) =>+ guard("Record answer", async () => {+ if (!detail || !selectedPage) return;+ const bookId = detail.book.id;+ const { progress } = await bookApi.recordQuizAttempt({+ book_id: bookId,+ page_id: selectedPage.id,+ block_id: block.id,+ question_id: args.questionId,+ user_answer: args.userAnswer,+ is_correct: args.isCorrect,+ });+ setDetail((current) =>+ current && current.book.id === bookId+ ? { ...current, progress }+ : current,+ );});- await loadBookDetail(detail.book.id);- };- const handleDeepDive = async (topic: string, blockId: string) => {+ /**+ * Add a remediation callout + explanation + easier quiz for a topic.+ *+ * Explicitly requested, never automatic. This grows the page by three+ * generated blocks, and having that happen unannounced under the reader —+ * once per wrong click, with nothing stopping a second round — was both+ * startling and expensive.+ */+ const handleRequestSupplement = async (block: Block) => {if (!detail || !selectedPage) return;- setPendingDeepDiveTopic(topic);+ const pageId = selectedPage.id;+ const topic =+ (block.params?.topic as string | undefined) || selectedPage.title || "";+ setSupplementingBlockId(block.id);try {- const result = await bookApi.deepDive({- book_id: detail.book.id,- parent_page_id: selectedPage.id,- topic,- block_id: blockId,+ await bookApi.supplement(detail.book.id, pageId, topic);+ await hydratePage(pageId);+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ notify(t("Could not add extra practice: {{message}}", { message: msg }), {+ tone: "error",+ durationMs: 8000,});- const refreshed = await loadBookDetail(detail.book.id);- const newPage = refreshed.pages.find((p) => p.id === result.page.id);- if (newPage) {- setSelectedPageId(newPage.id);- }} finally {- setPendingDeepDiveTopic(null);+ setSupplementingBlockId(null);}};- const handleQuizAttempt = async (- block: Block,- args: { questionId?: string; userAnswer?: string; isCorrect: boolean },- ) => {- if (!detail || !selectedPage) return;- await bookApi.recordQuizAttempt({- book_id: detail.book.id,- page_id: selectedPage.id,- block_id: block.id,- question_id: args.questionId,- user_answer: args.userAnswer,- is_correct: args.isCorrect,+ const handlePageChatSession = async (sessionId: string) =>+ guard("Link chat session", async () => {+ if (!detail || !selectedPage || !sessionId) return;+ const existing =+ detail.book.metadata?.page_chat_sessions?.[selectedPage.id];+ if (existing === sessionId) return;+ const result = await bookApi.setPageChatSession(+ detail.book.id,+ selectedPage.id,+ sessionId,+ );+ setDetail((current) =>+ current && current.book.id === result.book.id+ ? { ...current, book: result.book }+ : current,+ );});- if (!args.isCorrect) {- const topic =- (block.params?.topic as string | undefined) ||- selectedPage.title ||- "this topic";- try {- await bookApi.supplement(detail.book.id, selectedPage.id, topic);- } catch {- // best-effort- }- await loadBookDetail(detail.book.id);- }- };-- const handlePageChatSession = async (sessionId: string) => {- if (!detail || !selectedPage || !sessionId) return;- const existing =- detail.book.metadata?.page_chat_sessions?.[selectedPage.id];- if (existing === sessionId) return;- const result = await bookApi.setPageChatSession(- detail.book.id,- selectedPage.id,- sessionId,- );- setDetail((current) =>- current && current.book.id === result.book.id- ? { ...current, book: result.book }- : current,- );- };// ── Render ─────────────────────────────────────────────────────────return (- <div className="flex h-screen w-full">- {toast && (- <div className="fixed top-4 right-4 z-50 rounded-lg bg-red-500/90 px-4 py-2 text-sm text-white shadow-lg">- {toast}- </div>- )}+ <div className="flex h-full w-full">{view !== "list" && (<BookSidebarbook={detail?.book || pendingBook || null}@@ -491,6 +797,8 @@ function BookPageInner() {onSelectPage={handleSelectPage}onRebuild={detail ? () => void handleRebuildBook() : undefined}rebuilding={rebuildingBook}+ visitedPageIds={detail?.progress.visited_page_ids}+ bookmarkedPageIds={detail?.progress.bookmarked_page_ids}/>)}@@ -522,6 +830,7 @@ function BookPageInner() {</div>)}<BookCreator+ book={pendingBook}onCreate={handleCreate}loading={creating}proposal={pendingProposal}@@ -535,50 +844,83 @@ function BookPageInner() {<div className="flex h-full flex-col overflow-hidden"><div className="flex-1 overflow-hidden"><SpineEditor+ key={`${detail.spine.book_id}:${detail.spine.version}`}spine={detail.spine}onConfirm={handleConfirmSpine}loading={confirmingSpine}+ depth={detail.book.depth}/></div></div>)}{view === "reader" && (- <>+ // Column layout so banners push the reader down instead of+ // overflowing it — `PageReader` fills whatever height is left.+ <div className="flex h-full flex-col overflow-hidden">+ <BookPausedBanner+ book={detail?.book || null}+ onResume={() => void handleResumeBook()}+ resuming={resumingBook}+ /><BookHealthBannerbookId={selectedBookId}refreshKey={detail?.book.updated_at}+ explorationFailed={!!detail?.book.metadata?.exploration_failed}onRecompile={(pageId) => {setSelectedPageId(pageId);void compilePage(pageId, true);}}/>- <PageReader- page={selectedPage}- bookId={detail?.book.id}- bookLanguage={detail?.book.language}- loading={- !!compilingPageId && compilingPageId === selectedPage?.id- }- onRegenerateBlock={(block) => void handleRegenerateBlock(block)}- onDeleteBlock={(block) => void handleDeleteBlock(block)}- onMoveBlock={(block, dir) => void handleMoveBlock(block, dir)}- onChangeBlockType={(block, t) =>- void handleChangeBlockType(block, t)- }- onInsertBlock={(t) => handleInsertBlock(t)}- onDeepDive={(topic, blockId) => handleDeepDive(topic, blockId)}- onQuizAttempt={(block, args) =>- void handleQuizAttempt(block, args)- }- pendingDeepDiveTopic={pendingDeepDiveTopic}- onRecompile={- selectedPage- ? () => void compilePage(selectedPage.id, true)- : undefined- }- />- </>+ <div className="min-h-0 flex-1">+ <PageReader+ page={selectedPage}+ bookId={detail?.book.id}+ bookLanguage={detail?.book.language}+ loading={+ !!compilingPageId && compilingPageId === selectedPage?.id+ }+ onRegenerateBlock={(block) =>+ void handleRegenerateBlock(block)+ }+ onDeleteBlock={(block) => void handleDeleteBlock(block)}+ onMoveBlock={(block, dir) => void handleMoveBlock(block, dir)}+ onChangeBlockType={(block, t) =>+ void handleChangeBlockType(block, t)+ }+ onInsertBlock={(t) => handleInsertBlock(t)}+ onDeepDive={(topic, blockId) =>+ handleDeepDive(topic, blockId)+ }+ onOpenPage={(pageId) => handleSelectPage(pageId)}+ onQuizAttempt={(block, args) =>+ void handleQuizAttempt(block, args)+ }+ onRequestSupplement={(block) =>+ void handleRequestSupplement(block)+ }+ supplementingBlockId={supplementingBlockId}+ onUpdateBody={handleUpdateBody}+ attempts={detail?.progress.quiz_attempts}+ previousPage={pageNeighbours.previous}+ nextPage={pageNeighbours.next}+ onNavigate={handleSelectPage}+ bookmarked={+ !!selectedPage &&+ !!detail?.progress.bookmarked_page_ids.includes(+ selectedPage.id,+ )+ }+ onToggleBookmark={() => void handleToggleBookmark()}+ pendingDeepDiveTopic={pendingDeepDiveTopic}+ onRecompile={+ selectedPage+ ? () => void compilePage(selectedPage.id, true)+ : undefined+ }+ />+ </div>+ </div>)}{view === "spine" && !detail?.spine && (diff --git a/web/app/(workspace)/home/[[...sessionId]]/page.tsx b/web/app/(workspace)/home/[[...sessionId]]/page.tsxindex 7b51fb560..8ad55063b 100644--- a/web/app/(workspace)/home/[[...sessionId]]/page.tsx+++ b/web/app/(workspace)/home/[[...sessionId]]/page.tsx@@ -39,6 +39,7 @@ import { ChatMessageList } from "@/components/chat/home/ChatMessages";import { TurnNavigator } from "@/components/chat/home/TurnNavigator";import SessionLoadingView from "@/components/chat/home/SessionLoadingView";import StarterSuggestions from "@/components/chat/home/StarterSuggestions";+import MasteryPathStrip from "@/components/chat/home/MasteryPathStrip";// Imported eagerly so the drawer shell is always mounted off-screen —// clicking a chip becomes a single CSS class flip, no chunk fetch + double// render. The heavy renderers inside still load lazily.@@ -70,6 +71,7 @@ import {readFileAsDataUrl,} from "@/lib/file-attachments";import { classifyFile, isSvgFilename } from "@/lib/doc-attachments";+import { readChatLaunchIntent } from "@/lib/chat-launch-intent";import { useAttachmentLimits } from "@/lib/attachment-limits";import { useChatAutoScroll } from "@/hooks/useChatAutoScroll";import { useMeasuredHeight } from "@/hooks/useMeasuredHeight";@@ -1148,17 +1150,16 @@ export default function ChatPage() {setCapabilityConfigs(loadCapabilityPlaygroundConfigs());}, []);- /* URL query params (capability, tool, persistent mastery path) */+ /* Composer setup requested by the URL that opened this page (capability,+ tools, persistent mastery path). Runs once: from here on the composer is+ the user's to change. */useEffect(() => {if (typeof window === "undefined") return;- const p = new URLSearchParams(window.location.search);- const qc = p.get("capability");- const qt = p.getAll("tool");- const masteryPathId = p.get("mastery_path_id")?.trim();- if (masteryPathId) setMasteryPathId(masteryPathId);- if (qc !== null) handleSelectCapability(qc || "");- else if (qt.length) {- const valid = qt.filter((t): t is ToolName =>+ const intent = readChatLaunchIntent(window.location.search);+ if (intent.masteryPathId) setMasteryPathId(intent.masteryPathId);+ if (intent.capability !== null) handleSelectCapability(intent.capability);+ else if (intent.tools.length) {+ const valid = intent.tools.filter((t): t is ToolName =>ALL_TOOLS.some((d) => d.name === t),);if (valid.length) setTools(Array.from(new Set(valid)));@@ -2074,6 +2075,14 @@ export default function ChatPage() {</div>)}+ {/* Anchors the conversation to the path it is advancing. Only when+ the mastery capability is actually driving this turn — a stale+ path id on a plain chat would be a lie. */}+ {state.activeCapability === "mastery_path" &&+ state.masteryPathId && (+ <MasteryPathStrip pathId={state.masteryPathId} />+ )}+<ChatComposercomposerRef={composerRef}capMenuRef={capMenuRef}diff --git a/web/components/chat/home/MasteryPathStrip.tsx b/web/components/chat/home/MasteryPathStrip.tsxnew file mode 100644index 000000000..0920e1bb4--- /dev/null+++ b/web/components/chat/home/MasteryPathStrip.tsx@@ -0,0 +1,85 @@+"use client";++import { useEffect, useState } from "react";+import Link from "next/link";+import { GraduationCap } from "lucide-react";+import { useTranslation } from "react-i18next";++import { fetchMasteryMap, type MasteryMapResult } from "@/lib/learning-api";+import { useMasteryPathActivity } from "@/hooks/useMasteryPathActivity";++/**+ * What this conversation is working on, above the composer.+ *+ * A mastery conversation is bound to a path that outlives it, and until now+ * nothing in the chat said so — the learner arrived from the dashboard to an+ * empty composer with no sign of which path, how far along, or what is next.+ * This is that missing anchor. It reads the same event feed as the dashboard,+ * so the counts tick up as the tutor grades, without the learner switching+ * screens to find out whether an answer landed.+ */+const ACTION_LABEL: Record<string, { cn: string; en: string }> = {+ probe: { cn: "先探查", en: "probing first" },+ practice: { cn: "练到达标", en: "practising to the gate" },+ assess: { cn: "用自己的话解释", en: "explaining it back" },+ review: { cn: "到期复习", en: "due for review" },+ answer_pending: { cn: "等你作答", en: "awaiting your answer" },+ complete: { cn: "已全部掌握 🎉", en: "all mastered 🎉" },+};++export default function MasteryPathStrip({ pathId }: { pathId: string }) {+ const { i18n } = useTranslation();+ const zh = !!i18n.language?.toLowerCase().startsWith("zh");+ const tr = (cn: string, en: string) => (zh ? cn : en);+ const { revision } = useMasteryPathActivity(pathId);+ const [result, setResult] = useState<MasteryMapResult | null>(null);++ useEffect(() => {+ const controller = new AbortController();+ fetchMasteryMap(pathId, { signal: controller.signal })+ .then(setResult)+ .catch(() => {+ if (!controller.signal.aborted) setResult(null);+ });+ return () => controller.abort();+ }, [pathId, revision]);++ // A path with no objectives yet is one the tutor is about to build; there is+ // nothing to anchor to, and an empty "0/0" would read as broken.+ if (!result || result.map.counts.total === 0) return null;++ const { map, next } = result;+ const pct = Math.round((map.counts.mastered / map.counts.total) * 100);+ const action = ACTION_LABEL[next.action];++ return (+ <div className="mx-auto mb-2 flex w-full max-w-[760px] items-center gap-2.5 px-1 text-xs text-[var(--muted-foreground)]">+ <GraduationCap className="h-3.5 w-3.5 shrink-0" />+ <span className="shrink-0 font-medium text-[var(--foreground)]">+ {map.modules[0]?.name || tr("精通之路", "Mastery Path")}+ </span>+ <span className="h-1 w-16 shrink-0 overflow-hidden rounded-full bg-[var(--accent)]">+ <span+ className="block h-full bg-green-500 transition-all"+ style={{ width: `${pct}%` }}+ />+ </span>+ <span className="shrink-0">+ {map.counts.mastered}/{map.counts.total}+ </span>+ <span className="min-w-0 flex-1 truncate">+ {next.action === "complete"+ ? tr(action.cn, action.en)+ : `${tr("正在攻", "On")} ${next.knowledge_point_name}${+ action ? tr(` · ${action.cn}`, ` · ${action.en}`) : ""+ }`}+ </span>+ <Link+ href="/space/learning"+ className="shrink-0 text-[var(--primary)] hover:underline"+ >+ {tr("查看地图", "Map")}+ </Link>+ </div>+ );+}diff --git a/web/components/chat/home/ModelSelector.tsx b/web/components/chat/home/ModelSelector.tsxindex ed1828ee0..44e651846 100644--- a/web/components/chat/home/ModelSelector.tsx+++ b/web/components/chat/home/ModelSelector.tsx@@ -162,7 +162,8 @@ export default function ModelSelector({systemDefaultDetail || t("Use the active default model from Settings");const canRefresh = error && Boolean(onRefresh);const disabled =- loading || (!canRefresh && (error || (options.length === 0 && !allowSystemDefault)));+ loading ||+ (!canRefresh && (error || (options.length === 0 && !allowSystemDefault)));const label = loading? t("Loading models"): errordiff --git a/web/components/chat/home/StarterSuggestions.tsx b/web/components/chat/home/StarterSuggestions.tsxindex 0ea339107..11677d56d 100644--- a/web/components/chat/home/StarterSuggestions.tsx+++ b/web/components/chat/home/StarterSuggestions.tsx@@ -88,10 +88,13 @@ export default function StarterSuggestions({const load = useCallback(async (signal?: AbortSignal): Promise<SuggestionPayload | null> => {try {- const response = await apiFetch(apiUrl("/api/v1/dashboard/suggestions"), {- signal,- cache: "no-store",- });+ const response = await apiFetch(+ apiUrl("/api/v1/dashboard/suggestions"),+ {+ signal,+ cache: "no-store",+ },+ );if (!response.ok) return null;return (await response.json()) as SuggestionPayload;} catch {diff --git a/web/components/knowledge/CreateKbModal.tsx b/web/components/knowledge/CreateKbModal.tsxindex 2c910c6a0..c08157036 100644--- a/web/components/knowledge/CreateKbModal.tsx+++ b/web/components/knowledge/CreateKbModal.tsx@@ -136,6 +136,7 @@ export default function CreateKbModal({name,onNameChange: setName,onError: setError,+ active: linkIsIma,});const firstLinkable = providers.find((p) => p.linkable)?.id;@@ -295,8 +296,10 @@ export default function CreateKbModal({} else if (linkIsIma) {await onConnectIma({name: trimmed,- clientId: imaConnection.clientId.trim(),- apiKey: imaConnection.apiKey.trim(),+ // Empty when the engine's account credentials are used — the server+ // resolves them and the KB stores no copy.+ clientId: imaConnection.submittedClientId,+ apiKey: imaConnection.submittedApiKey,knowledgeBaseId: imaConnection.knowledgeBaseId,});} else if (linkIsObsidian) {diff --git a/web/components/knowledge/EngineDetail.tsx b/web/components/knowledge/EngineDetail.tsxindex f2bc657c4..4964b5168 100644--- a/web/components/knowledge/EngineDetail.tsx+++ b/web/components/knowledge/EngineDetail.tsx@@ -30,17 +30,20 @@ import {getEnginePreflight,getGraphRagConfig,getLightRagConfig,+ getImaConfig,getLlamaIndexConfig,getPageIndexConfig,setEngineActiveModel,testGraphRagModelCompatibility,updateGraphRagConfig,+ updateImaConfig,updateLightRagConfig,updateLlamaIndexConfig,updatePageIndexConfig,type EnginePreflight,type GraphRagModelCompatibility,type GraphRagConfig,+ type ImaAccountConfig,type LightRagConfig,type LlamaIndexConfig,type ModelOptionsByKind,@@ -145,7 +148,7 @@ const ENGINE_PREREQUISITES: Record<string, string> = {"Local knowledge-graph retrieval. Needs the optional dependency installed; indexing is LLM-heavy. Requires an active chat model and embedding model.",lightrag:"Graph + vector retrieval with multimodal parsing. Needs the optional dependency installed; indexing is LLM-heavy. Requires active chat and embedding models; multimodal also needs a vision model.",- ima: "Connect each Tencent IMA knowledge base with its own Client ID and API key. Retrieval is read-only and loads bounded source text when IMA omits a matched snippet.",+ ima: "Hosted engine: the library lives in Tencent IMA and DeepTutor keeps no copy. Requires an IMA Client ID and API key; retrieval is read-only and loads bounded source text when IMA omits a matched snippet.",};function StatusBadge({ status }: { status: ProviderConnectionStatus }) {@@ -158,13 +161,6 @@ function StatusBadge({ status }: { status: ProviderConnectionStatus }) {</span>);}- if (status === "per_kb") {- return (- <span className="inline-flex items-center rounded-full bg-sky-100 px-2 py-0.5 text-[10.5px] font-medium text-sky-700 dark:bg-sky-950/30 dark:text-sky-300">- {t("Connect per knowledge base")}- </span>- );- }if (status === "needs_key") {return (<span className="inline-flex items-center rounded-full bg-amber-100 px-2 py-0.5 text-[10.5px] font-medium text-amber-700 dark:bg-amber-950/30 dark:text-amber-300">@@ -660,6 +656,135 @@ function PageIndexForm({);}+/* ------------------------- Tencent IMA credentials ------------------------ */++function ImaForm({+ onChanged,+ onError,+}: {+ onChanged: () => void;+ onError: (message: string) => void;+}) {+ const { t } = useTranslation();+ const [config, setConfig] = useState<ImaAccountConfig | null>(null);+ const [clientId, setClientId] = useState("");+ const [apiKey, setApiKey] = useState("");+ const [saving, setSaving] = useState(false);++ useEffect(() => {+ let cancelled = false;+ getImaConfig({ force: true })+ .then((cfg) => {+ if (cancelled) return;+ setConfig(cfg);+ setClientId(cfg.client_id || "");+ })+ .catch((err) =>+ onError(err instanceof Error ? err.message : String(err)),+ );+ return () => {+ cancelled = true;+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ const persist = async (payload: { client_id?: string; api_key?: string }) => {+ setSaving(true);+ try {+ const next = await updateImaConfig(payload);+ setConfig(next);+ setClientId(next.client_id || "");+ setApiKey("");+ onChanged();+ } catch (err) {+ onError(err instanceof Error ? err.message : String(err));+ } finally {+ setSaving(false);+ }+ };++ const keySet = config?.api_key_set ?? false;++ return (+ <div className="space-y-4 rounded-2xl border border-[var(--border)] p-4">+ <p className="text-[12px] leading-relaxed text-[var(--muted-foreground)]">+ {t(+ "One IMA account reaches every library in it, so this pair is shared by all your Tencent IMA knowledge bases. Connecting one then only asks which library to point at. A knowledge base can still carry its own credentials to reach a second account.",+ )}+ </p>++ <div>+ <label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">+ {t("Client ID")}+ </label>+ <input+ value={clientId}+ onChange={(e) => setClientId(e.target.value)}+ disabled={saving}+ autoComplete="off"+ placeholder={t("Enter your IMA Client ID")}+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 font-mono text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25 disabled:opacity-50"+ />+ </div>++ <div>+ <label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">+ {t("API key")}+ </label>+ <input+ type="password"+ value={apiKey}+ onChange={(e) => setApiKey(e.target.value)}+ disabled={saving}+ autoComplete="off"+ placeholder={+ keySet+ ? t("•••••••• (configured — leave blank to keep)")+ : t("Enter your IMA API key")+ }+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25 disabled:opacity-50"+ />+ {keySet && (+ <button+ type="button"+ onClick={() => void persist({ api_key: "" })}+ disabled={saving}+ className="mt-1.5 text-[11px] font-medium text-red-600 transition-colors hover:text-red-700 disabled:opacity-40 dark:text-red-400"+ >+ {t("Remove stored key")}+ </button>+ )}+ </div>++ <div className="flex items-center justify-between gap-2">+ <a+ href="https://ima.qq.com/agent-interface"+ target="_blank"+ rel="noreferrer"+ className="inline-flex items-center gap-1 text-[11.5px] text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"+ >+ {t("Get an API key")}+ <ExternalLink className="h-3 w-3" />+ </a>+ <button+ type="button"+ onClick={() =>+ void persist({+ client_id: clientId.trim(),+ ...(apiKey.trim() ? { api_key: apiKey.trim() } : {}),+ })+ }+ disabled={saving}+ className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3.5 py-1.5 text-[12.5px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40"+ >+ {saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}+ {t("Save changes")}+ </button>+ </div>+ </div>+ );+}+/* --------------------------- Shared form controls ------------------------- */function ResponseTypeSelect({@@ -1290,11 +1415,7 @@ function EnvRequirements({: "text-amber-600 dark:text-amber-400"}`}>- {report.ok- ? providerId === "ima"- ? t("Configured per knowledge base")- : t("Ready to use")- : t("Not ready")}+ {report.ok ? t("Ready to use") : t("Not ready")}</span>)}</div>@@ -1418,6 +1539,13 @@ export default function EngineDetail({</Section>)}+ {/* Tencent IMA credentials */}+ {provider.id === "ima" && (+ <Section label={t("Credentials")} icon={KeyRound}>+ <ImaForm onChanged={onChanged} onError={onError} />+ </Section>+ )}+{/* Models — in-place pickers for the kinds this engine needs */}<ModelsSection providerId={provider.id} onError={onError} />diff --git a/web/components/knowledge/ImaConnectionFields.tsx b/web/components/knowledge/ImaConnectionFields.tsxindex a4bc765ef..b9bf74a02 100644--- a/web/components/knowledge/ImaConnectionFields.tsx+++ b/web/components/knowledge/ImaConnectionFields.tsx@@ -15,8 +15,8 @@ export default function ImaConnectionFields({}) {const { t } = useTranslation();const loading = connection.lookup.status === "loading";- const credentialsReady =- connection.clientId.trim() && connection.apiKey.trim();+ const credentialsReady = connection.credentialsReady;+ const showFields = connection.useOwnCredentials;return (<div className="space-y-3">@@ -26,45 +26,81 @@ export default function ImaConnectionFields({)}</p>- <div className="grid gap-3 sm:grid-cols-2">- <div>- <label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">- {t("Client ID")}- </label>- <input- value={connection.clientId}- onChange={(event) => connection.setClientId(event.target.value)}- disabled={submitting}- autoComplete="off"- className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 font-mono text-[12.5px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25 disabled:opacity-50"- />- </div>- <div>- <label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">- {t("API key")}- </label>- <input- value={connection.apiKey}- onChange={(event) => connection.setApiKey(event.target.value)}+ {connection.accountConfigured && !showFields ? (+ <div className="flex items-start justify-between gap-3 rounded-lg border border-[var(--border)] bg-[var(--muted)]/30 px-3 py-2.5">+ <span className="flex items-start gap-1.5 text-[11.5px] leading-snug text-[var(--muted-foreground)]">+ <Check className="mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-600 dark:text-emerald-400" />+ {t(+ "Using the IMA credentials configured for this engine in the Knowledge Center.",+ )}+ </span>+ <button+ type="button"+ onClick={() => connection.setUseOwnCredentials(true)}disabled={submitting}- type="password"- autoComplete="off"- className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[12.5px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25 disabled:opacity-50"- />+ className="shrink-0 text-[11.5px] font-medium text-[var(--foreground)] underline underline-offset-2 disabled:opacity-40"+ >+ {t("Use other credentials")}+ </button></div>- </div>+ ) : (+ <>+ <div className="grid gap-3 sm:grid-cols-2">+ <div>+ <label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">+ {t("Client ID")}+ </label>+ <input+ value={connection.clientId}+ onChange={(event) => connection.setClientId(event.target.value)}+ disabled={submitting}+ autoComplete="off"+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 font-mono text-[12.5px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25 disabled:opacity-50"+ />+ </div>+ <div>+ <label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">+ {t("API key")}+ </label>+ <input+ value={connection.apiKey}+ onChange={(event) => connection.setApiKey(event.target.value)}+ disabled={submitting}+ type="password"+ autoComplete="off"+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[12.5px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25 disabled:opacity-50"+ />+ </div>+ </div>- <p className="text-[11px] text-[var(--muted-foreground)]">- {t("Create these credentials on the Tencent IMA agent interface.")}{" "}- <a- href="https://ima.qq.com/agent-interface"- target="_blank"- rel="noreferrer"- className="font-medium text-[var(--foreground)] underline underline-offset-2"- >- {t("Open IMA")}- </a>- </p>+ <p className="text-[11px] text-[var(--muted-foreground)]">+ {connection.accountConfigured ? (+ <button+ type="button"+ onClick={() => connection.setUseOwnCredentials(false)}+ disabled={submitting}+ className="font-medium text-[var(--foreground)] underline underline-offset-2 disabled:opacity-40"+ >+ {t("Use the engine's credentials instead")}+ </button>+ ) : (+ <>+ {t(+ "Set these once for the engine in the Knowledge Center to skip this step next time.",+ )}{" "}+ <a+ href="https://ima.qq.com/agent-interface"+ target="_blank"+ rel="noreferrer"+ className="font-medium text-[var(--foreground)] underline underline-offset-2"+ >+ {t("Open IMA")}+ </a>+ </>+ )}+ </p>+ </>+ )}<div className="flex flex-wrap gap-2"><ModeButton@@ -146,9 +182,7 @@ export default function ImaConnectionFields({disabled={submitting || loading}className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)] px-3 py-1.5 text-[11.5px] font-medium text-[var(--foreground)] disabled:opacity-40">- {loading && (- <Loader2 className="h-3.5 w-3.5 animate-spin" />- )}+ {loading && <Loader2 className="h-3.5 w-3.5 animate-spin" />}{t("Load more")}</button>)}diff --git a/web/components/knowledge/KnowledgeHome.tsx b/web/components/knowledge/KnowledgeHome.tsxindex ca837d6d9..43efc77d3 100644--- a/web/components/knowledge/KnowledgeHome.tsx+++ b/web/components/knowledge/KnowledgeHome.tsx@@ -58,13 +58,6 @@ function EngineStatusBadge({ status }: { status: ProviderConnectionStatus }) {</span>);}- if (status === "per_kb") {- return (- <span className="inline-flex items-center rounded-full bg-sky-100 px-1.5 py-0.5 text-[10px] font-medium text-sky-700 dark:bg-sky-950/30 dark:text-sky-300">- {t("Connect per knowledge base")}- </span>- );- }if (status === "needs_key") {return (<span className="inline-flex items-center rounded-full bg-amber-100 px-1.5 py-0.5 text-[10px] font-medium text-amber-700 dark:bg-amber-950/30 dark:text-amber-300">diff --git a/web/components/partners/PartnerComposer.tsx b/web/components/partners/PartnerComposer.tsxindex 9e13f3b8d..a90f63043 100644--- a/web/components/partners/PartnerComposer.tsx+++ b/web/components/partners/PartnerComposer.tsx@@ -107,10 +107,7 @@ export const PartnerComposer = memo(function PartnerComposer({useEffect(() => {if (disabled || streaming) return;- if (- !restoreFocusAfterSendRef.current &&- !restoreFocusOnReturnRef.current- ) {+ if (!restoreFocusAfterSendRef.current && !restoreFocusOnReturnRef.current) {return;}restoreFocusAfterSendRef.current = false;diff --git a/web/components/sidebar/BookRecent.tsx b/web/components/sidebar/BookRecent.tsxindex 6c373d04e..c7908c5e8 100644--- a/web/components/sidebar/BookRecent.tsx+++ b/web/components/sidebar/BookRecent.tsx@@ -3,18 +3,10 @@import Link from "next/link";import { useEffect, useState } from "react";import { useTranslation } from "react-i18next";-import { apiFetch, apiUrl } from "@/lib/api";+import { bookApi } from "@/lib/book-api";+import type { Book } from "@/lib/book-types";import { formatRelativeTime } from "@/lib/relative-time";-interface RecentBook {- id: string;- title: string;- status: string;- chapter_count: number;- page_count: number;- updated_at: number;-}-const STATUS_DOT: Record<string, string> = {ready: "bg-emerald-400",partial: "bg-amber-400",@@ -33,24 +25,18 @@ interface BookRecentProps {export function BookRecent({ collapsed = false, limit = 4 }: BookRecentProps) {const { i18n } = useTranslation();- const [books, setBooks] = useState<RecentBook[]>([]);+ const [books, setBooks] = useState<Book[]>([]);useEffect(() => {let cancelled = false;(async () => {try {- const res = await apiFetch(apiUrl("/api/v1/book/books"));- if (!res.ok) return;- const data = await res.json();- const items: RecentBook[] = Array.isArray(data?.books)- ? data.books- : [];- items.sort(- (a, b) => (Number(b.updated_at) || 0) - (Number(a.updated_at) || 0),- );+ const { books: items } = await bookApi.list();+ // `list_books` already returns newest-first (engine sorts by+ // updated_at desc), so this is presentation only.if (!cancelled) setBooks(items.slice(0, limit));} catch {- /* ignore */+ /* the sidebar is decoration; a failed fetch just shows nothing */}})();return () => {diff --git a/web/components/space/learning/ActivityTimeline.tsx b/web/components/space/learning/ActivityTimeline.tsxnew file mode 100644index 000000000..f633c4419--- /dev/null+++ b/web/components/space/learning/ActivityTimeline.tsx@@ -0,0 +1,118 @@+"use client";++import type { MasteryEvent } from "@/lib/learning-api";++import { formatRelative, type Translate } from "./format";++/**+ * What the tutor and the engine have actually done to this path, newest first.+ *+ * The engine commits an event for every state change, which until now nothing+ * read. Rendering them turns the path from a score into a record: when an+ * objective was posed, answered, graded, assessed, or rebuilt — and, because+ * the same feed drives the live refresh, the list grows while you watch.+ */+export function ActivityTimeline({+ events,+ objectiveNames,+ tr,+ zh,+}: {+ events: MasteryEvent[];+ /** objective id → display name, so the feed reads in the learner's terms. */+ objectiveNames: Record<string, string>;+ tr: Translate;+ zh: boolean;+}) {+ if (events.length === 0) {+ return (+ <p className="py-6 text-center text-xs text-[var(--muted-foreground)]">+ {tr("还没有活动记录。", "Nothing has happened on this path yet.")}+ </p>+ );+ }+ return (+ <ol className="space-y-1.5">+ {[...events].reverse().map((event) => (+ <li key={event.id} className="flex items-baseline gap-2 text-xs">+ <span+ className={`mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full ${dotClass(event)}`}+ />+ <span className="flex-1 text-[var(--foreground)]">+ {describe(event, objectiveNames, tr)}+ </span>+ <span className="shrink-0 text-[var(--muted-foreground)]">+ {formatRelative(event.created_at, zh)}+ </span>+ </li>+ ))}+ </ol>+ );+}++function objectiveName(+ event: MasteryEvent,+ names: Record<string, string>,+): string {+ const id = String(event.payload?.knowledge_point_id ?? "");+ return names[id] || id;+}++function describe(+ event: MasteryEvent,+ names: Record<string, string>,+ tr: Translate,+): string {+ const name = objectiveName(event, names);+ switch (event.event_type) {+ case "path.created":+ return tr("创建了这条精通之路", "Path created");+ case "path.built":+ case "path.modules_replaced": {+ const modules = Number(event.payload?.module_count ?? 0);+ const points = Number(event.payload?.knowledge_point_count ?? 0);+ return event.payload?.mode === "append"+ ? tr(+ `追加了 ${modules} 个模块、${points} 个知识点`,+ `Added ${modules} modules and ${points} objectives`,+ )+ : tr(+ `重建了路径:${modules} 个模块、${points} 个知识点`,+ `Rebuilt the path: ${modules} modules, ${points} objectives`,+ );+ }+ case "path.reset":+ return tr("重置了进度", "Progress reset");+ case "interaction.registered":+ return tr(`出了一道题:${name}`, `Posed a question on ${name}`);+ case "interaction.awaiting_input":+ return tr("等待你的回答", "Waiting for your answer");+ case "interaction.answered":+ return tr("收到你的回答", "Your answer was recorded");+ case "attempt.recorded":+ return event.payload?.is_correct+ ? tr(`${name} 答对了`, `Correct on ${name}`)+ : tr(`${name} 答错了`, `Missed ${name}`);+ case "interaction.graded":+ return tr("判分完成", "Graded");+ case "interaction.abandoned":+ return tr("跳过了待回答的题目", "Skipped the outstanding question");+ case "mastery.assessed":+ return event.payload?.passed+ ? tr(`${name} 的解释达标`, `Explanation accepted for ${name}`)+ : tr(`${name} 的解释还不够`, `Explanation not yet sufficient for ${name}`);+ case "path.saved":+ return tr("保存了路径状态", "Path state saved");+ default:+ return event.event_type;+ }+}++function dotClass(event: MasteryEvent): string {+ if (event.event_type === "attempt.recorded")+ return event.payload?.is_correct ? "bg-green-500" : "bg-red-500";+ if (event.event_type === "mastery.assessed")+ return event.payload?.passed ? "bg-green-500" : "bg-yellow-500";+ if (event.event_type.startsWith("path.")) return "bg-[var(--primary)]";+ return "bg-[var(--muted-foreground)]/50";+}diff --git a/web/components/space/learning/ObjectiveDetail.tsx b/web/components/space/learning/ObjectiveDetail.tsxnew file mode 100644index 000000000..01b1711de--- /dev/null+++ b/web/components/space/learning/ObjectiveDetail.tsx@@ -0,0 +1,165 @@+"use client";++import { Check, X } from "lucide-react";++import type { ObjectiveReport } from "@/lib/learning-api";++import { formatAbsolute, formatRelative, type Translate } from "./format";++/**+ * The evidence behind one objective.+ *+ * The map answers "am I through the gate"; this answers "why" — which+ * questions were asked, what the learner said, what the engine did with it,+ * and when it comes back for review. The gate itself is shown as a bar with+ * the threshold marked, because a hard gate is only legible if you can see how+ * far away it is.+ */+export function ObjectiveDetail({+ report,+ tr,+ zh,+}: {+ report: ObjectiveReport;+ tr: Translate;+ zh: boolean;+}) {+ const qualitative = report.gate === "qualitative";+ return (+ <div className="mt-1 mb-2 ml-5 space-y-3 border-l border-[var(--border)] pl-3">+ <GateBar report={report} tr={tr} />++ {report.review && (+ <Row label={tr("间隔复习", "Spaced review")}>+ {report.review.due_at+ ? tr(+ `${formatRelative(report.review.due_at, zh)}复习 · ${formatAbsolute(report.review.due_at, zh)}`,+ `Due ${formatRelative(report.review.due_at, zh)} · ${formatAbsolute(report.review.due_at, zh)}`,+ )+ : tr("未排期", "Not scheduled")}+ <span className="ml-2 text-[var(--muted-foreground)]">+ {tr(+ `第 ${report.review.interval_index + 1} 档 · 连对 ${report.review.consecutive_correct}`,+ `interval ${report.review.interval_index + 1} · ${report.review.consecutive_correct} in a row`,+ )}+ </span>+ </Row>+ )}++ {qualitative && report.explanation && (+ <Row label={tr("你的解释", "Your explanation")}>+ <span className="italic">{report.explanation}</span>+ </Row>+ )}++ {report.attempts.length > 0 && (+ <div>+ <div className="text-xs text-[var(--muted-foreground)]">+ {tr(+ `作答记录(${report.correct_count}/${report.attempts.length} 正确)`,+ `Attempts (${report.correct_count}/${report.attempts.length} correct)`,+ )}+ </div>+ <ul className="mt-1 space-y-1.5">+ {[...report.attempts].reverse().map((attempt, index) => (+ <li+ key={`${attempt.question_id}-${index}`}+ className="flex gap-2 text-xs"+ >+ {attempt.is_correct ? (+ <Check className="mt-0.5 h-3 w-3 shrink-0 text-green-500" />+ ) : (+ <X className="mt-0.5 h-3 w-3 shrink-0 text-red-500" />+ )}+ <div className="min-w-0">+ <div className="text-[var(--foreground)]">+ {attempt.prompt || tr("(题面已不可用)", "(prompt unavailable)")}+ </div>+ <div className="text-[var(--muted-foreground)]">+ {tr("你答:", "You said: ")}+ {attempt.answer || tr("(空)", "(blank)")}+ <span className="ml-2">{formatRelative(attempt.at, zh)}</span>+ </div>+ </div>+ </li>+ ))}+ </ul>+ </div>+ )}++ {report.errors.length > 0 && (+ <Row label={tr("错因", "Error diagnosis")}>+ {report.errors.map((record) => (+ <span key={record.id} className="mr-2">+ {tr(ERROR_TYPE_CN[record.error_type] ?? record.error_type, record.error_type)}+ {record.retries > 0 &&+ tr(` · 重试 ${record.retries} 次`, ` · ${record.retries} retries`)}+ {record.status === "graduated" && tr(" · 已订正", " · cleared")}+ </span>+ ))}+ </Row>+ )}++ {report.attempts.length === 0 && !report.explanation && (+ <p className="text-xs text-[var(--muted-foreground)]">+ {tr(+ "还没有作答记录。在对话里继续辅导后,这里会出现题目、你的回答和判分。",+ "No attempts yet. Once you tutor this in Chat, the questions, your answers, and the grading show up here.",+ )}+ </p>+ )}+ </div>+ );+}++/** Mastery against the gate it has to clear. */+function GateBar({ report, tr }: { report: ObjectiveReport; tr: Translate }) {+ const pct = Math.round(report.mastery * 100);+ const thresholdPct = Math.round(report.threshold * 100);+ return (+ <div>+ <div className="flex items-baseline justify-between text-xs">+ <span className="text-[var(--muted-foreground)]">+ {report.gate === "qualitative"+ ? tr("定性门槛:用自己的话讲清楚", "Qualitative gate: explain it in your own words")+ : tr(`定量门槛:${thresholdPct}%`, `Quantitative gate: ${thresholdPct}%`)}+ </span>+ <span+ className={+ report.mastered ? "text-green-500" : "text-[var(--muted-foreground)]"+ }+ >+ {pct}%+ </span>+ </div>+ <div className="relative mt-1 h-1.5 w-full overflow-hidden rounded-full bg-[var(--accent)]">+ <div+ className={`h-full ${report.mastered ? "bg-green-500" : "bg-yellow-500"}`}+ style={{ width: `${pct}%` }}+ />+ {report.gate === "quantitative" && (+ <div+ className="absolute inset-y-0 w-px bg-[var(--foreground)]/40"+ style={{ left: `${thresholdPct}%` }}+ />+ )}+ </div>+ </div>+ );+}++function Row({ label, children }: { label: string; children: React.ReactNode }) {+ return (+ <div className="text-xs">+ <div className="text-[var(--muted-foreground)]">{label}</div>+ <div className="mt-0.5 text-[var(--foreground)]">{children}</div>+ </div>+ );+}++const ERROR_TYPE_CN: Record<string, string> = {+ structural: "知识结构性",+ deviation: "理解偏差",+ application: "应用错误",+ metacognitive: "元认知",+};diff --git a/web/components/space/learning/PathMap.tsx b/web/components/space/learning/PathMap.tsxnew file mode 100644index 000000000..a4e07e7ad--- /dev/null+++ b/web/components/space/learning/PathMap.tsx@@ -0,0 +1,142 @@+"use client";++import { useCallback, useEffect, useState } from "react";+import {+ ChevronDown,+ ChevronRight,+ Circle,+ CircleCheck,+ CircleDot,+ Loader2,+} from "lucide-react";++import {+ fetchObjectiveReport,+ type MasteryMap,+ type ObjectiveReport,+ type ObjectiveStatus,+} from "@/lib/learning-api";++import { ObjectiveDetail } from "./ObjectiveDetail";+import type { Translate } from "./format";++export const STATUS_META: Record<+ ObjectiveStatus,+ { cn: string; en: string; className: string }+> = {+ mastered: { cn: "已掌握", en: "Mastered", className: "text-green-500" },+ learning: { cn: "学习中", en: "Learning", className: "text-yellow-500" },+ new: {+ cn: "未开始",+ en: "Not started",+ className: "text-[var(--muted-foreground)]",+ },+};++/**+ * The module → objective map, with each objective openable.+ *+ * Rows stay as terse as before; the evidence behind one only loads when it is+ * opened, so a large path costs a single map request until the learner asks a+ * question of it. `revision` re-fetches whatever is open, which is how an+ * expanded objective keeps up with a live tutoring session.+ */+export function PathMap({+ pathId,+ map,+ revision,+ tr,+ zh,+}: {+ pathId: string;+ map: MasteryMap;+ revision: number;+ tr: Translate;+ zh: boolean;+}) {+ const [openId, setOpenId] = useState<string | null>(null);+ const [report, setReport] = useState<ObjectiveReport | null>(null);+ // Loading is derived rather than tracked: a report that does not match the+ // open objective is, by definition, still on its way.+ const loaded = openId !== null && report?.id === openId;++ useEffect(() => {+ if (!openId) return;+ const controller = new AbortController();+ fetchObjectiveReport(pathId, openId, { signal: controller.signal })+ .then(setReport)+ .catch(() => {+ if (!controller.signal.aborted) setReport(null);+ });+ return () => controller.abort();+ }, [pathId, openId, revision]);++ const toggle = useCallback((id: string) => {+ setOpenId((current) => (current === id ? null : id));+ setReport(null);+ }, []);++ return (+ <div className="space-y-4">+ {map.modules.map((module) => (+ <div key={module.id}>+ <div className="flex items-center justify-between">+ <h3 className="text-sm font-medium text-[var(--foreground)]">+ {module.name}+ </h3>+ <span className="text-xs text-[var(--muted-foreground)]">+ {module.mastered}/{module.total}+ </span>+ </div>+ <div className="mt-1.5">+ {module.knowledge_points.map((kp) => {+ const open = openId === kp.id;+ return (+ <div key={kp.id}>+ <button+ onClick={() => toggle(kp.id)}+ aria-expanded={open}+ className="flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-sm hover:bg-[var(--accent)] cursor-pointer"+ >+ {open ? (+ <ChevronDown className="h-3 w-3 shrink-0 text-[var(--muted-foreground)]" />+ ) : (+ <ChevronRight className="h-3 w-3 shrink-0 text-[var(--muted-foreground)]" />+ )}+ <StatusIcon status={kp.status} />+ <span className="flex-1 truncate text-[var(--foreground)]">+ {kp.name}+ </span>+ <span className="text-[10px] uppercase tracking-wide text-[var(--muted-foreground)]">+ {kp.type}+ </span>+ <span+ className={`text-xs ${STATUS_META[kp.status].className}`}+ >+ {zh ? STATUS_META[kp.status].cn : STATUS_META[kp.status].en}+ </span>+ </button>+ {open &&+ (loaded && report ? (+ <ObjectiveDetail report={report} tr={tr} zh={zh} />+ ) : (+ <div className="ml-8 py-2 text-[var(--muted-foreground)]">+ <Loader2 className="h-3 w-3 animate-spin" />+ </div>+ ))}+ </div>+ );+ })}+ </div>+ </div>+ ))}+ </div>+ );+}++function StatusIcon({ status }: { status: ObjectiveStatus }) {+ const cls = `w-3 h-3 shrink-0 ${STATUS_META[status].className}`;+ if (status === "mastered") return <CircleCheck className={cls} />;+ if (status === "learning") return <CircleDot className={cls} />;+ return <Circle className={cls} />;+}diff --git a/web/components/space/learning/format.ts b/web/components/space/learning/format.tsnew file mode 100644index 000000000..7a0d5fa4f--- /dev/null+++ b/web/components/space/learning/format.ts@@ -0,0 +1,40 @@+/** Shared presentation helpers for the Mastery Path dashboard. */++export type Translate = (cn: string, en: string) => string;++const MINUTE = 60;+const HOUR = 60 * MINUTE;+const DAY = 24 * HOUR;++/**+ * "3 分钟前" / "in 2 days" — engine timestamps are epoch seconds and can point+ * either way (an attempt happened, a review is due).+ */+export function formatRelative(epochSeconds: number, zh: boolean): string {+ const deltaSeconds = epochSeconds - Date.now() / 1000;+ const past = deltaSeconds < 0;+ const abs = Math.abs(deltaSeconds);++ const [value, unit]: [number, Intl.RelativeTimeFormatUnit] =+ abs < MINUTE+ ? [Math.round(abs), "second"]+ : abs < HOUR+ ? [Math.round(abs / MINUTE), "minute"]+ : abs < DAY+ ? [Math.round(abs / HOUR), "hour"]+ : [Math.round(abs / DAY), "day"];++ return new Intl.RelativeTimeFormat(zh ? "zh-CN" : "en", {+ numeric: "auto",+ }).format(past ? -value : value, unit);+}++/** Calendar form, for when "in 3 days" is not precise enough. */+export function formatAbsolute(epochSeconds: number, zh: boolean): string {+ return new Date(epochSeconds * 1000).toLocaleString(zh ? "zh-CN" : "en", {+ month: "short",+ day: "numeric",+ hour: "2-digit",+ minute: "2-digit",+ });+}diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsxindex e89450aa2..688d30e67 100644--- a/web/context/UnifiedChatContext.tsx+++ b/web/context/UnifiedChatContext.tsx@@ -202,7 +202,10 @@ type Action =| { type: "SET_CAPABILITY"; cap: string | null }| { type: "SET_KB"; kbs: string[] }| { type: "SET_LLM_SELECTION"; selection: LLMSelection | null }- | { type: "SET_MASTERY_PATH_ID"; masteryPathId: string | null }+ // ``key`` targets a specific conversation — a backend push belongs to the+ // session that produced it, which may no longer be the selected one. The+ // composer omits it and means "the one on screen".+ | { type: "SET_MASTERY_PATH_ID"; masteryPathId: string | null; key?: string }| { type: "SET_PERSONA_SELECTION"; persona: string }| { type: "SET_LANGUAGE"; lang: string }| {@@ -243,6 +246,7 @@ type Action =}| { type: "DELETE_TURN"; key: string; messageId: number }| { type: "NEW_SESSION"; key: string }+ | { type: "ENSURE_DRAFT_SESSION"; key: string }| {type: "SET_SELECTED_BRANCH";key: string;@@ -307,6 +311,24 @@ function updateSelectedSession(};}+/** Add an empty session under ``key`` and make it the selected one. */+function selectFreshDraft(state: ProviderState, key: string): ProviderState {+ const MAX_CACHED_SESSIONS = 20;+ const nextSessions = {+ ...state.sessions,+ [key]: createSessionEntry(key),+ };+ const keys = Object.keys(nextSessions);+ if (keys.length > MAX_CACHED_SESSIONS) {+ const evictable = keys+ .filter((k) => k !== key && nextSessions[k].status !== "running")+ .sort((a, b) => nextSessions[a].updatedAt - nextSessions[b].updatedAt);+ const toRemove = evictable.slice(0, keys.length - MAX_CACHED_SESSIONS);+ for (const k of toRemove) delete nextSessions[k];+ }+ return { ...state, selectedKey: key, sessions: nextSessions };+}+function isSameTurnEvent(a: StreamEvent, b: StreamEvent): boolean {const aSeq = Number(a.seq || 0);const bSeq = Number(b.seq || 0);@@ -338,11 +360,23 @@ function reducer(state: ProviderState, action: Action): ProviderState {...session,llmSelection: action.selection,}));- case "SET_MASTERY_PATH_ID":- return updateSelectedSession(state, (session) => ({- ...session,- masteryPathId: action.masteryPathId,- }));+ case "SET_MASTERY_PATH_ID": {+ if (!action.key) {+ return updateSelectedSession(state, (session) => ({+ ...session,+ masteryPathId: action.masteryPathId,+ }));+ }+ const target = state.sessions[action.key];+ if (!target) return state;+ return {+ ...state,+ sessions: {+ ...state.sessions,+ [action.key]: { ...target, masteryPathId: action.masteryPathId },+ },+ };+ }case "SET_PERSONA_SELECTION":return updateSelectedSession(state, (session) => ({...session,@@ -761,26 +795,16 @@ function reducer(state: ProviderState, action: Action): ProviderState {...state,sidebarRefreshToken: state.sidebarRefreshToken + 1,};- case "NEW_SESSION": {- const MAX_CACHED_SESSIONS = 20;- let nextSessions = {- ...state.sessions,- [action.key]: createSessionEntry(action.key),- };- const keys = Object.keys(nextSessions);- if (keys.length > MAX_CACHED_SESSIONS) {- const evictable = keys- .filter(- (k) => k !== action.key && nextSessions[k].status !== "running",- )- .sort(- (a, b) => nextSessions[a].updatedAt - nextSessions[b].updatedAt,- );- const toRemove = evictable.slice(0, keys.length - MAX_CACHED_SESSIONS);- for (const k of toRemove) delete nextSessions[k];- }- return { ...state, selectedKey: action.key, sessions: nextSessions };- }+ case "NEW_SESSION":+ return selectFreshDraft(state, action.key);+ // Idempotent variant of NEW_SESSION: guarantees there is *a* selected+ // session without discarding one a page already selected and configured.+ // The check belongs here rather than in the caller because a mount effect+ // only ever sees the state of the render that created it, which is stale+ // the moment anything else has dispatched.+ case "ENSURE_DRAFT_SESSION":+ if (state.selectedKey && state.sessions[state.selectedKey]) return state;+ return selectFreshDraft(state, action.key);default:return state;}@@ -1118,21 +1142,30 @@ export function UnifiedChatProvider({return;}if (event.type === "session_meta") {- // Post-turn metadata push (currently only used for the- // LLM-generated session title). The backend writes the new- // title to its store *before* sending this event. Update the- // active header immediately and bump the sidebar so history- // rows refresh to the generated title without a flicker.- const title = String(- (event.metadata as { title?: string } | undefined)?.title || "",- ).trim();+ // Post-turn metadata push: session state the backend settled during+ // the turn. It writes each value to its store *before* sending this,+ // so applying it here only catches the open client up to what a+ // reload would already show.+ const meta = event.metadata as+ | { title?: string; mastery_path_id?: string }+ | undefined;+ // The tutor can move a conversation between mastery paths mid-turn;+ // without this the composer would keep naming the path it started on.+ if (typeof meta?.mastery_path_id === "string") {+ dispatch({+ type: "SET_MASTERY_PATH_ID",+ key: effectiveKey,+ masteryPathId: meta.mastery_path_id.trim() || null,+ });+ }+ const title = String(meta?.title || "").trim();if (title) {dispatch({type: "SET_SESSION_TITLE",key: effectiveKey,title,});- } else {+ } else if (!meta?.mastery_path_id) {dispatch({ type: "BUMP_SIDEBAR_REFRESH" });}return;@@ -1448,11 +1481,15 @@ export function UnifiedChatProvider({// URL is now the source of truth for session loading.// Chat pages load sessions based on URL params; no sessionStorage restore needed.// Initialize a draft session so the provider always has a selected key.+ //+ // React flushes a child's effects before its parent's, so any page under+ // this provider has already picked and configured its session by the time+ // this runs — a plain NEW_SESSION here would throw that away (it is what+ // used to silently drop ``/home?capability=…&mastery_path_id=…``). The+ // reducer decides on live state; this only supplies the key it may need.useEffect(() => {if (typeof window === "undefined") return;- if (!state.selectedKey) {- dispatch({ type: "NEW_SESSION", key: makeDraftKey() });- }+ dispatch({ type: "ENSURE_DRAFT_SESSION", key: makeDraftKey() });}, []); // eslint-disable-line react-hooks/exhaustive-deps// Idle timeout: if a streaming session receives no events for the configureddiff --git a/web/hooks/useImaConnection.ts b/web/hooks/useImaConnection.tsindex aa4b89f20..d5bd3e22c 100644--- a/web/hooks/useImaConnection.ts+++ b/web/hooks/useImaConnection.ts@@ -1,6 +1,7 @@-import { useCallback, useRef, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import {+ getImaConfig,listImaKnowledgeBases,probeImaKnowledgeBase,type ImaProbe,@@ -19,9 +20,16 @@ interface UseImaConnectionOptions {name: string;onNameChange: (name: string) => void;onError: (error: string | null) => void;+ /** True while the IMA source is the one being filled in. */+ active: boolean;}export interface ImaConnectionController {+ /** Whether the engine page holds an account credential pair. */+ accountConfigured: boolean;+ /** True when this knowledge base supplies its own credentials instead. */+ useOwnCredentials: boolean;+ setUseOwnCredentials: (value: boolean) => void;clientId: string;setClientId: (value: string) => void;apiKey: string;@@ -32,8 +40,13 @@ export interface ImaConnectionController {setManualKnowledgeBaseId: (value: string) => void;lookup: ImaLookupState;manualProbe: ImaProbe | null;+ /** Credentials are resolvable — from this form or from the account pair. */+ credentialsReady: boolean;canSubmit: boolean;knowledgeBaseId: string;+ /** What to send: empty means "use the account pair stored server-side". */+ submittedClientId: string;+ submittedApiKey: string;reset: () => void;load: (reset: boolean) => Promise<void>;select: (item: ImaKnowledgeBaseOption) => void;@@ -45,7 +58,10 @@ export function useImaConnection({name,onNameChange,onError,+ active,}: UseImaConnectionOptions): ImaConnectionController {+ const [accountConfigured, setAccountConfigured] = useState(false);+ const [useOwnCredentials, setUseOwnCredentials] = useState(false);const [clientId, setClientId] = useState("");const [apiKey, setApiKey] = useState("");const [mode, setMode] = useState<ImaConnectionMode>("automatic");@@ -54,6 +70,35 @@ export function useImaConnection({const [manualProbe, setManualProbe] = useState<ImaProbe | null>(null);const requestVersionRef = useRef(0);+ // Read the account pair only once the user is actually on this source, so+ // opening the modal for any other engine costs nothing.+ useEffect(() => {+ if (!active) return;+ let cancelled = false;+ getImaConfig()+ .then((config) => {+ if (cancelled) return;+ setAccountConfigured(config.configured);+ // Without an account pair there is nothing to inherit, so the form+ // asks for one instead of offering a choice.+ if (!config.configured) setUseOwnCredentials(true);+ })+ .catch(() => {+ if (!cancelled) setUseOwnCredentials(true);+ });+ return () => {+ cancelled = true;+ };+ }, [active]);++ // What actually goes on the wire: empty tells the server to resolve the+ // account pair, so a stored key is never round-tripped through the browser.+ const submittedClientId = useOwnCredentials ? clientId.trim() : "";+ const submittedApiKey = useOwnCredentials ? apiKey.trim() : "";+ const credentialsReady = useOwnCredentials+ ? Boolean(clientId.trim() && apiKey.trim())+ : accountConfigured;+const reset = useCallback(() => {requestVersionRef.current += 1;setClientId("");@@ -75,6 +120,14 @@ export function useImaConnection({onError(null);}, [onError]);+ const changeUseOwnCredentials = useCallback(+ (value: boolean) => {+ setUseOwnCredentials(value);+ invalidateLookup();+ },+ [invalidateLookup],+ );+const changeClientId = useCallback((value: string) => {setClientId(value);@@ -109,9 +162,7 @@ export function useImaConnection({const load = useCallback(async (resetPage: boolean) => {- const normalizedClientId = clientId.trim();- const normalizedApiKey = apiKey.trim();- if (!normalizedClientId || !normalizedApiKey) return;+ if (!credentialsReady) return;const version = ++requestVersionRef.current;const cursor = resetPage ? "" : lookup.nextCursor;@@ -128,8 +179,8 @@ export function useImaConnection({);try {const page = await listImaKnowledgeBases({- clientId: normalizedClientId,- apiKey: normalizedApiKey,+ clientId: submittedClientId,+ apiKey: submittedApiKey,cursor,limit: 20,});@@ -157,7 +208,14 @@ export function useImaConnection({}));onError(error instanceof Error ? error.message : String(error));}- }, [apiKey, clientId, lookup.nextCursor, onError],+ },+ [+ credentialsReady,+ lookup.nextCursor,+ onError,+ submittedApiKey,+ submittedClientId,+ ],);const select = useCallback(@@ -174,18 +232,16 @@ export function useImaConnection({);const probe = useCallback(async () => {- const normalizedClientId = clientId.trim();- const normalizedApiKey = apiKey.trim();const knowledgeBaseId = manualKnowledgeBaseId.trim();- if (!normalizedClientId || !normalizedApiKey || !knowledgeBaseId) return;+ if (!credentialsReady || !knowledgeBaseId) return;const version = ++requestVersionRef.current;onError(null);setLookup((current) => ({ ...current, status: "loading" }));try {const result = await probeImaKnowledgeBase({- clientId: normalizedClientId,- apiKey: normalizedApiKey,+ clientId: submittedClientId,+ apiKey: submittedApiKey,knowledgeBaseId,});if (requestVersionRef.current !== version) return;@@ -196,8 +252,8 @@ export function useImaConnection({manualVerification: result.ok? {ok: true,- clientId: normalizedClientId,- apiKey: normalizedApiKey,+ clientId: submittedClientId,+ apiKey: submittedApiKey,knowledgeBaseId,}: null,@@ -212,19 +268,29 @@ export function useImaConnection({setManualProbe(null);onError(error instanceof Error ? error.message : String(error));}- }, [apiKey, clientId, manualKnowledgeBaseId, onError]);+ }, [+ credentialsReady,+ manualKnowledgeBaseId,+ onError,+ submittedApiKey,+ submittedClientId,+ ]);const canSubmit = canConnectIma({mode,name,- clientId,- apiKey,+ clientId: submittedClientId,+ apiKey: submittedApiKey,+ credentialsReady,selectedId: lookup.selectedId,manualKnowledgeBaseId,manualVerification: lookup.manualVerification,});return {+ accountConfigured,+ useOwnCredentials,+ setUseOwnCredentials: changeUseOwnCredentials,clientId,setClientId: changeClientId,apiKey,@@ -235,9 +301,12 @@ export function useImaConnection({setManualKnowledgeBaseId: changeManualKnowledgeBaseId,lookup,manualProbe,+ credentialsReady,canSubmit,knowledgeBaseId:mode === "automatic" ? lookup.selectedId : manualKnowledgeBaseId.trim(),+ submittedClientId,+ submittedApiKey,reset,load,select,diff --git a/web/hooks/useMasteryPathActivity.ts b/web/hooks/useMasteryPathActivity.tsnew file mode 100644index 000000000..cc6477bb5--- /dev/null+++ b/web/hooks/useMasteryPathActivity.ts@@ -0,0 +1,135 @@+"use client";++import { useCallback, useEffect, useRef, useState } from "react";++import { fetchProgressEvents, type MasteryEvent } from "@/lib/learning-api";++/**+ * Follow a mastery path while it changes underneath you.+ *+ * Tutoring happens in the chat, usually in another tab, so a snapshot taken+ * when the dashboard opened goes stale within a turn. Every committed change+ * to a path already emits an event numbered by the path's revision, so this+ * polls for events *after* the last revision it saw: a quiet path costs one+ * indexed query returning nothing, and a busy one streams in order with no+ * gaps and no duplicates.+ *+ * `revision` is the single "the path moved" signal — render off the event list+ * and re-read anything else (the map, the summary list) when it changes.+ * Polling pauses while the tab is hidden and catches up the moment it is+ * visible again, so a backgrounded dashboard costs nothing.+ */+const DEFAULT_INTERVAL_MS = 4000;++export interface MasteryPathActivity {+ events: MasteryEvent[];+ revision: number;+ /** Poll now instead of waiting for the next tick. */+ refresh: () => void;+}++/** The feed is stamped with the path it belongs to, so switching paths shows+ * nothing rather than the previous path's history for one render. */+export interface ActivityFeed {+ pathId: string | null;+ events: MasteryEvent[];+ revision: number;+}++export const EMPTY_FEED: ActivityFeed = {+ pathId: null,+ events: [],+ revision: 0,+};++/**+ * Fold one polled batch into the feed.+ *+ * `since` is what the request asked for, and it decides append vs replace: a+ * batch read from revision 0 is the path's whole history, so it *replaces*+ * rather than doubling anything already on screen. Keeping that rule here (and+ * not in the effect) is what makes a forced refresh safe to trigger from+ * anywhere.+ */+export function mergeEventBatch(+ previous: ActivityFeed,+ pathId: string,+ since: number,+ batch: MasteryEvent[],+): ActivityFeed {+ if (batch.length === 0) return previous;+ const continues = since > 0 && previous.pathId === pathId;+ return {+ pathId,+ events: continues ? [...previous.events, ...batch] : batch,+ revision: latestRevision(since, batch),+ };+}++/** Where the next read should start from after consuming ``batch``. */+export function latestRevision(since: number, batch: MasteryEvent[]): number {+ return batch.reduce((highest, event) => Math.max(highest, event.revision), since);+}++export function useMasteryPathActivity(+ pathId: string | null,+ options?: { intervalMs?: number },+): MasteryPathActivity {+ const intervalMs = options?.intervalMs ?? DEFAULT_INTERVAL_MS;+ const [feed, setFeed] = useState<ActivityFeed>(EMPTY_FEED);+ // The read cursor, carried in a ref so a tick never closes over a stale+ // revision and a new batch never restarts the polling effect. It is stamped+ // with its path, so a path switch reads from the beginning again without+ // anything having to reset it — and so a forced refresh resumes rather than+ // re-reading a history the feed already holds.+ const cursorRef = useRef<{ pathId: string | null; revision: number }>({+ pathId: null,+ revision: 0,+ });+ const [pollToken, setPollToken] = useState(0);++ const refresh = useCallback(() => setPollToken((token) => token + 1), []);++ useEffect(() => {+ if (!pathId) return;+ let cancelled = false;+ const controller = new AbortController();++ const poll = async () => {+ if (typeof document !== "undefined" && document.visibilityState !== "visible")+ return;+ const since =+ cursorRef.current.pathId === pathId ? cursorRef.current.revision : 0;+ try {+ const batch = await fetchProgressEvents(pathId, since, {+ signal: controller.signal,+ });+ if (cancelled || batch.length === 0) return;+ cursorRef.current = { pathId, revision: latestRevision(since, batch) };+ setFeed((previous) => mergeEventBatch(previous, pathId, since, batch));+ } catch {+ // A path can be deleted or reset mid-poll; the next tick recovers.+ }+ };++ void poll();+ const timer = setInterval(poll, intervalMs);+ // A hidden tab may have missed many ticks — catch up on return rather than+ // making the learner wait out a full interval.+ const pollWhenVisible = () => {+ if (document.visibilityState === "visible") void poll();+ };+ window.addEventListener("focus", pollWhenVisible);+ document.addEventListener("visibilitychange", pollWhenVisible);+ return () => {+ cancelled = true;+ controller.abort();+ clearInterval(timer);+ window.removeEventListener("focus", pollWhenVisible);+ document.removeEventListener("visibilitychange", pollWhenVisible);+ };+ }, [pathId, intervalMs, pollToken]);++ const current = feed.pathId === pathId ? feed : EMPTY_FEED;+ return { events: current.events, revision: current.revision, refresh };+}diff --git a/web/lib/book-api.ts b/web/lib/book-api.tsindex 0a4e9a2d7..6ceec6506 100644--- a/web/lib/book-api.ts+++ b/web/lib/book-api.ts@@ -5,9 +5,11 @@ import {} from "@/lib/book-ws-operation";import type {Book,+ BookDepth,BookDetail,BookProposal,Page,+ Progress,Spine,Block,} from "@/lib/book-types";@@ -53,12 +55,41 @@ export interface CreateBookPayload {question_categories?: number[];question_entries?: number[];language?: string;+ depth?: BookDepth;+}++/** Per-chapter generation cost, keyed by content type. */+export interface EstimateBasis {+ [contentType: string]: { blocks: number; words: number; seconds: number };}export const bookApi = {list: () => request<{ books: Book[] }>("/books"),- get: (book_id: string) =>- request<BookDetail>(`/books/${encodeURIComponent(book_id)}`),++ /**+ * Cost of one chapter of each content type, at a given depth.+ *+ * Fetched once; the spine editor sums it locally so the estimate stays live+ * while chapters are edited. The numbers derive from the same templates the+ * architect plans from, so they cannot drift from reality.+ */+ estimateBasis: (depth: BookDepth = "standard") =>+ request<{ depth: string; basis: EstimateBasis }>(+ `/estimate-basis?depth=${encodeURIComponent(depth)}`,+ ),+ /**+ * Load a book.+ *+ * `includeBlocks: false` returns chapter metadata without block payloads —+ * a compiled book's blocks carry their whole rendered content, so the full+ * response runs to hundreds of kilobytes. Views that only need the chapter+ * list should ask for summaries.+ */+ get: (book_id: string, options?: { includeBlocks?: boolean }) =>+ request<BookDetail>(+ `/books/${encodeURIComponent(book_id)}` ++ (options?.includeBlocks === false ? "?include_blocks=false" : ""),+ ),delete: (book_id: string) =>request<{ deleted: boolean; book_id: string }>(`/books/${encodeURIComponent(book_id)}`,@@ -147,6 +178,35 @@ export const bookApi = {}),}),+ /** Edit a block's prose in place. Title/body only — see the backend note. */+ updateBlock: (params: {+ book_id: string;+ page_id: string;+ block_id: string;+ title?: string;+ body?: string;+ }) =>+ request<{ block: Block }>("/books/update-block", {+ method: "POST",+ body: JSON.stringify(params),+ }),++ markVisited: (book_id: string, page_id: string) =>+ request<{ progress: Progress }>("/books/progress/visit", {+ method: "POST",+ body: JSON.stringify({ book_id, page_id }),+ }),++ toggleBookmark: (book_id: string, page_id: string) =>+ request<{ progress: Progress }>("/books/progress/bookmark", {+ method: "POST",+ body: JSON.stringify({ book_id, page_id }),+ }),++ /** Href for the Markdown download — a plain link, so the browser saves it. */+ exportUrl: (book_id: string) =>+ apiUrl(`${BASE}/books/${encodeURIComponent(book_id)}/export`),+deleteBlock: (book_id: string, page_id: string, block_id: string) =>request<{ ok: boolean }>("/books/delete-block", {method: "POST",@@ -194,9 +254,10 @@ export const bookApi = {block_id: string;question_id?: string;user_answer?: string;- is_correct: boolean;+ /** Omit for a written answer the reader revealed but didn't self-grade. */+ is_correct?: boolean;}) =>- request<{ progress: Record<string, unknown> }>("/books/quiz-attempt", {+ request<{ progress: Progress }>("/books/quiz-attempt", {method: "POST",body: JSON.stringify(params),}),@@ -213,6 +274,14 @@ export const bookApi = {body: JSON.stringify({ book_id, page_id, session_id }),}),+ /** Re-queue unfinished pages, keeping everything already compiled. */+ resume: (book_id: string) =>+ request<{ pages: Page[] }>("/books/resume", {+ method: "POST",+ body: JSON.stringify({ book_id }),+ }),++ /** Destructive: discards every page and regenerates from the spine. */rebuild: (book_id: string, auto_compile = true) =>request<{ pages: Page[] }>("/books/rebuild", {method: "POST",diff --git a/web/lib/book-progress.ts b/web/lib/book-progress.tsindex 885498f2f..f80b9b1b3 100644--- a/web/lib/book-progress.ts+++ b/web/lib/book-progress.ts@@ -174,9 +174,25 @@ function startStage(state: BookProgress, id: StageId): BookProgress {}function completeStage(state: BookProgress, id: StageId): BookProgress {+ // A stage that already reported a failure stays failed: the pipeline still+ // emits stage_end on its way out of the `async with`, and letting that+ // overwrite the error would show a green tick for a sweep that found nothing.+ if (state.stages[id]?.state === "error") return state;return patchStage(state, id, { state: "completed", endedAt: Date.now() });}+function errorStage(+ state: BookProgress,+ id: StageId,+ detail?: string,+): BookProgress {+ return patchStage(state, id, {+ state: "error",+ detail: detail || undefined,+ endedAt: Date.now(),+ });+}+function asNumber(value: unknown): number {if (typeof value === "number") return value;if (Array.isArray(value)) return value.length;@@ -189,6 +205,8 @@ function asString(value: unknown): string {}/** Reducer: ingest a single WS event and return the next snapshot. */+export const RESET_BOOK_PROGRESS = { type: "__reset" } as const;+export function reduceBookEvent(state: BookProgress,event: BookWsEvent,@@ -200,6 +218,21 @@ export function reduceBookEvent();const eventType = String(event.type || "");+ // Explicit reset — the timeline belongs to one book's run. Selecting another+ // book (or starting a new one) must not inherit the previous book's stages.+ if (eventType === "__reset") {+ return emptyBookProgress();+ }++ // A book id that contradicts the one we're tracking means the stream moved+ // on; start clean rather than blending two runs into one timeline.+ const incomingBookId = asString(+ (event.metadata as Record<string, unknown> | undefined)?.book_id,+ );+ if (incomingBookId && state.bookId && incomingBookId !== state.bookId) {+ state = emptyBookProgress();+ }+// Track book id once.let next: BookProgress = { ...state, updatedAt: Date.now() };const bookIdFromMeta = asString(meta.book_id);@@ -208,7 +241,7 @@ export function reduceBookEvent(}// Pick up STAGE_BEGIN / STAGE_END from generic stream events.- if (eventType === "stage_begin" && stage) {+ if (eventType === "stage_start" && stage) {if ((STAGE_ORDER as string[]).includes(stage)) {next = startStage(next, stage as StageId);}@@ -258,6 +291,13 @@ export function reduceBookEvent(});break;}+ case "exploration_failed": {+ // The stage still emits stage_end afterwards; errorStage wins so the+ // timeline does not claim the sweep succeeded.+ next = errorStage(next, "exploration", asString(meta.reason));+ next = { ...next, message: "Source sweep failed" };+ break;+ }case "spine_round": {const round = asString(meta.round);const isCritique = round.startsWith("critique");@@ -395,6 +435,7 @@ export function reduceBookEvent(next = completeStage(next, "overview");break;}+ case "book_ready":case "compilation_complete": {next = completeStage(next, "compilation");next = { ...next, message: "Book compilation complete" };diff --git a/web/lib/book-types.ts b/web/lib/book-types.tsindex f73924a40..2249a7c68 100644--- a/web/lib/book-types.ts+++ b/web/lib/book-types.ts@@ -6,10 +6,16 @@ export type BookStatus =| "draft"| "spine_ready"| "compiling"+ // Compilation stopped itself after repeated provider failures (quota, keys,+ // outage). Everything generated so far is intact and `resume` continues.+ | "paused"| "ready"| "error"| "archived";+/** How much prose the reader wants per chapter. Scales template word counts. */+export type BookDepth = "brief" | "standard" | "deep";+export type PageStatus =| "pending"| "planning"@@ -97,7 +103,10 @@ export interface Page {content_type: ContentType;status: PageStatus;order: number;+ /** Empty when the page was fetched via a summary (`include_blocks=false`). */blocks: Block[];+ /** Present on summaries so callers can show a count without the payloads. */+ block_count?: number;links: Array<{ target_page_id: string; relation: string; label: string }>;parent_page_id: string;error: string;@@ -115,6 +124,10 @@ export interface Chapter {page_ids: string[];summary: string;order: number;+ /** Engine-injected overview chapter — not user-authored. */+ auto_overview?: boolean;+ /** Spawned by a deep dive; lives outside the book's chapter structure. */+ deep_dive?: boolean;}export interface Spine {@@ -135,6 +148,14 @@ export interface BookProposal {rationale: string;}+/** How far the reader has got. Attached by the list endpoint. */+export interface ReadingSummary {+ current_page_id: string;+ visited_pages: number;+ total_pages: number;+ percent: number;+}+export interface Book {id: string;title: string;@@ -143,13 +164,28 @@ export interface Book {proposal: BookProposal | null;knowledge_bases: string[];language: string;+ depth?: BookDepth;page_count: number;chapter_count: number;created_at: number;updated_at: number;metadata: Record<string, unknown> & {page_chat_sessions?: Record<string, string>;+ /** Why compilation paused — set alongside `status: "paused"`. */+ pause_reason?: string;};+ /** Present on list responses only. */+ reading?: ReadingSummary;+}++export interface QuizAttempt {+ block_id: string;+ page_id: string;+ question_id: string;+ user_answer: string;+ /** `null` when a written answer was revealed but never self-graded. */+ is_correct: boolean | null;+ timestamp: number;}export interface Progress {@@ -157,14 +193,7 @@ export interface Progress {current_page_id: string;visited_page_ids: string[];bookmarked_page_ids: string[];- quiz_attempts: Array<{- block_id: string;- page_id: string;- question_id: string;- user_answer: string;- is_correct: boolean;- timestamp: number;- }>;+ quiz_attempts: QuizAttempt[];weak_chapters: string[];score: number;updated_at: number;diff --git a/web/lib/chat-launch-intent.ts b/web/lib/chat-launch-intent.tsnew file mode 100644index 000000000..bc768e1a0--- /dev/null+++ b/web/lib/chat-launch-intent.ts@@ -0,0 +1,49 @@+/**+ * The `/home` launch-URL contract — both ends in one place.+ *+ * Other surfaces (the Mastery Path dashboard, capability shortcuts) open a+ * chat by navigating to `/home` with query parameters that say how the+ * composer should be set up before the learner types anything. Building and+ * reading that URL are two halves of one contract, so they live together and+ * are covered by a round-trip test.+ *+ * Parsing is deliberately dependency-free: tool names are returned verbatim+ * and validated by the caller against its own tool registry.+ */++/** Composer setup requested by the URL that opened `/home`. */+export interface ChatLaunchIntent {+ /** Capability to activate. `""` means plain chat; `null` means unspecified. */+ capability: string | null;+ /** Raw `tool` values — the caller filters these against its registry. */+ tools: string[];+ /** Persistent mastery path this conversation should operate on. */+ masteryPathId: string | null;+}++const EMPTY_INTENT: ChatLaunchIntent = {+ capability: null,+ tools: [],+ masteryPathId: null,+};++/** Read the launch intent out of a `location.search` string. */+export function readChatLaunchIntent(search: string): ChatLaunchIntent {+ if (!search) return { ...EMPTY_INTENT };+ const params = new URLSearchParams(search);+ const capability = params.get("capability");+ return {+ capability: capability === null ? null : capability.trim(),+ tools: params.getAll("tool").map((tool) => tool.trim()),+ masteryPathId: params.get("mastery_path_id")?.trim() || null,+ };+}++/** Build a fresh chat URL associated with existing persistent mastery state. */+export function newMasteryPathChatUrl(masteryPathId: string): string {+ const params = new URLSearchParams({+ capability: "mastery_path",+ mastery_path_id: masteryPathId,+ });+ return `/home?${params.toString()}`;+}diff --git a/web/lib/concept-graph.ts b/web/lib/concept-graph.tsindex 23b5cd974..f1dea1a7f 100644--- a/web/lib/concept-graph.ts+++ b/web/lib/concept-graph.ts@@ -1,9 +1,9 @@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";+ 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)) {diff --git a/web/lib/ima-connection.ts b/web/lib/ima-connection.tsindex 09caea0f4..2a263dc83 100644--- a/web/lib/ima-connection.ts+++ b/web/lib/ima-connection.ts@@ -2,7 +2,12 @@ export const IMA_PROVIDER = "ima";export type ImaConnectionMode = "automatic" | "manual";export type ImaLookupStatus =- "idle" | "loading" | "ready" | "empty" | "error" | "manual_verified";+ | "idle"+ | "loading"+ | "ready"+ | "empty"+ | "error"+ | "manual_verified";export interface ImaKnowledgeBaseOption {id: string;@@ -70,8 +75,11 @@ export const emptyImaLookupState = (): ImaLookupState => ({export const canConnectIma = (input: {mode: ImaConnectionMode;name: string;+ /** Credentials as submitted — empty when the account pair is used. */clientId: string;apiKey: string;+ /** Credentials resolve, either from this form or from the account pair. */+ credentialsReady: boolean;selectedId: string;manualKnowledgeBaseId: string;manualVerification: ImaManualVerification | null;@@ -79,9 +87,11 @@ export const canConnectIma = (input: {const name = input.name.trim();const clientId = input.clientId.trim();const apiKey = input.apiKey.trim();- if (!name || !clientId || !apiKey) return false;+ if (!name || !input.credentialsReady) return false;if (input.mode === "automatic") return Boolean(input.selectedId.trim());+ // A manually typed id is only trusted once the verdict for *these* exact+ // credentials came back ok — editing either invalidates it.const knowledgeBaseId = input.manualKnowledgeBaseId.trim();const verified = input.manualVerification;return Boolean(diff --git a/web/lib/knowledge-api.ts b/web/lib/knowledge-api.tsindex a4dbce4d6..e81087f02 100644--- a/web/lib/knowledge-api.ts+++ b/web/lib/knowledge-api.ts@@ -42,6 +42,13 @@ export interface PageIndexConfig {configured: boolean;}+/** Account-level Tencent IMA credentials, shared by every `ima` KB. */+export interface ImaAccountConfig {+ client_id: string;+ api_key_set: boolean;+ configured: boolean;+}+export interface LlamaIndexConfig {version: number;/** "hybrid" (BM25 + vector fusion) or "vector" only. */@@ -279,6 +286,48 @@ export async function updatePageIndexConfig(payload: {return (await res.json()) as PageIndexConfig;}+const IMA_CONFIG_PATH = "/api/v1/knowledge/rag-pipelines/ima/config";++export async function getImaConfig(options?: {+ force?: boolean;+}): Promise<ImaAccountConfig> {+ return withClientCache<ImaAccountConfig>(+ `${KNOWLEDGE_CACHE_PREFIX}ima-config`,+ async () => {+ const response = await apiFetch(apiUrl(IMA_CONFIG_PATH), {+ cache: "no-store",+ });+ if (!response.ok) {+ throw new Error(+ await readErrorDetail(response, "Failed to read Tencent IMA config"),+ );+ }+ return (await response.json()) as ImaAccountConfig;+ },+ { force: options?.force, ttlMs: 15_000 },+ );+}++export async function updateImaConfig(payload: {+ client_id?: string;+ /** Omit to keep the stored key, "" to clear it, any value to replace it. */+ api_key?: string;+}): Promise<ImaAccountConfig> {+ const res = await apiFetch(apiUrl(IMA_CONFIG_PATH), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(payload),+ });+ if (!res.ok) {+ throw new Error(+ await readErrorDetail(res, "Failed to update Tencent IMA config"),+ );+ }+ // The provider list's `configured` flag depends on this; refresh it.+ invalidateKnowledgeCaches();+ return (await res.json()) as ImaAccountConfig;+}+const LLAMAINDEX_CONFIG_PATH ="/api/v1/knowledge/rag-pipelines/llamaindex/config";@@ -705,8 +754,9 @@ export interface ImaProbe {}export async function listImaKnowledgeBases(payload: {- clientId: string;- apiKey: string;+ /** Empty falls back to the account credentials stored on the engine page. */+ clientId?: string;+ apiKey?: string;cursor?: string;limit?: number;}): Promise<ImaKnowledgeBasePage> {@@ -714,8 +764,8 @@ export async function listImaKnowledgeBases(payload: {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({- client_id: payload.clientId,- api_key: payload.apiKey,+ client_id: payload.clientId ?? "",+ api_key: payload.apiKey ?? "",cursor: payload.cursor ?? "",limit: payload.limit ?? 20,}),@@ -730,16 +780,16 @@ export async function listImaKnowledgeBases(payload: {}export async function probeImaKnowledgeBase(payload: {- clientId: string;- apiKey: string;+ clientId?: string;+ apiKey?: string;knowledgeBaseId: string;}): Promise<ImaProbe> {const res = await apiFetch(apiUrl("/api/v1/knowledge/probe-ima"), {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({- client_id: payload.clientId,- api_key: payload.apiKey,+ client_id: payload.clientId ?? "",+ api_key: payload.apiKey ?? "",knowledge_base_id: payload.knowledgeBaseId,}),skipAuthRedirect: true,@@ -754,8 +804,9 @@ export async function probeImaKnowledgeBase(payload: {export async function connectImaKnowledgeBase(payload: {name: string;- clientId: string;- apiKey: string;+ /** Empty binds the KB to the account credentials instead of pinning a copy. */+ clientId?: string;+ apiKey?: string;knowledgeBaseId: string;}): Promise<{status: string;@@ -768,8 +819,8 @@ export async function connectImaKnowledgeBase(payload: {headers: { "Content-Type": "application/json" },body: JSON.stringify({name: payload.name,- client_id: payload.clientId,- api_key: payload.apiKey,+ client_id: payload.clientId ?? "",+ api_key: payload.apiKey ?? "",knowledge_base_id: payload.knowledgeBaseId,}),skipAuthRedirect: true,diff --git a/web/lib/knowledge-helpers.ts b/web/lib/knowledge-helpers.tsindex df9f6f6c1..f998af2d8 100644--- a/web/lib/knowledge-helpers.ts+++ b/web/lib/knowledge-helpers.ts@@ -93,18 +93,13 @@ export interface KnowledgeBase {available?: boolean;}-export type ProviderConnectionStatus =- | "ready"- | "per_kb"- | "needs_key"- | "unavailable";+export type ProviderConnectionStatus = "ready" | "needs_key" | "unavailable";export const providerConnectionStatus = (provider: {id: string;configured?: boolean;requires_api_key?: boolean;}): ProviderConnectionStatus => {- if (provider.id === "ima") return "per_kb";if (provider.requires_api_key && provider.configured === false)return "needs_key";if (provider.configured === false) return "unavailable";diff --git a/web/lib/learning-api.ts b/web/lib/learning-api.tsindex 78a3b1636..8897ec3f7 100644--- a/web/lib/learning-api.ts+++ b/web/lib/learning-api.ts@@ -86,30 +86,127 @@ export interface MasteryMap {export interface NextStep {action: string;+ knowledge_point_id: string;knowledge_point_name: string;knowledge_point_type: string;status: string;+ gate: string;mastery: number;threshold: number;reason: string;+ /** The outstanding question's text, when `action` is `answer_pending`. */+ pending_prompt: string;}export interface MasteryMapResult {book_id: string;+ path_revision: number;next: NextStep;map: MasteryMap;}export async function fetchMasteryMap(pathId: string,+ init?: RequestInit,): Promise<MasteryMapResult> {const res = await apiFetch(apiUrl(`/api/v1/learning/progress/${encodeURIComponent(pathId)}/map`),+ init,);if (!res.ok) throw new Error(`Failed to fetch mastery map: ${res.status}`);return res.json() as Promise<MasteryMapResult>;}+// ── Activity feed ─────────────────────────────────────────────────────────+// Mirrors deeptutor/learning/models.py MasteryEvent. Every committed change to+// a path emits one, numbered by the path's revision — which is what lets the+// dashboard follow along with a tutoring session running in another tab.++export interface MasteryEvent {+ id: number;+ revision: number;+ event_type: string;+ payload: Record<string, unknown>;+ session_id: string;+ turn_id: string;+ created_at: number;+}++export async function fetchProgressEvents(+ pathId: string,+ afterRevision = 0,+ init?: RequestInit,+): Promise<MasteryEvent[]> {+ const res = await apiFetch(+ apiUrl(+ `/api/v1/learning/progress/${encodeURIComponent(pathId)}/events?after_revision=${afterRevision}`,+ ),+ init,+ );+ if (!res.ok) throw new Error(`Failed to fetch path events: ${res.status}`);+ return (await res.json()).events as MasteryEvent[];+}++// ── One objective's evidence trail ────────────────────────────────────────+// Mirrors deeptutor/learning/policy.py objective_report.++export interface ObjectiveAttempt {+ question_id: string;+ prompt: string;+ answer: string;+ is_correct: boolean;+ error_type: string;+ at: number;+}++export interface ObjectiveReview {+ due_at: number | null;+ interval_index: number;+ consecutive_correct: number;+ consecutive_wrong: number;+}++export interface ObjectiveErrorRecord {+ id: string;+ error_type: string;+ status: string;+ self_attribution: string;+ retries: number;+ created_at: number;+}++export interface ObjectiveReport {+ id: string;+ name: string;+ type: string;+ module_name: string;+ status: ObjectiveStatus;+ gate: "quantitative" | "qualitative";+ mastered: boolean;+ mastery: number;+ threshold: number;+ attempts: ObjectiveAttempt[];+ correct_count: number;+ explanation: string;+ review: ObjectiveReview | null;+ errors: ObjectiveErrorRecord[];+}++export async function fetchObjectiveReport(+ pathId: string,+ objectiveId: string,+ init?: RequestInit,+): Promise<ObjectiveReport> {+ const res = await apiFetch(+ apiUrl(+ `/api/v1/learning/progress/${encodeURIComponent(pathId)}/objectives/${encodeURIComponent(objectiveId)}`,+ ),+ init,+ );+ if (!res.ok) throw new Error(`Failed to fetch objective: ${res.status}`);+ return (await res.json()).objective as ObjectiveReport;+}+export interface ProgressSummary {book_id: string;name: string;@@ -149,6 +246,18 @@ export async function redoProgress(bookId: string) {return res.json();}+/** Drop an outstanding question, keeping every mastery level already earned. */+export async function skipPendingQuestion(bookId: string) {+ const res = await apiFetch(+ apiUrl(+ `/api/v1/learning/progress/${encodeURIComponent(bookId)}/skip-question`,+ ),+ { method: "POST" },+ );+ if (!res.ok) throw new Error(`Failed to skip question: ${res.status}`);+ return res.json();+}+export async function importFromBook(bookId: string,chapters: { title: string; knowledge_points: string[] }[],diff --git a/web/lib/llm-options.ts b/web/lib/llm-options.tsindex 504733114..8f7b38b80 100644--- a/web/lib/llm-options.ts+++ b/web/lib/llm-options.ts@@ -52,10 +52,13 @@ export async function listLLMOptions(options?: {options?.timeoutMs ?? DEFAULT_LLM_OPTIONS_TIMEOUT_MS,);try {- const response = await apiFetch(apiUrl("/api/v1/settings/llm-options"), {- cache: "no-store",- signal: controller.signal,- });+ const response = await apiFetch(+ apiUrl("/api/v1/settings/llm-options"),+ {+ cache: "no-store",+ signal: controller.signal,+ },+ );if (!response.ok) {throw new Error(`Failed to load LLM options: ${response.status}`);}diff --git a/web/lib/mastery-path-navigation.ts b/web/lib/mastery-path-navigation.tsdeleted file mode 100644index 5cfd7ab2c..000000000--- a/web/lib/mastery-path-navigation.ts+++ /dev/null@@ -1,8 +0,0 @@-/** Build a fresh chat URL associated with existing persistent mastery state. */-export function newMasteryPathChatUrl(masteryPathId: string): string {- const params = new URLSearchParams({- capability: "mastery_path",- mastery_path_id: masteryPathId,- });- return `/home?${params.toString()}`;-}diff --git a/web/lib/reconnecting-websocket.ts b/web/lib/reconnecting-websocket.tsindex 6632c187b..194898ff4 100644--- a/web/lib/reconnecting-websocket.ts+++ b/web/lib/reconnecting-websocket.ts@@ -1,44 +1,44 @@-const CONNECTING = 0-const OPEN = 1+const CONNECTING = 0;+const OPEN = 1;-const DEFAULT_BASE_RETRY_MS = 250-const DEFAULT_MAX_RETRY_MS = 8_000-const DEFAULT_STALE_CONNECTING_MS = 10_000+const DEFAULT_BASE_RETRY_MS = 250;+const DEFAULT_MAX_RETRY_MS = 8_000;+const DEFAULT_STALE_CONNECTING_MS = 10_000;export function reconnectDelayMs(attempt: number,baseDelayMs = DEFAULT_BASE_RETRY_MS,- maxDelayMs = DEFAULT_MAX_RETRY_MS+ maxDelayMs = DEFAULT_MAX_RETRY_MS,): number {- return Math.min(baseDelayMs * 2 ** Math.max(0, attempt), maxDelayMs)+ return Math.min(baseDelayMs * 2 ** Math.max(0, attempt), maxDelayMs);}interface RetryScheduler {- set(callback: () => void, delayMs: number): unknown- clear(handle: unknown): void+ set(callback: () => void, delayMs: number): unknown;+ clear(handle: unknown): void;}interface ReconnectingWebSocketHandlers {- onOpen?: () => void- onMessage: (event: MessageEvent) => void- onDisconnect?: () => void- onError?: (error: unknown) => void+ onOpen?: () => void;+ onMessage: (event: MessageEvent) => void;+ onDisconnect?: () => void;+ onError?: (error: unknown) => void;}interface ReconnectingWebSocketOptions {- createSocket?: (url: string) => WebSocket- shouldReconnect?: () => boolean- scheduler?: RetryScheduler- now?: () => number- baseRetryMs?: number- maxRetryMs?: number- staleConnectingMs?: number+ createSocket?: (url: string) => WebSocket;+ shouldReconnect?: () => boolean;+ scheduler?: RetryScheduler;+ now?: () => number;+ baseRetryMs?: number;+ maxRetryMs?: number;+ staleConnectingMs?: number;}const defaultScheduler: RetryScheduler = {set: (callback, delayMs) => setTimeout(callback, delayMs),- clear: handle => clearTimeout(handle as ReturnType<typeof setTimeout>),-}+ clear: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),+};/*** Owns one browser WebSocket and keeps it alive across transient disconnects.@@ -48,147 +48,152 @@ const defaultScheduler: RetryScheduler = {* focus/visibility/online events for an immediate connection attempt.*/export class ReconnectingWebSocket {- private socket: WebSocket | null = null- private retryHandle: unknown = null- private retryAttempt = 0- private connectingSince = 0- private stopped = true-- private readonly createSocket: (url: string) => WebSocket- private readonly shouldReconnect: () => boolean- private readonly scheduler: RetryScheduler- private readonly now: () => number- private readonly baseRetryMs: number- private readonly maxRetryMs: number- private readonly staleConnectingMs: number+ private socket: WebSocket | null = null;+ private retryHandle: unknown = null;+ private retryAttempt = 0;+ private connectingSince = 0;+ private stopped = true;++ private readonly createSocket: (url: string) => WebSocket;+ private readonly shouldReconnect: () => boolean;+ private readonly scheduler: RetryScheduler;+ private readonly now: () => number;+ private readonly baseRetryMs: number;+ private readonly maxRetryMs: number;+ private readonly staleConnectingMs: number;constructor(private readonly url: string,private readonly handlers: ReconnectingWebSocketHandlers,- options: ReconnectingWebSocketOptions = {}+ options: ReconnectingWebSocketOptions = {},) {- this.createSocket = options.createSocket ?? (url => new WebSocket(url))- this.shouldReconnect = options.shouldReconnect ?? (() => true)- this.scheduler = options.scheduler ?? defaultScheduler- this.now = options.now ?? Date.now- this.baseRetryMs = options.baseRetryMs ?? DEFAULT_BASE_RETRY_MS- this.maxRetryMs = options.maxRetryMs ?? DEFAULT_MAX_RETRY_MS- this.staleConnectingMs = options.staleConnectingMs ?? DEFAULT_STALE_CONNECTING_MS+ this.createSocket = options.createSocket ?? ((url) => new WebSocket(url));+ this.shouldReconnect = options.shouldReconnect ?? (() => true);+ this.scheduler = options.scheduler ?? defaultScheduler;+ this.now = options.now ?? Date.now;+ this.baseRetryMs = options.baseRetryMs ?? DEFAULT_BASE_RETRY_MS;+ this.maxRetryMs = options.maxRetryMs ?? DEFAULT_MAX_RETRY_MS;+ this.staleConnectingMs =+ options.staleConnectingMs ?? DEFAULT_STALE_CONNECTING_MS;}get connected(): boolean {- return this.socket?.readyState === OPEN+ return this.socket?.readyState === OPEN;}start(): void {- if (!this.stopped) return- this.stopped = false- if (this.shouldReconnect()) this.open()+ if (!this.stopped) return;+ this.stopped = false;+ if (this.shouldReconnect()) this.open();}/** Try immediately after the browser becomes active or comes back online. */wake(): void {- if (this.stopped || !this.shouldReconnect()) return- this.clearRetry()- this.retryAttempt = 0+ if (this.stopped || !this.shouldReconnect()) return;+ this.clearRetry();+ this.retryAttempt = 0;- if (this.socket?.readyState === OPEN) return+ if (this.socket?.readyState === OPEN) return;if (this.socket?.readyState === CONNECTING &&this.now() - this.connectingSince < this.staleConnectingMs) {- return+ return;}- this.releaseSocket()- this.open()+ this.releaseSocket();+ this.open();}send(payload: string): boolean {- if (!this.socket || this.socket.readyState !== OPEN) return false+ if (!this.socket || this.socket.readyState !== OPEN) return false;try {- this.socket.send(payload)- return true+ this.socket.send(payload);+ return true;} catch (error) {- this.handlers.onError?.(error)- this.socket.close()- return false+ this.handlers.onError?.(error);+ this.socket.close();+ return false;}}stop(): void {- if (this.stopped) return- this.stopped = true- this.clearRetry()- this.releaseSocket()- this.retryAttempt = 0+ if (this.stopped) return;+ this.stopped = true;+ this.clearRetry();+ this.releaseSocket();+ this.retryAttempt = 0;}private open(): void {if (this.stopped || (this.socket && this.socket.readyState <= OPEN)) {- return+ return;}- let socket: WebSocket+ let socket: WebSocket;try {- socket = this.createSocket(this.url)+ socket = this.createSocket(this.url);} catch (error) {- this.handlers.onError?.(error)- this.scheduleRetry()- return+ this.handlers.onError?.(error);+ this.scheduleRetry();+ return;}- this.socket = socket- this.connectingSince = this.now()+ this.socket = socket;+ this.connectingSince = this.now();socket.onopen = () => {- if (this.socket !== socket || this.stopped) return- this.retryAttempt = 0- this.handlers.onOpen?.()- }- socket.onmessage = event => {+ if (this.socket !== socket || this.stopped) return;+ this.retryAttempt = 0;+ this.handlers.onOpen?.();+ };+ socket.onmessage = (event) => {if (this.socket === socket && !this.stopped) {- this.handlers.onMessage(event)+ this.handlers.onMessage(event);}- }- socket.onerror = error => {+ };+ socket.onerror = (error) => {if (this.socket === socket && !this.stopped) {- this.handlers.onError?.(error)+ this.handlers.onError?.(error);}- }+ };socket.onclose = () => {- if (this.socket !== socket) return- this.socket = null- this.handlers.onDisconnect?.()- this.scheduleRetry()- }+ if (this.socket !== socket) return;+ this.socket = null;+ this.handlers.onDisconnect?.();+ this.scheduleRetry();+ };}private scheduleRetry(): void {if (this.stopped || this.retryHandle !== null || !this.shouldReconnect()) {- return+ return;}- const delayMs = reconnectDelayMs(this.retryAttempt, this.baseRetryMs, this.maxRetryMs)- this.retryAttempt += 1+ const delayMs = reconnectDelayMs(+ this.retryAttempt,+ this.baseRetryMs,+ this.maxRetryMs,+ );+ this.retryAttempt += 1;this.retryHandle = this.scheduler.set(() => {- this.retryHandle = null- if (this.shouldReconnect()) this.open()- }, delayMs)+ this.retryHandle = null;+ if (this.shouldReconnect()) this.open();+ }, delayMs);}private clearRetry(): void {- if (this.retryHandle === null) return- this.scheduler.clear(this.retryHandle)- this.retryHandle = null+ if (this.retryHandle === null) return;+ this.scheduler.clear(this.retryHandle);+ this.retryHandle = null;}private releaseSocket(): void {- const socket = this.socket- this.socket = null- if (!socket) return- socket.onopen = null- socket.onmessage = null- socket.onerror = null- socket.onclose = null- if (socket.readyState <= OPEN) socket.close()+ const socket = this.socket;+ this.socket = null;+ if (!socket) return;+ socket.onopen = null;+ socket.onmessage = null;+ socket.onerror = null;+ socket.onclose = null;+ if (socket.readyState <= OPEN) socket.close();}}diff --git a/web/lib/relative-time.ts b/web/lib/relative-time.tsindex 6a158ebbe..276086426 100644--- a/web/lib/relative-time.ts+++ b/web/lib/relative-time.ts@@ -47,5 +47,13 @@ export function formatRelativeTime(timestamp: number, locale: string): string {return formatter.format(Math.round(diffSeconds / 60), "minute");if (abs < 86400)return formatter.format(Math.round(diffSeconds / 3600), "hour");- return formatter.format(Math.round(diffSeconds / 86400), "day");+ if (abs < 604800)+ return formatter.format(Math.round(diffSeconds / 86400), "day");+ // Past a week, days stop being readable — "31 days ago" is worse than+ // "last month". Intl handles the plural and the wording per locale.+ if (abs < 2592000)+ return formatter.format(Math.round(diffSeconds / 604800), "week");+ if (abs < 31536000)+ return formatter.format(Math.round(diffSeconds / 2592000), "month");+ return formatter.format(Math.round(diffSeconds / 31536000), "year");}diff --git a/web/lib/use-book-stream.ts b/web/lib/use-book-stream.tsnew file mode 100644index 000000000..ecc91628e--- /dev/null+++ b/web/lib/use-book-stream.ts@@ -0,0 +1,123 @@+"use client";++import { useEffect, useRef } from "react";++import { wsUrl } from "@/lib/api";+import type { BookWsEvent } from "@/lib/book-ws-operation";++const BOOK_WS_PATH = "/api/v1/book/ws";++// Backs off quickly at first — a dropped socket is usually a transient blip —+// then settles so a backend that is genuinely down isn't hammered.+const RECONNECT_DELAYS_MS = [500, 1_000, 2_000, 5_000, 10_000];++/**+ * Subscribe to a book's live event stream for as long as it is open.+ *+ * Separate from `runBookSocketOperation`, which owns a socket per action and+ * closes it on the result. Compilation outlives any single action, so watching+ * a book needs a connection that outlives them too: this one stays open,+ * reconnects on drop, and re-subscribes on the way back — the backend replays+ * recent history on subscribe, so a reconnect catches up on what it missed.+ *+ * `onEvent` is held in a ref, so callers may pass an inline closure without+ * causing the socket to tear down and reconnect on every render.+ */+export function useBookStream(+ bookId: string | null,+ onEvent: (event: BookWsEvent) => void,+): void {+ const handlerRef = useRef(onEvent);+ useEffect(() => {+ handlerRef.current = onEvent;+ });++ useEffect(() => {+ if (!bookId) return;++ let disposed = false;+ let socket: WebSocket | null = null;+ let retry = 0;+ let reconnectTimer: ReturnType<typeof setTimeout> | undefined;++ const connect = () => {+ if (disposed) return;++ let next: WebSocket;+ try {+ next = new WebSocket(wsUrl(BOOK_WS_PATH));+ } catch {+ scheduleReconnect();+ return;+ }+ socket = next;++ next.onopen = () => {+ retry = 0;+ try {+ next.send(JSON.stringify({ type: "subscribe", book_id: bookId }));+ } catch {+ // The close handler will schedule a reconnect.+ }+ };++ next.onmessage = (message: MessageEvent<string>) => {+ let event: BookWsEvent;+ try {+ event = JSON.parse(message.data) as BookWsEvent;+ } catch {+ return;+ }+ handlerRef.current(event);+ };++ next.onclose = () => {+ socket = null;+ scheduleReconnect();+ };++ // `onclose` always follows `onerror`, so reconnection is handled there.+ next.onerror = () => {};+ };++ const scheduleReconnect = () => {+ if (disposed) return;+ const delay =+ RECONNECT_DELAYS_MS[Math.min(retry, RECONNECT_DELAYS_MS.length - 1)];+ retry += 1;+ reconnectTimer = setTimeout(connect, delay);+ };++ connect();++ return () => {+ disposed = true;+ if (reconnectTimer) clearTimeout(reconnectTimer);+ if (socket) {+ // Drop the handlers first so the teardown close doesn't look like a+ // dropped connection and schedule a reconnect for a book we left.+ socket.onclose = null;+ socket.onerror = null;+ socket.onmessage = null;+ try {+ socket.close();+ } catch {+ // Already closing — nothing to do.+ }+ }+ };+ }, [bookId]);+}++/** Normalized `kind` for a book event, wherever the backend put it. */+export function bookEventKind(event: BookWsEvent): string {+ const metadata = (event.metadata as Record<string, unknown> | undefined) || {};+ return String(metadata.kind || event.content || "");+}++/** The page a book event refers to, or `null` for book-level events. */+export function bookEventPageId(event: BookWsEvent): string | null {+ const metadata = (event.metadata as Record<string, unknown> | undefined) || {};+ const pageId = metadata.page_id;+ return typeof pageId === "string" && pageId ? pageId : null;+}diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 7f0c55a75..37aa4bb0b 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -2537,12 +2537,16 @@"Text-only": "Text-only","Built-in plain text extraction for PDF, Office, and text files. No optional parser package, model download, OCR, or layout reconstruction.": "Built-in plain text extraction for PDF, Office, and text files. No optional parser package, model download, OCR, or layout reconstruction.","Knowledge Center": "Knowledge Center",- "Connect per knowledge base": "Connect per knowledge base",- "Configured per knowledge base": "Configured per knowledge base",- "Connect each Tencent IMA knowledge base with its own Client ID and API key. Retrieval is read-only and loads bounded source text when IMA omits a matched snippet.": "Connect each Tencent IMA knowledge base with its own Client ID and API key. Retrieval is read-only and loads bounded source text when IMA omits a matched snippet.",+ "Hosted engine: the library lives in Tencent IMA and DeepTutor keeps no copy. Requires an IMA Client ID and API key; retrieval is read-only and loads bounded source text when IMA omits a matched snippet.": "Hosted engine: the library lives in Tencent IMA and DeepTutor keeps no copy. Requires an IMA Client ID and API key; retrieval is read-only and loads bounded source text when IMA omits a matched snippet.",+ "One IMA account reaches every library in it, so this pair is shared by all your Tencent IMA knowledge bases. Connecting one then only asks which library to point at. A knowledge base can still carry its own credentials to reach a second account.": "One IMA account reaches every library in it, so this pair is shared by all your Tencent IMA knowledge bases. Connecting one then only asks which library to point at. A knowledge base can still carry its own credentials to reach a second account.",+ "Enter your IMA Client ID": "Enter your IMA Client ID",+ "Enter your IMA API key": "Enter your IMA API key","DeepTutor searches IMA and loads bounded source text when a match has no snippet. It never writes to IMA.": "DeepTutor searches IMA and loads bounded source text when a match has no snippet. It never writes to IMA.","Client ID": "Client ID",- "Create these credentials on the Tencent IMA agent interface.": "Create these credentials on the Tencent IMA agent interface.",+ "Using the IMA credentials configured for this engine in the Knowledge Center.": "Using the IMA credentials configured for this engine in the Knowledge Center.",+ "Use other credentials": "Use other credentials",+ "Use the engine's credentials instead": "Use the engine's credentials instead",+ "Set these once for the engine in the Knowledge Center to skip this step next time.": "Set these once for the engine in the Knowledge Center to skip this step next time.","Open IMA": "Open IMA","Choose from knowledge base list": "Choose from knowledge base list","Use knowledge base ID instead": "Use knowledge base ID instead",@@ -2552,8 +2556,8 @@"Verify knowledge base": "Verify knowledge base","Knowledge base verified": "Knowledge base verified","Read only": "Read only",- "Credentials supplied when connecting a knowledge base": "Credentials supplied when connecting a knowledge base",- "Enter the IMA Client ID and API key in the link-existing flow.": "Enter the IMA Client ID and API key in the link-existing flow.",+ "IMA Client ID and API key configured": "IMA Client ID and API key configured",+ "Add them under Credentials, or supply a pair per knowledge base when connecting one.": "Add them under Credentials, or supply a pair per knowledge base when connecting one.","Retrieval profile": "Retrieval profile","Credentials": "Credentials","Requirements": "Requirements",@@ -3039,5 +3043,32 @@"Adding…": "Adding…","Could not add extra practice: {{message}}": "Could not add extra practice: {{message}}","Compile failed: {{message}}": "Compile failed: {{message}}",- "Regenerate block failed: {{message}}": "Regenerate block failed: {{message}}"+ "Regenerate block failed: {{message}}": "Regenerate block failed: {{message}}",+ "planning": "planning",+ "generating": "generating",+ "partial": "partial",+ "paused": "paused",+ "Draft": "Draft",+ "Outline": "Outline",+ "Paused": "Paused",+ "Brief": "Brief",+ "Roughly half the prose per chapter — a fast orientation.": "Roughly half the prose per chapter — a fast orientation.",+ "The default balance of explanation, examples and practice.": "The default balance of explanation, examples and practice.",+ "Longer treatments with more worked detail. Takes noticeably longer.": "Longer treatments with more worked detail. Takes noticeably longer.",+ "Flash cards": "Flash cards",+ "Deep dive": "Deep dive",+ "Concept graph": "Concept graph",+ "Previous chapter": "Previous chapter",+ "Next chapter": "Next chapter",+ "Got it right": "Got it right",+ "Rebuilding…": "Rebuilding…",+ "Click again to rebuild": "Click again to rebuild",+ "Replaces every generated chapter and clears your reading progress, bookmarks, notes and edits.": "Replaces every generated chapter and clears your reading progress, bookmarks, notes and edits.",+ "Click again to delete this block": "Click again to delete this block",+ "{{action}} failed: {{reason}}": "{{action}} failed: {{reason}}",+ "Open the chapter this created": "Open the chapter this created",+ "Generate a chapter on this": "Generate a chapter on this",+ "This book was written without reading your sources.": "This book was written without reading your sources.",+ "Retrieval failed while planning it, so the chapters come from the proposal alone. Rebuilding will try your knowledge bases again.": "Retrieval failed while planning it, so the chapters come from the proposal alone. Rebuilding will try your knowledge bases again.",+ "Source sweep failed": "Source sweep failed"}diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex ad11a5227..2063b39dd 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -1151,7 +1151,7 @@"Learning Path": "学习路径","Quick": "快速","Standard": "标准",- "Deep": "深度",+ "Deep": "详尽","Manual": "手动","Round {{n}}": "第 {{n}} 轮","Step {{n}}": "第 {{n}} 步",@@ -2537,12 +2537,16 @@"Text-only": "仅文本","Built-in plain text extraction for PDF, Office, and text files. No optional parser package, model download, OCR, or layout reconstruction.": "内置纯文本提取,支持 PDF、Office 和文本文件。无需可选解析包、模型下载、OCR 或版面重建。","Knowledge Center": "知识中心",- "Connect per knowledge base": "按知识库连接",- "Configured per knowledge base": "按知识库配置",- "Connect each Tencent IMA knowledge base with its own Client ID and API key. Retrieval is read-only and loads bounded source text when IMA omits a matched snippet.": "每个腾讯 IMA 知识库都使用各自的 Client ID 和 API 密钥进行连接。检索为只读模式,并在 IMA 未返回命中片段时限量读取原文。",+ "Hosted engine: the library lives in Tencent IMA and DeepTutor keeps no copy. Requires an IMA Client ID and API key; retrieval is read-only and loads bounded source text when IMA omits a matched snippet.": "托管引擎:知识库存放在腾讯 IMA,DeepTutor 不保留副本。需配置 IMA Client ID 和 API 密钥;检索为只读,并在 IMA 未返回命中片段时限量读取原文。",+ "One IMA account reaches every library in it, so this pair is shared by all your Tencent IMA knowledge bases. Connecting one then only asks which library to point at. A knowledge base can still carry its own credentials to reach a second account.": "一个 IMA 账号可访问其名下所有知识库,因此这组凭证由你全部的腾讯 IMA 知识库共用。之后连接知识库时只需选择指向哪个库。单个知识库仍可填写自己的凭证以连接另一个账号。",+ "Enter your IMA Client ID": "输入你的 IMA Client ID",+ "Enter your IMA API key": "输入你的 IMA API 密钥","DeepTutor searches IMA and loads bounded source text when a match has no snippet. It never writes to IMA.": "DeepTutor 会检索 IMA,并在命中结果缺少片段时限量读取原文;不会向 IMA 写入内容。","Client ID": "Client ID",- "Create these credentials on the Tencent IMA agent interface.": "请在腾讯 IMA 智能体接口中创建这些凭据。",+ "Using the IMA credentials configured for this engine in the Knowledge Center.": "正在使用知识中心里为该引擎配置的 IMA 凭证。",+ "Use other credentials": "使用其他凭证",+ "Use the engine's credentials instead": "改用引擎配置的凭证",+ "Set these once for the engine in the Knowledge Center to skip this step next time.": "在知识中心为该引擎配置一次,下次即可跳过这一步。","Open IMA": "打开 IMA","Choose from knowledge base list": "从知识库列表选择","Use knowledge base ID instead": "改用知识库 ID",@@ -2552,8 +2556,8 @@"Verify knowledge base": "验证知识库","Knowledge base verified": "知识库验证成功","Read only": "只读",- "Credentials supplied when connecting a knowledge base": "连接知识库时提供凭据",- "Enter the IMA Client ID and API key in the link-existing flow.": "请在“关联已有”流程中输入 IMA Client ID 和 API 密钥。",+ "IMA Client ID and API key configured": "已配置 IMA Client ID 和 API 密钥",+ "Add them under Credentials, or supply a pair per knowledge base when connecting one.": "请在“凭证”中填写,或在连接知识库时单独提供一组。","Retrieval profile": "检索画像","Credentials": "凭证","Requirements": "环境要求",@@ -3005,7 +3009,7 @@"Only the backend and its own children. Start DeepTutor through the launcher to include the web server.": "仅统计后端及其子进程。通过 DeepTutor 启动器运行才能把前端服务一起算进来。","Generate all chapters": "生成全部章节","First chapter only": "只生成第一章",- "Confirm spine": "确认大纲",+ "Confirm spine": "确认主线","Chapters will be generated the first time you open them — useful when you want to read as you go, or keep an eye on model usage.": "章节会在你第一次打开时生成——适合边读边生成,或者想控制模型用量的场景。","~{{count}} words": "约 {{count}} 字","~{{count}} min to generate": "预计生成 {{count}} 分钟",@@ -3039,5 +3043,32 @@"Adding…": "正在生成…","Could not add extra practice: {{message}}": "补充练习失败:{{message}}","Compile failed: {{message}}": "生成失败:{{message}}",- "Regenerate block failed: {{message}}": "重新生成模块失败:{{message}}"+ "Regenerate block failed: {{message}}": "重新生成模块失败:{{message}}",+ "planning": "规划中",+ "generating": "生成中",+ "partial": "部分完成",+ "paused": "已暂停",+ "Draft": "草稿",+ "Outline": "大纲",+ "Paused": "已暂停",+ "Brief": "精简",+ "Roughly half the prose per chapter — a fast orientation.": "每章篇幅约为一半,快速建立整体认识。",+ "The default balance of explanation, examples and practice.": "讲解、示例与练习的默认配比。",+ "Longer treatments with more worked detail. Takes noticeably longer.": "更长的展开与更多推演细节,生成时间明显更久。",+ "Flash cards": "记忆卡",+ "Deep dive": "深入",+ "Concept graph": "概念图",+ "Previous chapter": "上一章",+ "Next chapter": "下一章",+ "Got it right": "答对了",+ "Rebuilding…": "正在重建…",+ "Click again to rebuild": "再点一次确认重建",+ "Replaces every generated chapter and clears your reading progress, bookmarks, notes and edits.": "会替换所有已生成的章节,并清空阅读进度、书签、笔记和你的修改。",+ "Click again to delete this block": "再点一次删除此模块",+ "{{action}} failed: {{reason}}": "{{action}}失败:{{reason}}",+ "Open the chapter this created": "打开由此生成的章节",+ "Generate a chapter on this": "就此生成一章",+ "This book was written without reading your sources.": "这本书生成时没有读取你的资料来源。",+ "Retrieval failed while planning it, so the chapters come from the proposal alone. Rebuilding will try your knowledge bases again.": "规划阶段检索失败,因此各章仅基于方案生成。重建会重新尝试读取你的知识库。",+ "Source sweep failed": "来源扫描失败"}diff --git a/web/tests/build-wrapper.test.ts b/web/tests/build-wrapper.test.tsindex a54fb01a5..92154c6b2 100644--- a/web/tests/build-wrapper.test.ts+++ b/web/tests/build-wrapper.test.ts@@ -24,7 +24,11 @@ test("the build wrapper restores every generated checked-in input", () => {`wrapper must snapshot ${name}`,);}- assert.match(source, /restoreAll\(snapshots\)/, "wrapper must restore snapshots");+ assert.match(+ source,+ /restoreAll\(snapshots\)/,+ "wrapper must restore snapshots",+ );assert.match(source,/stdio: "inherit"/,diff --git a/web/tests/chat-launch-intent.test.ts b/web/tests/chat-launch-intent.test.tsnew file mode 100644index 000000000..a6b587063--- /dev/null+++ b/web/tests/chat-launch-intent.test.ts@@ -0,0 +1,43 @@+import test from "node:test";+import assert from "node:assert/strict";++import {+ newMasteryPathChatUrl,+ readChatLaunchIntent,+} from "../lib/chat-launch-intent";++test("continuing a mastery path opens a fresh associated chat", () => {+ assert.equal(+ newMasteryPathChatUrl("calculus/path 1"),+ "/home?capability=mastery_path&mastery_path_id=calculus%2Fpath+1",+ );+});++test("the mastery continue URL round-trips into a launch intent", () => {+ const url = newMasteryPathChatUrl("calculus/path 1");+ const intent = readChatLaunchIntent(url.slice(url.indexOf("?")));+ assert.equal(intent.capability, "mastery_path");+ assert.equal(intent.masteryPathId, "calculus/path 1");+ assert.deepEqual(intent.tools, []);+});++test("an absent capability stays unspecified, an empty one means plain chat", () => {+ assert.equal(readChatLaunchIntent("?tool=web_search").capability, null);+ assert.equal(readChatLaunchIntent("?capability=").capability, "");+});++test("tools are collected verbatim for the caller to validate", () => {+ assert.deepEqual(+ readChatLaunchIntent("?tool=web_search&tool=+reason+").tools,+ ["web_search", "reason"],+ );+});++test("a blank mastery path id is dropped rather than bound", () => {+ assert.equal(readChatLaunchIntent("?mastery_path_id=%20%20").masteryPathId, null);+ assert.deepEqual(readChatLaunchIntent(""), {+ capability: null,+ tools: [],+ masteryPathId: null,+ });+});diff --git a/web/tests/ima-connection.test.ts b/web/tests/ima-connection.test.tsindex f03e9b49f..bc55d98aa 100644--- a/web/tests/ima-connection.test.ts+++ b/web/tests/ima-connection.test.ts@@ -40,7 +40,10 @@ test("leaving the IMA source clears credentials from the mounted flow", () => {);assert.match(hookSource, /setClientId\(""\);\s+setApiKey\(""\);/);- assert.match(modalSource, /const handleClose = \(\) => {\s+imaConnection\.reset\(\);/);+ assert.match(+ modalSource,+ /const handleClose = \(\) => {\s+imaConnection\.reset\(\);/,+ );assert.match(modalSource,/if \(source !== IMA_PROVIDER\) imaConnection\.reset\(\);/,@@ -93,22 +96,41 @@ test("automatic IMA connection requires credentials and a selected id", () => {name: "Notes",clientId: "cid",apiKey: "key",+ credentialsReady: true,selectedId: "kb-1",manualKnowledgeBaseId: "",manualVerification: null,};assert.equal(canConnectIma(base), true);- assert.equal(canConnectIma({ ...base, clientId: "" }), false);+ assert.equal(canConnectIma({ ...base, credentialsReady: false }), false);assert.equal(canConnectIma({ ...base, selectedId: "" }), false);});+test("the account credential pair connects without any typed credentials", () => {+ // Nothing is typed and nothing is sent — the server resolves the pair.+ assert.equal(+ canConnectIma({+ mode: "automatic",+ name: "Notes",+ clientId: "",+ apiKey: "",+ credentialsReady: true,+ selectedId: "kb-1",+ manualKnowledgeBaseId: "",+ manualVerification: null,+ }),+ true,+ );+});+test("manual IMA connection accepts only the current verified credential tuple", () => {const base = {mode: "manual" as const,name: "Notes",clientId: "cid",apiKey: "key",+ credentialsReady: true,selectedId: "",manualKnowledgeBaseId: "kb-1",manualVerification: {diff --git a/web/tests/knowledge-helpers.test.ts b/web/tests/knowledge-helpers.test.tsindex 953360a43..6cbfe64f0 100644--- a/web/tests/knowledge-helpers.test.ts+++ b/web/tests/knowledge-helpers.test.ts@@ -135,10 +135,23 @@ test("taskFailureMessage keeps trace details out of the primary error", () => {);});-test("IMA is connected per knowledge base instead of globally ready", () => {+test("engine status follows the credential and install state", () => {+ // IMA holds one account credential pair, like PageIndex.assert.equal(- providerConnectionStatus({ id: "ima", configured: true }),- "per_kb",+ providerConnectionStatus({+ id: "ima",+ configured: false,+ requires_api_key: true,+ }),+ "needs_key",+ );+ assert.equal(+ providerConnectionStatus({+ id: "ima",+ configured: true,+ requires_api_key: true,+ }),+ "ready",);assert.equal(providerConnectionStatus({ id: "llamaindex", configured: true }),diff --git a/web/tests/llm-options-transport.test.ts b/web/tests/llm-options-transport.test.tsindex 738f614a0..4560b4fd6 100644--- a/web/tests/llm-options-transport.test.ts+++ b/web/tests/llm-options-transport.test.ts@@ -1,10 +1,7 @@import assert from "node:assert/strict";import test from "node:test";-import {- invalidateLLMOptionsCache,- listLLMOptions,-} from "../lib/llm-options";+import { invalidateLLMOptionsCache, listLLMOptions } from "../lib/llm-options";test("a timed-out model catalog request can be retried", async () => {const originalFetch = globalThis.fetch;@@ -32,7 +29,8 @@ test("a timed-out model catalog request can be retried", async () => {try {await assert.rejects(listLLMOptions({ force: true, timeoutMs: 5 }),- (error: unknown) => error instanceof DOMException && error.name === "AbortError",+ (error: unknown) =>+ error instanceof DOMException && error.name === "AbortError",);const result = await listLLMOptions({ force: true, timeoutMs: 50 });assert.deepEqual(result, { active: null, options: [] });diff --git a/web/tests/mastery-path-activity.test.ts b/web/tests/mastery-path-activity.test.tsnew file mode 100644index 000000000..dc1a6f3e7--- /dev/null+++ b/web/tests/mastery-path-activity.test.ts@@ -0,0 +1,71 @@+import test from "node:test";+import assert from "node:assert/strict";++import {+ EMPTY_FEED,+ latestRevision,+ mergeEventBatch,+ type ActivityFeed,+} from "../hooks/useMasteryPathActivity";+import type { MasteryEvent } from "../lib/learning-api";++function event(revision: number, eventType = "attempt.recorded"): MasteryEvent {+ return {+ id: revision,+ revision,+ event_type: eventType,+ payload: {},+ session_id: "",+ turn_id: "",+ created_at: revision,+ };+}++function feed(pathId: string, revisions: number[]): ActivityFeed {+ return {+ pathId,+ events: revisions.map((r) => event(r)),+ revision: Math.max(0, ...revisions),+ };+}++test("an incremental batch appends and advances the cursor", () => {+ const merged = mergeEventBatch(feed("p1", [1, 2]), "p1", 2, [event(3), event(4)]);+ assert.deepEqual(+ merged.events.map((e) => e.revision),+ [1, 2, 3, 4],+ );+ assert.equal(merged.revision, 4);+});++test("a read from revision 0 replaces, so a forced refresh cannot double the feed", () => {+ const merged = mergeEventBatch(feed("p1", [1, 2, 3]), "p1", 0, [+ event(1),+ event(2),+ event(3),+ ]);+ assert.deepEqual(+ merged.events.map((e) => e.revision),+ [1, 2, 3],+ );+});++test("an empty batch leaves the feed untouched", () => {+ const before = feed("p1", [1, 2]);+ assert.equal(mergeEventBatch(before, "p1", 2, []), before);+ assert.equal(mergeEventBatch(EMPTY_FEED, "p1", 0, []), EMPTY_FEED);+});++test("a batch for another path never mixes into the previous path's history", () => {+ const merged = mergeEventBatch(feed("p1", [1, 2, 3]), "p2", 0, [event(1)]);+ assert.equal(merged.pathId, "p2");+ assert.deepEqual(+ merged.events.map((e) => e.revision),+ [1],+ );+});++test("the cursor never moves backwards past what was already requested", () => {+ assert.equal(latestRevision(7, []), 7);+ assert.equal(latestRevision(7, [event(9), event(8)]), 9);+});diff --git a/web/tests/mastery-path-navigation.test.ts b/web/tests/mastery-path-navigation.test.tsdeleted file mode 100644index 93e2bfbc2..000000000--- a/web/tests/mastery-path-navigation.test.ts+++ /dev/null@@ -1,11 +0,0 @@-import test from "node:test";-import assert from "node:assert/strict";--import { newMasteryPathChatUrl } from "../lib/mastery-path-navigation";--test("continuing a mastery path opens a fresh associated chat", () => {- assert.equal(- newMasteryPathChatUrl("calculus/path 1"),- "/home?capability=mastery_path&mastery_path_id=calculus%2Fpath+1",- );-});diff --git a/web/tests/reconnecting-websocket.test.ts b/web/tests/reconnecting-websocket.test.tsindex 548cfbec2..b7e885817 100644--- a/web/tests/reconnecting-websocket.test.ts+++ b/web/tests/reconnecting-websocket.test.ts@@ -1,163 +1,173 @@-import test from 'node:test'-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import path from 'node:path'-import { ReconnectingWebSocket, reconnectDelayMs } from '../lib/reconnecting-websocket'+import test from "node:test";+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import path from "node:path";+import {+ ReconnectingWebSocket,+ reconnectDelayMs,+} from "../lib/reconnecting-websocket";class FakeSocket {- readyState = 0- sent: string[] = []- onopen: ((event: Event) => void) | null = null- onmessage: ((event: MessageEvent) => void) | null = null- onerror: ((event: Event) => void) | null = null- onclose: ((event: CloseEvent) => void) | null = null+ readyState = 0;+ sent: string[] = [];+ onopen: ((event: Event) => void) | null = null;+ onmessage: ((event: MessageEvent) => void) | null = null;+ onerror: ((event: Event) => void) | null = null;+ onclose: ((event: CloseEvent) => void) | null = null;open(): void {- this.readyState = 1- this.onopen?.({} as Event)+ this.readyState = 1;+ this.onopen?.({} as Event);}drop(): void {- this.readyState = 3- this.onclose?.({} as CloseEvent)+ this.readyState = 3;+ this.onclose?.({} as CloseEvent);}close(): void {- if (this.readyState !== 3) this.drop()+ if (this.readyState !== 3) this.drop();}send(payload: string): void {- this.sent.push(payload)+ this.sent.push(payload);}}function createHarness(shouldReconnect: () => boolean = () => true) {- const sockets: FakeSocket[] = []+ const sockets: FakeSocket[] = [];const scheduled: Array<{- callback: () => void- delayMs: number- cancelled: boolean- }> = []- let now = 0+ callback: () => void;+ delayMs: number;+ cancelled: boolean;+ }> = [];+ let now = 0;const client = new ReconnectingWebSocket(- 'ws://partner.test',+ "ws://partner.test",{ onMessage: () => {} },{createSocket: () => {- const socket = new FakeSocket()- sockets.push(socket)- return socket as unknown as WebSocket+ const socket = new FakeSocket();+ sockets.push(socket);+ return socket as unknown as WebSocket;},shouldReconnect,now: () => now,scheduler: {set: (callback, delayMs) => {- const task = { callback, delayMs, cancelled: false }- scheduled.push(task)- return task+ const task = { callback, delayMs, cancelled: false };+ scheduled.push(task);+ return task;},- clear: handle => {- ;(handle as (typeof scheduled)[number]).cancelled = true+ clear: (handle) => {+ (handle as (typeof scheduled)[number]).cancelled = true;},},- }- )+ },+ );return {client,sockets,scheduled,setNow: (value: number) => {- now = value+ now = value;},- }+ };}-test('reconnect delay grows exponentially and remains bounded', () => {+test("reconnect delay grows exponentially and remains bounded", () => {assert.deepEqual(- [0, 1, 2, 3, 8].map(attempt => reconnectDelayMs(attempt, 250, 2_000)),- [250, 500, 1_000, 2_000, 2_000]- )-})--test('unexpected closes reconnect without creating concurrent sockets', () => {- const { client, sockets, scheduled } = createHarness()- client.start()- client.start()- assert.equal(sockets.length, 1)-- sockets[0].open()- sockets[0].drop()- assert.equal(scheduled[0].delayMs, 250)-- scheduled[0].callback()- assert.equal(sockets.length, 2)- sockets[1].drop()- assert.equal(scheduled[1].delayMs, 500)-})--test('wake reconnects immediately when a hidden page becomes active', () => {- let active = true- const { client, sockets, scheduled } = createHarness(() => active)- client.start()- sockets[0].open()- active = false- sockets[0].drop()- assert.equal(scheduled.length, 0, 'hidden pages should not spin retry timers')-- active = true- client.wake()- assert.equal(sockets.length, 2)-})--test('a retry timer that fires in the background waits for wake', () => {- let active = true- const { client, sockets, scheduled } = createHarness(() => active)- client.start()- sockets[0].open()- sockets[0].drop()-- active = false- scheduled[0].callback()- assert.equal(sockets.length, 1)-- active = true- client.wake()- assert.equal(sockets.length, 2)-})--test('wake replaces only a stale connecting socket', () => {- const { client, sockets, setNow } = createHarness()- client.start()- setNow(9_999)- client.wake()- assert.equal(sockets.length, 1)-- setNow(10_001)- client.wake()- assert.equal(sockets.length, 2)- assert.equal(sockets[0].readyState, 3)-})--test('stop cancels pending retries and closes without reconnecting', () => {- const { client, sockets, scheduled } = createHarness()- client.start()- sockets[0].open()- sockets[0].drop()- client.stop()-- assert.equal(scheduled[0].cancelled, true)- scheduled[0].callback()- assert.equal(sockets.length, 1)-})--test('partner composer restores focus after streaming and page return', () => {+ [0, 1, 2, 3, 8].map((attempt) => reconnectDelayMs(attempt, 250, 2_000)),+ [250, 500, 1_000, 2_000, 2_000],+ );+});++test("unexpected closes reconnect without creating concurrent sockets", () => {+ const { client, sockets, scheduled } = createHarness();+ client.start();+ client.start();+ assert.equal(sockets.length, 1);++ sockets[0].open();+ sockets[0].drop();+ assert.equal(scheduled[0].delayMs, 250);++ scheduled[0].callback();+ assert.equal(sockets.length, 2);+ sockets[1].drop();+ assert.equal(scheduled[1].delayMs, 500);+});++test("wake reconnects immediately when a hidden page becomes active", () => {+ let active = true;+ const { client, sockets, scheduled } = createHarness(() => active);+ client.start();+ sockets[0].open();+ active = false;+ sockets[0].drop();+ assert.equal(+ scheduled.length,+ 0,+ "hidden pages should not spin retry timers",+ );++ active = true;+ client.wake();+ assert.equal(sockets.length, 2);+});++test("a retry timer that fires in the background waits for wake", () => {+ let active = true;+ const { client, sockets, scheduled } = createHarness(() => active);+ client.start();+ sockets[0].open();+ sockets[0].drop();++ active = false;+ scheduled[0].callback();+ assert.equal(sockets.length, 1);++ active = true;+ client.wake();+ assert.equal(sockets.length, 2);+});++test("wake replaces only a stale connecting socket", () => {+ const { client, sockets, setNow } = createHarness();+ client.start();+ setNow(9_999);+ client.wake();+ assert.equal(sockets.length, 1);++ setNow(10_001);+ client.wake();+ assert.equal(sockets.length, 2);+ assert.equal(sockets[0].readyState, 3);+});++test("stop cancels pending retries and closes without reconnecting", () => {+ const { client, sockets, scheduled } = createHarness();+ client.start();+ sockets[0].open();+ sockets[0].drop();+ client.stop();++ assert.equal(scheduled[0].cancelled, true);+ scheduled[0].callback();+ assert.equal(sockets.length, 1);+});++test("partner composer restores focus after streaming and page return", () => {const source = readFileSync(- path.resolve(process.cwd(), 'components/partners/PartnerComposer.tsx'),- 'utf8'- )-- assert.match(source, /restoreFocusAfterSendRef\.current = true/)- assert.match(source, /if \(disabled \|\| streaming/)- assert.match(source, /window\.addEventListener\("blur", rememberFocus\)/)- assert.match(source, /document\.addEventListener\("visibilitychange", restoreFocus\)/)-})+ path.resolve(process.cwd(), "components/partners/PartnerComposer.tsx"),+ "utf8",+ );++ assert.match(source, /restoreFocusAfterSendRef\.current = true/);+ assert.match(source, /if \(disabled \|\| streaming/);+ assert.match(source, /window\.addEventListener\("blur", rememberFocus\)/);+ assert.match(+ source,+ /document\.addEventListener\("visibilitychange", restoreFocus\)/,+ );+});