Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

prepare v1.3.4 release

Bingxi Zhao (Frank)144c90f3f70a
diff --git a/CLAUDE.md b/CLAUDE.md
deleted file mode 100644
index e69de29bb..000000000
diff --git a/README.md b/README.md
index 68a56ef0a..1b515cc50 100644
--- a/README.md
+++ b/README.md
@@ -10,7 +10,7 @@
[![Next.js 16](https://img.shields.io/badge/Next.js-16-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue?style=flat-square)](LICENSE)
[![GitHub release](https://img.shields.io/github/v/release/HKUDS/DeepTutor?style=flat-square&color=brightgreen)](https://github.com/HKUDS/DeepTutor/releases)
-[![arXiv](https://img.shields.io/badge/arXiv-Coming_Soon-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](#)
+[![arXiv](https://img.shields.io/badge/arXiv-2604.26962-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](https://arxiv.org/abs/2604.26962)
[![Discord](https://img.shields.io/badge/Discord-Community-5865F2?style=flat-square&logo=discord&logoColor=white)](https://discord.gg/eRsjPgMU4t)
[![Feishu](https://img.shields.io/badge/Feishu-Group-00D4AA?style=flat-square&logo=feishu&logoColor=white)](./Communication.md)
@@ -28,6 +28,8 @@
### 📦 Releases
+> **[2026.5.1]** [v1.3.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.4) — Book page chat persistence and rebuild flows, chat-to-book references, stronger language/reasoning handling, RAG document extraction hardening.
+
> **[2026.4.30]** [v1.3.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.3) — NVIDIA NIM + Gemini embedding support, unified Space context for chat history/skills/memory, session snapshots, RAG re-index resilience.
> **[2026.4.29]** [v1.3.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.2) — Transparent embedding endpoint URLs, RAG re-index resilience for invalid persisted vectors, memory cleanup for thinking-model output, Deep Solve runtime fix.
@@ -91,6 +93,8 @@
> **[2026.4.19]** 🎉 We've reached 20k stars after 111 days! Thank you for the incredible support — we're committed to continuous iteration toward truly personalized, intelligent tutoring for everyone.
+> **[2026.4.10]** 📄 Our paper is now live on arXiv! Read the [preprint](https://arxiv.org/abs/2604.26962) to learn more about the design and ideas behind DeepTutor.
+
> **[2026.4.4]** Long time no see! ✨ DeepTutor v1.0.0 is finally here — an agent-native evolution featuring a ground-up architecture rewrite, TutorBot, and flexible mode switching under the Apache-2.0 license. A new chapter begins, and our story continues!
> **[2026.2.6]** 🚀 We've reached 10k stars in just 39 days! A huge thank you to our incredible community for the support!
diff --git a/assets/README/README_AR.md b/assets/README/README_AR.md
index 00be72623..0c873a765 100644
--- a/assets/README/README_AR.md
+++ b/assets/README/README_AR.md
@@ -10,7 +10,7 @@
[![Next.js 16](https://img.shields.io/badge/Next.js-16-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue?style=flat-square)](../../LICENSE)
[![GitHub release](https://img.shields.io/github/v/release/HKUDS/DeepTutor?style=flat-square&color=brightgreen)](https://github.com/HKUDS/DeepTutor/releases)
-[![arXiv](https://img.shields.io/badge/arXiv-Coming_Soon-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](#)
+[![arXiv](https://img.shields.io/badge/arXiv-2604.26962-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](https://arxiv.org/abs/2604.26962)
[![Discord](https://img.shields.io/badge/Discord-Community-5865F2?style=flat-square&logo=discord&logoColor=white)](https://discord.gg/eRsjPgMU4t)
[![Feishu](https://img.shields.io/badge/Feishu-Group-00D4AA?style=flat-square&logo=feishu&logoColor=white)](../../Communication.md)
@@ -18,7 +18,7 @@
[الميزات](#key-features) · [البدء](#get-started) · [استكشاف](#explore-deeptutor) · [TutorBot](#tutorbot) · [CLI](#deeptutor-cli-guide) · [خارطة الطريق](#roadmap) · [المجتمع](#community)
-[🇬🇧 English](../../README.md) · [🇨🇳 中文](README_CN.md) · [🇯🇵 日本語](README_JA.md) · [🇪🇸 Español](README_ES.md) · [🇫🇷 Français](README_FR.md) · [🇷🇺 Русский](README_RU.md) · [🇮🇳 हिन्दी](README_HI.md) · [🇵🇹 Português](README_PT.md) · [🇹🇭 ภาษาไทย](README_TH.md)
+[🇬🇧 English](../../README.md) · [🇨🇳 中文](README_CN.md) · [🇯🇵 日本語](README_JA.md) · [🇪🇸 Español](README_ES.md) · [🇫🇷 Français](README_FR.md) · [🇷🇺 Русский](README_RU.md) · [🇮🇳 हिन्दी](README_HI.md) · [🇵🇹 Português](README_PT.md) · [🇹🇭 ภาษาไทย](README_TH.md) · 🇵🇱 [Polski](README_PL.md)
</div>
@@ -28,17 +28,33 @@
### 📦 الإصدارات
-> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — مرفقات مستندات في الدردشة (PDF/DOCX/XLSX/PPTX)، عرض كتلة تفكير نموذج التفكير، مفتاح `send_dimensions` ثلاثي الحالات لـ embedding، إعادة هيكلة نواة مزوّدي LLM، محرّر قوالب Soul، حفظ Co-Writer في الدفتر، سحب وإفلات في قاعدة المعرفة ومرونة الحذف، وضبط لغة توليد الأسئلة.
+> **[2026.4.30]** [v1.3.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.3) — دعم تضمين NVIDIA NIM وGemini، سياق Space موحّد لسجل الدردشة / المهارات / الذاكرة، لقطات الجلسة، مرونة إعادة فهرسة RAG.
-> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — نظام Skills من إنشاء المستخدم (CRUD + تكامل مع الدردشة)، تحسين أداء إدخال الدردشة مع وضع الحالة، تراجع تلقائي لـ `response_format` عند مزوّدين غير متوافقين، إصلاح الوصول البعيد عبر LAN، شارة إصدار في الشريط الجانبي، مرفقات صور في Deep Solve، بدء تلقائي لـ WebSocket لـ TutorBot، واجهة مكتبة الكتب، ووضع ملء الشاشة للتصوّر.
+> **[2026.4.29]** [v1.3.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.2) — عناوين URL شفافة لنقاط نهاية التضمين، مرونة إعادة فهرسة RAG للمتجهات المخزّنة غير الصالحة، تنظيف الذاكرة لمخرجات نماذج التفكير، إصلاح وقت تشغيل Deep Solve.
-> **[2026.4.21]** [v1.2.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.1) — حدود رموز لكل مرحلة في `agents.yaml` (ردود 8000 رمز)، إعادة توليد آخر رد عبر CLI / WebSocket / واجهة الويب، إصلاح تعطل RAG عند تضمينات `None`، توافق Gemma مع `json_object`، وقراءة أفضل لكتل الشيفرة الداكنة.
+> **[2026.4.28]** [v1.3.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.1) — الاستقرار: توجيه RAG أكثر أمانًا والتحقق من التضمين، استمرارية Docker، إدخال آمن مع IME، قوة على Windows/GBK.
-> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — Book Engine: مُجمّع «كتب حية» متعدد الوكلاء بـ 14 نوع كتل، مساحة عمل Co-Writer متعددة المستندات، تصورات HTML تفاعلية، إشارات @ لبنك الأسئلة في الدردشة، المرحلة الثانية لإخراج المطالبات، وإعادة تصميم الشريط الجانبي.
+> **[2026.4.27]** [v1.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.0) — فهارس KB ذات إصدار مع سير إعادة الفهرسة، إعادة بناء مساحة المعرفة، اكتشاف تلقائي للتضمين مع محولات جديدة، مركز Space.
-> **[2026.4.18]** [v1.1.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.2) — تبويب القنوات المستند إلى المخطط مع إخفاء الأسرار؛ دمج RAG في مسار واحد؛ تعزيز اتساق RAG/قواعد المعرفة؛ نقل مطالبات الدردشة خارج الكود؛ وREADME التايلاندية.
+> **[2026.4.25]** [v1.2.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.5) — مرفقات دردشة دائمة مع درج معاينة الملفات، خطوط أنابيب قدرات تدرك المرفقات، تصدير Markdown لـ TutorBot.
-> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — «أجب الآن» شامل لجميع القدرات؛ مزامنة تمرير Co-Writer؛ اختيار الرسائل عند الحفظ في الدفتر؛ لوحة إعدادات موحّدة؛ زر إيقاف أثناء البث؛ كتابة إعدادات TutorBot بشكل ذري.
+> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — مرفقات نص / شيفرة / SVG، جولة إعداد بأمر واحد، تصدير الدردشة Markdown، واجهة إدارة KB مدمجة.
+
+> **[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، واجهة مكتبة الكتب، تصور بملء الشاشة.
+
+> **[2026.4.21]** [v1.2.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.1) — حدود رموز لكل مرحلة، إعادة توليد الرد عبر جميع نقاط الدخول، إصلاحات توافق RAG وGemma.
+
+> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — مُجمّع Book Engine ل«كتب حية»، Co-Writer متعدد المستندات، تصورات HTML تفاعلية، إشارات @ لبنك الأسئلة في الدردشة.
+
+> **[2026.4.18]** [v1.1.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.2) — تبويب القنوات المستند إلى المخطط، دمج RAG في مسار واحد، مطالبات الدردشة خارج الكود.
+
+> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — «أجب الآن» شامل، مزامنة تمرير Co-Writer، لوحة إعدادات موحّدة، زر إيقاف أثناء البث.
+
+
+<details>
+<summary><b>إصدارات أقدم (أكثر من أسبوعين)</b></summary>
> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) — إعادة هيكلة تحليل صيغ LaTeX في الكتل؛ فحص تشخيص LLM عبر `agents.yaml`؛ إصلاح تمرير رؤوس HTTP إضافية؛ إصلاح UUID في SaveToNotebook؛ إرشادات Docker وLLM محلي.
@@ -58,9 +74,6 @@
> **[2026.4.4]** [v1.0.0-beta.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.0-beta.1) — إعادة كتابة أصلية للمعمار (‎~200k سطر): نموذج إضافات Tools + Capabilities، وCLI وSDK، وTutorBot، وCo-Writer، وتعليم موجّه، وذاكرة دائمة.
-<details>
-<summary><b>إصدارات سابقة</b></summary>
-
> **[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) — Docling، سجلات، إصلاحات.
@@ -79,6 +92,8 @@
> **[2026.4.19]** 🎉 وصلنا 20k نجمة بعد 111 يومًا! شكرًا لدعمكم — نواصل التطوير نحو تدريس مخصّص وذكي حقًا.
+> **[2026.4.10]** 📄 ورقتنا متاحة الآن على arXiv! اطّلع على [النسخة الأولية](https://arxiv.org/abs/2604.26962) لتعرف التصميم والأفكار وراء DeepTutor.
+
> **[2026.4.4]** منذ زمن غائبين! ✨ DeepTutor v1.0.0 وصل أخيرًا — تطور أصلي للوكلاء مع إعادة بناء المعمار من الصفر وTutorBot وأوضاع مرنة بموجب Apache-2.0. فصل جديد يبدأ!
> **[2026.2.6]** 🚀 10k نجوم في 39 يومًا — شكرًا للمجتمع!
diff --git a/assets/README/README_CN.md b/assets/README/README_CN.md
index 92559c253..c308b127d 100644
--- a/assets/README/README_CN.md
+++ b/assets/README/README_CN.md
@@ -10,7 +10,7 @@
[![Next.js 16](https://img.shields.io/badge/Next.js-16-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue?style=flat-square)](../../LICENSE)
[![GitHub release](https://img.shields.io/github/v/release/HKUDS/DeepTutor?style=flat-square&color=brightgreen)](https://github.com/HKUDS/DeepTutor/releases)
-[![arXiv](https://img.shields.io/badge/arXiv-Coming_Soon-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](#)
+[![arXiv](https://img.shields.io/badge/arXiv-2604.26962-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](https://arxiv.org/abs/2604.26962)
[![Discord](https://img.shields.io/badge/Discord-Community-5865F2?style=flat-square&logo=discord&logoColor=white)](https://discord.gg/eRsjPgMU4t)
[![Feishu](https://img.shields.io/badge/Feishu-Group-00D4AA?style=flat-square&logo=feishu&logoColor=white)](../../Communication.md)
@@ -18,7 +18,7 @@
[核心亮点](#key-features) · [快速开始](#get-started) · [探索 DeepTutor](#explore-deeptutor) · [TutorBot](#tutorbot) · [CLI](#deeptutor-cli-guide) · [路线图](#roadmap) · [社区](#community)
-[🇬🇧 English](../../README.md) · [🇯🇵 日本語](README_JA.md) · [🇪🇸 Español](README_ES.md) · [🇫🇷 Français](README_FR.md) · [🇸🇦 العربية](README_AR.md) · [🇷🇺 Русский](README_RU.md) · [🇮🇳 हिन्दी](README_HI.md) · [🇵🇹 Português](README_PT.md) · [🇹🇭 ภาษาไทย](README_TH.md)
+[🇬🇧 English](../../README.md) · [🇯🇵 日本語](README_JA.md) · [🇪🇸 Español](README_ES.md) · [🇫🇷 Français](README_FR.md) · [🇸🇦 العربية](README_AR.md) · [🇷🇺 Русский](README_RU.md) · [🇮🇳 हिन्दी](README_HI.md) · [🇵🇹 Português](README_PT.md) · [🇹🇭 ภาษาไทย](README_TH.md) · 🇵🇱 [Polski](README_PL.md)
</div>
@@ -28,21 +28,36 @@
### 📦 版本发布
-> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — 聊天内文档附件(PDF/DOCX/XLSX/PPTX)、推理模型思维链块展示、嵌入 `send_dimensions` 三态开关、LLM 提供商核心重构、Soul 模板编辑器、Co-Writer 保存到笔记本、知识库拖放上传与删除韧性、出题语言保真度。
+> **[2026.4.30]** [v1.3.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.3) — NVIDIA NIM 与 Gemini 嵌入支持,统一 Space 上下文(聊天历史 / 技能 / 记忆),会话快照,RAG 重索引韧性。
-> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — 用户自编写 Skills 体系(增删改查 + 聊天集成)、聊天输入性能重构与状态共置、不兼容提供商的 `response_format` 自动回退、局域网远程访问修复、侧栏版本徽章、Deep Solve 图片附件、TutorBot WebSocket 自启动、图书库 UI、可视化全屏模式。
+> **[2026.4.29]** [v1.3.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.2) — 嵌入端点 URL 透明可读,无效持久化向量时 RAG 重索引韧性,思考模型输出记忆清理,Deep Solve 运行时修复。
-> **[2026.4.21]** [v1.2.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.1) — `agents.yaml` 按阶段配置 chat token 上限(8000-token 回复);CLI / WebSocket / Web UI 重新生成上一条回复;RAG `None` 嵌入崩溃修复;Gemma `json_object` 兼容;暗色代码块可读性修复。
+> **[2026.4.28]** [v1.3.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.1) — 稳定性:更安全的 RAG 路由与嵌入校验,Docker 持久化,输入法安全输入,Windows/GBK 健壮性。
-> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — Book Engine 多智能体「活书」编译器(14 种块类型);多文档 Co-Writer 工作区;交互式 HTML 可视化;题库 @-引用进聊天;提示词外置第二阶段;侧栏重构。
+> **[2026.4.27]** [v1.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.0) — 版本化知识库索引与重索引工作流,知识工作区重构,嵌入自动发现与新适配器,Space 中心枢纽。
-> **[2026.4.18]** [v1.1.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.2) — 基于 Schema 的「频道」标签页与密钥脱敏;RAG 收敛为单一流水线;RAG/知识库一致性加固;聊天提示词外置;以及泰语 README。
+> **[2026.4.25]** [v1.2.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.5) — 聊天附件持久化与文件预览抽屉,感知附件的能力流水线,TutorBot Markdown 导出。
-> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — 全能力通用「立即回答」;Co-Writer 滚动同步;保存到笔记本时的消息选择;统一设置面板;流式「停止」按钮;TutorBot 配置原子写入。
+> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — 文本 / 代码 / SVG 附件,一键设置导览,Markdown 聊天导出,紧凑知识库管理界面。
-> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) — LaTeX 块级公式解析重构;通过 `agents.yaml` 的 LLM 诊断探测;额外请求头转发修复;SaveToNotebook UUID 修复;Docker 与本地 LLM 使用说明。
+> **[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.14]** [v1.1.0-beta](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0-beta) — 基于 URL 的可收藏会话;Snow 主题;WebSocket 心跳与自动重连;ChatComposer 性能修复;嵌入提供商注册表重构;Serper 搜索提供商。
+> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — 用户自编写 Skills 体系、聊天输入性能重构、TutorBot 自动启动、图书库 UI、可视化全屏。
+
+> **[2026.4.21]** [v1.2.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.1) — 按阶段 token 上限,各入口重新生成回复,RAG 与 Gemma 兼容性修复。
+
+> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — Book Engine「活书」编译器,多文档 Co-Writer,交互式 HTML 可视化,题库 @-引用。
+
+> **[2026.4.18]** [v1.1.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.2) — 基于 Schema 的 Channels 标签页,RAG 单一流水线收敛,聊天提示词外置。
+
+> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — 全能力「立即回答」,Co-Writer 滚动同步,统一设置面板,流式停止按钮。
+
+<details>
+<summary><b>更早版本(两周以前)</b></summary>
+
+> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) — LaTeX 块级公式解析重构;通过 `agents.yaml` 的 LLM 诊断探测;Docker 与本地 LLM 使用说明。
+
+> **[2026.4.14]** [v1.1.0-beta](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0-beta) — 基于 URL 的可收藏会话;Snow 主题;WebSocket 心跳与自动重连;嵌入提供商注册表重构。
> **[2026.4.13]** [v1.0.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.3) — 带书签与分类的测验笔记本;Visualize 支持 Mermaid;嵌入模型不一致检测;Qwen/vLLM 兼容;LM Studio 与 llama.cpp 支持;Glass 主题。
@@ -58,9 +73,6 @@
> **[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、引导式学习与持久记忆。
-<details>
-<summary><b>历史版本</b></summary>
-
> **[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、日志优化与问题修复。
@@ -79,6 +91,8 @@
> **[2026.4.19]** 🎉 发布 111 天后突破 20k star!感谢大家的支持 —— 我们会持续迭代,朝着真正个性化、智能的辅导不断前进。
+> **[2026.4.10]** 📄 论文已上线 arXiv!欢迎阅读[预印本](https://arxiv.org/abs/2604.26962),了解 DeepTutor 的设计与思路。
+
> **[2026.4.4]** 好久不见!✨ DeepTutor v1.0.0 终于到来 —— 在 Apache-2.0 许可下的智能体原生演进:自底向上架构重写、TutorBot、灵活模式切换。新篇章开启,故事继续!
> **[2026.2.6]** 🚀 仅用 39 天即突破 10k star!感谢社区的大力支持!
diff --git a/assets/README/README_ES.md b/assets/README/README_ES.md
index 331c6651f..c839600af 100644
--- a/assets/README/README_ES.md
+++ b/assets/README/README_ES.md
@@ -10,7 +10,7 @@
[![Next.js 16](https://img.shields.io/badge/Next.js-16-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue?style=flat-square)](../../LICENSE)
[![GitHub release](https://img.shields.io/github/v/release/HKUDS/DeepTutor?style=flat-square&color=brightgreen)](https://github.com/HKUDS/DeepTutor/releases)
-[![arXiv](https://img.shields.io/badge/arXiv-Coming_Soon-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](#)
+[![arXiv](https://img.shields.io/badge/arXiv-2604.26962-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](https://arxiv.org/abs/2604.26962)
[![Discord](https://img.shields.io/badge/Discord-Community-5865F2?style=flat-square&logo=discord&logoColor=white)](https://discord.gg/eRsjPgMU4t)
[![Feishu](https://img.shields.io/badge/Feishu-Group-00D4AA?style=flat-square&logo=feishu&logoColor=white)](../../Communication.md)
@@ -18,7 +18,7 @@
[Funciones](#key-features) · [Primeros pasos](#get-started) · [Explorar](#explore-deeptutor) · [TutorBot](#tutorbot) · [CLI](#deeptutor-cli-guide) · [Hoja de ruta](#roadmap) · [Comunidad](#community)
-[🇬🇧 English](../../README.md) · [🇨🇳 中文](README_CN.md) · [🇯🇵 日本語](README_JA.md) · [🇫🇷 Français](README_FR.md) · [🇸🇦 العربية](README_AR.md) · [🇷🇺 Русский](README_RU.md) · [🇮🇳 हिन्दी](README_HI.md) · [🇵🇹 Português](README_PT.md) · [🇹🇭 ภาษาไทย](README_TH.md)
+[🇬🇧 English](../../README.md) · [🇨🇳 中文](README_CN.md) · [🇯🇵 日本語](README_JA.md) · [🇫🇷 Français](README_FR.md) · [🇸🇦 العربية](README_AR.md) · [🇷🇺 Русский](README_RU.md) · [🇮🇳 हिन्दी](README_HI.md) · [🇵🇹 Português](README_PT.md) · [🇹🇭 ภาษาไทย](README_TH.md) · 🇵🇱 [Polski](README_PL.md)
</div>
@@ -28,21 +28,36 @@
### 📦 Lanzamientos
-> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — Archivos adjuntos en el chat (PDF/DOCX/XLSX/PPTX), bloque de «pensamiento» del modelo de razonamiento, conmutación trisestado `send_dimensions` en embeddings, refactor del núcleo de proveedores LLM, editor de plantillas Soul, guardar en cuaderno desde Co-Writer, carga por arrastrar y soltar en la base de conocimiento y borrado resiliente, fidelidad idiomática en la generación de preguntas.
+> **[2026.4.30]** [v1.3.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.3) — Soporte de embeddings NVIDIA NIM y Gemini, contexto unificado de Space para historial de chat / skills / memoria, instantáneas de sesión, resiliencia de reindexación RAG.
-> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — Skills creados por el usuario (CRUD + integración en el chat), mejora del rendimiento del input con colocación de estado, retroceso automático de `response_format` para proveedores incompatibles, corrección de acceso remoto en LAN, insignia de versión en la barra lateral, adjuntos de imagen en Deep Solve, inicio automático de WebSocket de TutorBot, UI de la biblioteca de libros y modo de visualización a pantalla completa.
+> **[2026.4.29]** [v1.3.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.2) — URLs de endpoint de embedding transparentes, resiliencia de reindexación RAG ante vectores persistidos inválidos, limpieza de memoria para salida de modelos de razonamiento, corrección de tiempo de ejecución de Deep Solve.
-> **[2026.4.21]** [v1.2.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.1) — Límites de tokens por etapa en `agents.yaml` (respuestas de 8000 tokens), regenerar la última respuesta en CLI / WebSocket / Web UI, corrección del fallo de incrustaciones RAG `None`, compatibilidad de Gemma con `json_object`, legibilidad de bloques de código oscuros.
+> **[2026.4.28]** [v1.3.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.1) — Estabilidad: enrutamiento RAG más seguro y validación de embeddings, persistencia Docker, entrada segura con IME, robustez Windows/GBK.
-> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — Book Engine: compilador multiagente de «libros vivos» con 14 tipos de bloques, espacio de trabajo Co-Writer multidocumento, visualizaciones HTML interactivas, menciones @ del banco de preguntas en el chat, segunda fase de externalización de prompts y renovación de la barra lateral.
+> **[2026.4.27]** [v1.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.0) — Índices KB versionados con flujo de reindexación, espacio de trabajo de conocimiento reconstruido, autodetección de embeddings con nuevos adaptadores, hub de Space.
-> **[2026.4.18]** [v1.1.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.2) — Pestaña Channels basada en esquema con enmascaramiento de secretos; RAG unificado en un solo pipeline; refuerzo de coherencia RAG/KB; prompts de chat externalizados; README en tailandés.
+> **[2026.4.25]** [v1.2.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.5) — Adjuntos de chat persistentes con cajón de vista previa, pipelines de capacidad conscientes de adjuntos, exportación Markdown de TutorBot.
-> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — «Responder ya» universal en todas las capacidades; sincronización de desplazamiento en Co-Writer; selección de mensajes al guardar en el cuaderno; panel de ajustes unificado; botón Stop en streaming; escritura atómica de la configuración de TutorBot.
+> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — Adjuntos de texto / código / SVG, recorrido de configuración en un comando, exportación de chat Markdown, UI compacta de gestión de KB.
-> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) — Renovación del análisis de matemáticas LaTeX en bloque; sonda de diagnóstico LLM vía `agents.yaml`; corrección del reenvío de cabeceras extra; arreglo de UUID en SaveToNotebook; guía Docker + LLM local.
+> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — Adjuntos de documentos (PDF/DOCX/XLSX/PPTX), bloque de pensamiento del modelo de razonamiento, editor de plantillas Soul, guardar en cuaderno desde Co-Writer.
-> **[2026.4.14]** [v1.1.0-beta](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0-beta) — Sesiones marcables por URL; tema Snow; latido WebSocket y reconexión automática; mejora de rendimiento de ChatComposer; renovación del registro de proveedores de embeddings; proveedor de búsqueda Serper.
+> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — Sistema de Skills creados por el usuario, renovación del rendimiento del input de chat, inicio automático de TutorBot, UI de la biblioteca de libros, visualización a pantalla completa.
+
+> **[2026.4.21]** [v1.2.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.1) — Límites de tokens por etapa, regenerar respuesta en todos los puntos de entrada, correcciones de compatibilidad RAG y Gemma.
+
+> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — Compilador Book Engine de «libros vivos», Co-Writer multidocumento, visualizaciones HTML interactivas, menciones @ del banco de preguntas en el chat.
+
+> **[2026.4.18]** [v1.1.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.2) — Pestaña Channels basada en esquema, consolidación de RAG en un solo pipeline, prompts de chat externalizados.
+
+> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — «Responder ya» universal, sincronización de desplazamiento en Co-Writer, panel de ajustes unificado, botón Stop en streaming.
+
+<details>
+<summary><b>Lanzamientos anteriores (hace más de 2 semanas)</b></summary>
+
+> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) — Renovación del análisis de matemáticas LaTeX en bloque; sonda de diagnóstico LLM vía `agents.yaml`; guía Docker + LLM local.
+
+> **[2026.4.14]** [v1.1.0-beta](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0-beta) — Sesiones marcables por URL; tema Snow; latido WebSocket y reconexión automática; renovación del registro de proveedores de embeddings.
> **[2026.4.13]** [v1.0.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.3) — Cuaderno de preguntas con marcadores y categorías; Mermaid en Visualize; detección de desajuste de embeddings; compatibilidad Qwen/vLLM; soporte LM Studio y llama.cpp; tema Glass.
@@ -58,9 +73,6 @@
> **[2026.4.4]** [v1.0.0-beta.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.0-beta.1) — Reescritura nativa de agentes (~200k líneas): modelo de plugins Tools + Capabilities, CLI y SDK, TutorBot, Co-Writer, aprendizaje guiado y memoria persistente.
-<details>
-<summary><b>Lanzamientos anteriores</b></summary>
-
> **[2026.1.23]** [v0.6.0](https://github.com/HKUDS/DeepTutor/releases/tag/v0.6.0) — Persistencia de sesión, carga incremental, importación flexible de RAG, localización completa al chino.
> **[2026.1.18]** [v0.5.2](https://github.com/HKUDS/DeepTutor/releases/tag/v0.5.2) — Docling, logs y correcciones.
@@ -79,6 +91,8 @@
> **[2026.4.19]** 🎉 ¡Llegamos a 20k estrellas en 111 días! Gracias por el apoyo — seguiremos iterando hacia un tutorazgo realmente personalizado e inteligente.
+> **[2026.4.10]** 📄 ¡Nuestro artículo ya está en arXiv! Lee el [preprint](https://arxiv.org/abs/2604.26962) para conocer el diseño y las ideas detrás de DeepTutor.
+
> **[2026.4.4]** ¡Cuánto tiempo! ✨ DeepTutor v1.0.0 ya está aquí: evolución nativa de agentes con reescritura de arquitectura desde cero, TutorBot y modos flexibles bajo Apache-2.0. ¡Un nuevo capítulo comienza!
> **[2026.2.6]** 🚀 ¡10k estrellas en solo 39 días! Gracias a la comunidad.
diff --git a/assets/README/README_FR.md b/assets/README/README_FR.md
index 525633ac3..ab84a3953 100644
--- a/assets/README/README_FR.md
+++ b/assets/README/README_FR.md
@@ -10,7 +10,7 @@
[![Next.js 16](https://img.shields.io/badge/Next.js-16-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue?style=flat-square)](../../LICENSE)
[![GitHub release](https://img.shields.io/github/v/release/HKUDS/DeepTutor?style=flat-square&color=brightgreen)](https://github.com/HKUDS/DeepTutor/releases)
-[![arXiv](https://img.shields.io/badge/arXiv-Coming_Soon-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](#)
+[![arXiv](https://img.shields.io/badge/arXiv-2604.26962-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](https://arxiv.org/abs/2604.26962)
[![Discord](https://img.shields.io/badge/Discord-Community-5865F2?style=flat-square&logo=discord&logoColor=white)](https://discord.gg/eRsjPgMU4t)
[![Feishu](https://img.shields.io/badge/Feishu-Group-00D4AA?style=flat-square&logo=feishu&logoColor=white)](../../Communication.md)
@@ -18,7 +18,7 @@
[Fonctionnalités](#key-features) · [Démarrage](#get-started) · [Explorer](#explore-deeptutor) · [TutorBot](#tutorbot) · [CLI](#deeptutor-cli-guide) · [Feuille de route](#roadmap) · [Communauté](#community)
-[🇬🇧 English](../../README.md) · [🇨🇳 中文](README_CN.md) · [🇯🇵 日本語](README_JA.md) · [🇪🇸 Español](README_ES.md) · [🇸🇦 العربية](README_AR.md) · [🇷🇺 Русский](README_RU.md) · [🇮🇳 हिन्दी](README_HI.md) · [🇵🇹 Português](README_PT.md) · [🇹🇭 ภาษาไทย](README_TH.md)
+[🇬🇧 English](../../README.md) · [🇨🇳 中文](README_CN.md) · [🇯🇵 日本語](README_JA.md) · [🇪🇸 Español](README_ES.md) · [🇸🇦 العربية](README_AR.md) · [🇷🇺 Русский](README_RU.md) · [🇮🇳 हिन्दी](README_HI.md) · [🇵🇹 Português](README_PT.md) · [🇹🇭 ภาษาไทย](README_TH.md) · 🇵🇱 [Polski](README_PL.md)
</div>
@@ -28,17 +28,33 @@
### 📦 Versions
-> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — Pièces jointes de documents dans le chat (PDF/DOCX/XLSX/PPTX), affichage du bloc de raisonnement du modèle, bascule trité sur `send_dimensions` pour l’embedding, refonte du cœur des fournisseurs LLM, éditeur de modèles Soul, enregistrement Co-Writer vers le carnet, glisser-déposer et suppression résiliente dans la base de connaissances, fidélité linguistique à la génération de questions.
+> **[2026.4.30]** [v1.3.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.3) — Prise en charge des embeddings NVIDIA NIM et Gemini, contexte Space unifié pour l'historique du chat / les skills / la mémoire, instantanés de session, résilience de la réindexation RAG.
-> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — Skills rédigés par l’utilisateur (CRUD + intégration chat), refonte des perfs de saisie avec colocation d’état, repli auto de `response_format` pour fournisseurs incompatibles, correctif d’accès distant LAN, badge de version dans la barre latérale, pièces jointes image dans Deep Solve, démarrage auto WebSocket TutorBot, UI de la bibliothèque de livres, mode plein écran des visualisations.
+> **[2026.4.29]** [v1.3.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.2) — URLs d'endpoint d'embedding transparentes, résilience de réindexation RAG pour vecteurs persistés invalides, nettoyage mémoire pour la sortie des modèles de raisonnement, correctif d'exécution Deep Solve.
-> **[2026.4.21]** [v1.2.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.1) — Limites de tokens par étape dans `agents.yaml` (réponses 8000 tokens), régénérer la dernière réponse (CLI / WebSocket / Web UI), correctif crash RAG sur embeddings `None`, compatibilité Gemma `json_object`, lisibilité des blocs de code sombres.
+> **[2026.4.28]** [v1.3.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.1) — Stabilité : routage RAG plus sûr et validation des embeddings, persistance Docker, saisie compatible IME, robustesse Windows/GBK.
-> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — Book Engine : compilateur multi-agents de « livres vivants » avec 14 types de blocs, espace Co-Writer multi-documents, visualisations HTML interactives, mentions @ de la banque de questions dans le chat, phase 2 d’externalisation des prompts, refonte de la barre latérale.
+> **[2026.4.27]** [v1.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.0) — Index KB versionnés avec flux de réindexation, espace Connaissances reconstruit, auto-découverte des embeddings avec nouveaux adaptateurs, hub Space.
-> **[2026.4.18]** [v1.1.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.2) — Onglet Channels piloté par schéma et masquage des secrets ; RAG fusionné en un seul pipeline ; renforcement de la cohérence RAG/KB ; prompts de chat externalisés ; README en thaï.
+> **[2026.4.25]** [v1.2.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.5) — Pièces jointes de chat persistantes avec tiroir d'aperçu, pipelines de capacité sensibles aux pièces jointes, export Markdown TutorBot.
-> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — « Répondre maintenant » universel sur toutes les capacités ; synchronisation du défilement Co-Writer ; sélection des messages pour l’enregistrement dans le carnet ; panneau de paramètres unifié ; bouton Stop en streaming ; écriture atomique de la configuration TutorBot.
+> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — Pièces jointes texte / code / SVG, visite guidée de configuration en une commande, export du chat Markdown, UI compacte de gestion des KB.
+
+> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — Pièces jointes de documents (PDF/DOCX/XLSX/PPTX), affichage du bloc de raisonnement, éditeur de modèles Soul, enregistrement Co-Writer vers le carnet.
+
+> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — Système de Skills rédigés par l'utilisateur, refonte des perfs de saisie du chat, démarrage auto TutorBot, UI de la bibliothèque de livres, visualisations plein écran.
+
+> **[2026.4.21]** [v1.2.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.1) — Limites de tokens par étape, régénérer la réponse sur tous les points d'entrée, correctifs de compatibilité RAG et Gemma.
+
+> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — Compilateur Book Engine de « livres vivants », Co-Writer multi-documents, visualisations HTML interactives, mentions @ de la banque de questions dans le chat.
+
+> **[2026.4.18]** [v1.1.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.2) — Onglet Channels piloté par schéma, consolidation RAG en pipeline unique, prompts de chat externalisés.
+
+> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — « Répondre maintenant » universel, synchronisation du défilement Co-Writer, panneau de paramètres unifié, bouton Stop en streaming.
+
+
+<details>
+<summary><b>Versions antérieures (il y a plus de 2 semaines)</b></summary>
> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) — Refonte du parsing LaTeX en blocs ; sonde de diagnostic LLM via `agents.yaml` ; correctif de transfert d’en-têtes supplémentaires ; correctif UUID SaveToNotebook ; guide Docker + LLM local.
@@ -58,9 +74,6 @@
> **[2026.4.4]** [v1.0.0-beta.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.0-beta.1) — Réécriture native agents (~200k lignes) : modèle de plugins Tools + Capabilities, CLI et SDK, TutorBot, Co-Writer, apprentissage guidé et mémoire persistante.
-<details>
-<summary><b>Versions précédentes</b></summary>
-
> **[2026.1.23]** [v0.6.0](https://github.com/HKUDS/DeepTutor/releases/tag/v0.6.0) — Persistance de session, import incrémental, RAG flexible, localisation chinoise complète.
> **[2026.1.18]** [v0.5.2](https://github.com/HKUDS/DeepTutor/releases/tag/v0.5.2) — Docling, journaux, correctifs.
@@ -79,6 +92,8 @@
> **[2026.4.19]** 🎉 20k étoiles en 111 jours ! Merci pour votre soutien — nous poursuivons l’itération vers un tutorat vraiment personnalisé et intelligent.
+> **[2026.4.10]** 📄 Notre article est en ligne sur arXiv ! Lisez le [preprint](https://arxiv.org/abs/2604.26962) pour découvrir la conception et les idées derrière DeepTutor.
+
> **[2026.4.4]** Ça faisait longtemps ! ✨ DeepTutor v1.0.0 est enfin là — évolution native agents : refonte complète de l’architecture, TutorBot et modes flexibles sous Apache-2.0. Un nouveau chapitre commence !
> **[2026.2.6]** 🚀 10k étoiles en 39 jours — merci à la communauté !
diff --git a/assets/README/README_HI.md b/assets/README/README_HI.md
index 0f593fc80..f9be7f1e6 100644
--- a/assets/README/README_HI.md
+++ b/assets/README/README_HI.md
@@ -10,7 +10,7 @@
[![Next.js 16](https://img.shields.io/badge/Next.js-16-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue?style=flat-square)](../../LICENSE)
[![GitHub release](https://img.shields.io/github/v/release/HKUDS/DeepTutor?style=flat-square&color=brightgreen)](https://github.com/HKUDS/DeepTutor/releases)
-[![arXiv](https://img.shields.io/badge/arXiv-Coming_Soon-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](#)
+[![arXiv](https://img.shields.io/badge/arXiv-2604.26962-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](https://arxiv.org/abs/2604.26962)
[![Discord](https://img.shields.io/badge/Discord-Community-5865F2?style=flat-square&logo=discord&logoColor=white)](https://discord.gg/eRsjPgMU4t)
[![Feishu](https://img.shields.io/badge/Feishu-Group-00D4AA?style=flat-square&logo=feishu&logoColor=white)](../../Communication.md)
@@ -18,7 +18,7 @@
[मुख्य विशेषताएँ](#key-features) · [शुरू करें](#get-started) · [अन्वेषण](#explore-deeptutor) · [TutorBot](#tutorbot) · [CLI](#deeptutor-cli-guide) · [रोडमैप](#roadmap) · [समुदाय](#community)
-[🇬🇧 English](../../README.md) · [🇨🇳 中文](README_CN.md) · [🇯🇵 日本語](README_JA.md) · [🇪🇸 Español](README_ES.md) · [🇫🇷 Français](README_FR.md) · [🇸🇦 العربية](README_AR.md) · [🇷🇺 Русский](README_RU.md) · [🇮🇳 हिन्दी](README_HI.md) · [🇵🇹 Português](README_PT.md) · [🇹🇭 ภาษาไทย](README_TH.md)
+[🇬🇧 English](../../README.md) · [🇨🇳 中文](README_CN.md) · [🇯🇵 日本語](README_JA.md) · [🇪🇸 Español](README_ES.md) · [🇫🇷 Français](README_FR.md) · [🇸🇦 العربية](README_AR.md) · [🇷🇺 Русский](README_RU.md) · [🇮🇳 हिन्दी](README_HI.md) · [🇵🇹 Português](README_PT.md) · [🇹🇭 ภาษาไทย](README_TH.md) · 🇵🇱 [Polski](README_PL.md)
</div>
@@ -28,17 +28,33 @@
### 📦 रिलीज़
-> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — चैट में दस्तावेज़ संलग्नक (PDF/DOCX/XLSX/PPTX), तर्क मॉडल की सोच-ब्लॉक प्रदर्शन, एम्बेडिंग `send_dimensions` त्रि-स्थिति टॉगल, LLM प्रदाता कोर रिफैक्टर, Soul टेम्पलेट संपादक, Co-Writer से नोटबुक में सहेजें, नॉलेज बेस ड्रैग-एंड-ड्रॉप अपलोड व हटाने में लचीलेपन, प्रश्न निर्माण में भाषा निष्ठा।
+> **[2026.4.30]** [v1.3.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.3) — NVIDIA NIM + Gemini एम्बेडिंग समर्थन, चैट इतिहास / स्किल / मेमोरी के लिए एकीकृत Space संदर्भ, सत्र स्नैपशॉट, RAG पुनः-अनुक्रमण लचीलापन।
-> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — उपयोगकर्ता-लिखित Skills प्रणाली (CRUD + चैट एकीकरण), चैट इनपुट प्रदर्शन ओवरहॉल व state सह-स्थान, असंगत प्रदाताओं के लिए `response_format` ऑटो-फ़ॉलबैक, LAN रिमोट एक्सेस फिक्स, साइडबार संस्करण बैज, Deep Solve में चित्र संलग्नक, TutorBot WebSocket ऑटो-स्टार्ट, बुक लाइब्रेरी UI, विज़ुअलाइज़ेशन फ़ुलस्क्रीन।
+> **[2026.4.29]** [v1.3.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.2) — पारदर्शी एम्बेडिंग एंडपॉइंट URL, अमान्य स्थायी वेक्टर पर RAG पुनः-अनुक्रमण लचीलापन, थिंकिंग-मॉडल आउटपुट के लिए मेमोरी सफाई, Deep Solve रनटाइम फिक्स।
-> **[2026.4.21]** [v1.2.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.1) — `agents.yaml` में चरण-दर-चरण चैट टोकन सीमाएँ (8000-टोकन उत्तर), CLI / WebSocket / वेब UI पर अंतिम उत्तर पुनर्जनन, RAG `None`-एम्बेडिंग क्रैश ठीक, Gemma `json_object` अनुकूलता, गहरे कोड ब्लॉक पठनीयता।
+> **[2026.4.28]** [v1.3.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.1) — स्थिरता: सुरक्षित RAG रूटिंग व एम्बेडिंग सत्यापन, Docker स्थिरता, IME-सुरक्षित इनपुट, Windows/GBK मजबूती।
-> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — Book Engine: 14 ब्लॉक प्रकारों के साथ मल्टी-एजेंट «जीवंत पुस्तक» संकलक, मल्टी-दस्तावेज़ Co-Workspace, इंटरैक्टिव HTML विज़ुअलाइज़ेशन, चैट में प्रश्न बैंक @-उल्लेख, प्रॉम्प्ट बाहरीकरण चरण 2, साइडबार ओवरहॉल।
+> **[2026.4.27]** [v1.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.0) — संस्करणित KB इंडेक्स व पुनः-अनुक्रमण वर्कफ़्लो, नॉलेज वर्कस्पेस पुनर्निर्माण, नए अडैप्टर के साथ एम्बेडिंग ऑटो-डिस्कवरी, Space हब।
-> **[2026.4.18]** [v1.1.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.2) — स्कीमा-चालित Channels टैब व सीक्रेट मास्किंग; एकल RAG पाइपलाइन; RAG/KB स्थिरता मजबूत; चैट प्रॉम्प्ट बाहरी फ़ाइलों में; थाई README।
+> **[2026.4.25]** [v1.2.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.5) — फ़ाइल-पूर्वावलोकन दराज के साथ स्थायी चैट संलग्नक, संलग्नक-जागरूक क्षमता पाइपलाइन, TutorBot Markdown निर्यात।
-> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — सभी क्षमताओं पर सार्वभौमिक «अभी उत्तर दें»; Co-Writer स्क्रॉल सिंक; नोटबुक में सहेजते समय संदेश चयन; एकीकृत सेटिंग्स पैनल; स्ट्रीमिंग Stop बटन; TutorBot कॉन्फ़िगरेशन परमाणु लेखन।
+> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — टेक्स्ट / कोड / SVG संलग्नक, एक-कमांड सेटअप टूर, Markdown चैट निर्यात, कॉम्पैक्ट KB प्रबंधन UI।
+
+> **[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 ऑटो-स्टार्ट, बुक लाइब्रेरी UI, विज़ुअलाइज़ेशन फ़ुलस्क्रीन।
+
+> **[2026.4.21]** [v1.2.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.1) — चरण-दर-चरण टोकन सीमाएँ, सभी प्रवेश बिंदुओं पर उत्तर पुनर्जनन, RAG व Gemma अनुकूलता फिक्स।
+
+> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — Book Engine «जीवंत पुस्तक» संकलक, मल्टी-दस्तावेज़ Co-Writer, इंटरैक्टिव HTML विज़ुअलाइज़ेशन, चैट में प्रश्न बैंक @-उल्लेख।
+
+> **[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) — सार्वभौमिक «अभी उत्तर दें», Co-Writer स्क्रॉल सिंक, एकीकृत सेटिंग्स पैनल, स्ट्रीमिंग Stop बटन।
+
+
+<details>
+<summary><b>पुराने रिलीज़ (2 सप्ताह से अधिक पहले)</b></summary>
> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) — LaTeX ब्लॉक गणित पार्सिंग ओवरहॉल; `agents.yaml` के माध्यम से LLM डायग्नोस्टिक प्रोब; अतिरिक्त हेडर फॉरवर्डिंग फिक्स; SaveToNotebook UUID फिक्स; Docker + स्थानीय LLM मार्गदर्शिका।
@@ -58,9 +74,6 @@
> **[2026.4.4]** [v1.0.0-beta.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.0-beta.1) — एजेंट-नेटिव आर्किटेक्चर रिराइट (~200k पंक्तियाँ): Tools + Capabilities प्लगइन मॉडल, CLI व SDK, TutorBot, Co-Writer, Guided Learning, स्थायी मेमोरी।
-<details>
-<summary><b>पिछले रिलीज़</b></summary>
-
> **[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) — Docling, लॉग, बग फिक्स।
@@ -79,6 +92,8 @@
> **[2026.4.19]** 🎉 111 दिनों में 20k सितारे! समर्थन के लिए धन्यवाद — हम वास्तव में व्यक्तिगत, बुद्धिमान शिक्षण की दिशा में निरंतर सुधार करते रहेंगे।
+> **[2026.4.10]** 📄 हमारा पेपर अब arXiv पर है! [प्रीप्रिंट](https://arxiv.org/abs/2604.26962) पढ़ें और DeepTutor की रचना व विचारधारा जानें।
+
> **[2026.4.4]** बहुत दिन बाद! ✨ DeepTutor v1.0.0 आ गया — Apache-2.0 के तहत एजेंट-नेटिव विकास: ज़मीन से आर्किटेक्चर रिराइट, TutorBot, लचीले मोड। नया अध्याय शुरू!
> **[2026.2.6]** 🚀 39 दिनों में 10k सितारे — समुदाय का धन्यवाद!
diff --git a/assets/README/README_JA.md b/assets/README/README_JA.md
index 7e7759919..e41017a2e 100644
--- a/assets/README/README_JA.md
+++ b/assets/README/README_JA.md
@@ -10,7 +10,7 @@
[![Next.js 16](https://img.shields.io/badge/Next.js-16-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue?style=flat-square)](../../LICENSE)
[![GitHub release](https://img.shields.io/github/v/release/HKUDS/DeepTutor?style=flat-square&color=brightgreen)](https://github.com/HKUDS/DeepTutor/releases)
-[![arXiv](https://img.shields.io/badge/arXiv-Coming_Soon-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](#)
+[![arXiv](https://img.shields.io/badge/arXiv-2604.26962-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](https://arxiv.org/abs/2604.26962)
[![Discord](https://img.shields.io/badge/Discord-Community-5865F2?style=flat-square&logo=discord&logoColor=white)](https://discord.gg/eRsjPgMU4t)
[![Feishu](https://img.shields.io/badge/Feishu-Group-00D4AA?style=flat-square&logo=feishu&logoColor=white)](../../Communication.md)
@@ -18,7 +18,7 @@
[主な機能](#key-features) · [はじめる](#get-started) · [DeepTutor を探る](#explore-deeptutor) · [TutorBot](#tutorbot) · [CLI](#deeptutor-cli-guide) · [ロードマップ](#roadmap) · [コミュニティ](#community)
-[🇬🇧 English](../../README.md) · [🇨🇳 中文](README_CN.md) · [🇪🇸 Español](README_ES.md) · [🇫🇷 Français](README_FR.md) · [🇸🇦 العربية](README_AR.md) · [🇷🇺 Русский](README_RU.md) · [🇮🇳 हिन्दी](README_HI.md) · [🇵🇹 Português](README_PT.md) · [🇹🇭 ภาษาไทย](README_TH.md)
+[🇬🇧 English](../../README.md) · [🇨🇳 中文](README_CN.md) · [🇪🇸 Español](README_ES.md) · [🇫🇷 Français](README_FR.md) · [🇸🇦 العربية](README_AR.md) · [🇷🇺 Русский](README_RU.md) · [🇮🇳 हिन्दी](README_HI.md) · [🇵🇹 Português](README_PT.md) · [🇹🇭 ภาษาไทย](README_TH.md) · 🇵🇱 [Polski](README_PL.md)
</div>
@@ -28,21 +28,36 @@
### 📦 リリース
-> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — チャットでの文書添付(PDF/DOCX/XLSX/PPTX)、推論モデルの思考ブロック表示、埋め込み `send_dimensions` 三択、LLM プロバイダ中核のリファクタ、Soul テンプレートエディタ、Co-Writer のノートブック保存、ナレッジベースのドラッグ&ドロップアップロードと削除耐性、問題生成の言語忠実度。
+> **[2026.4.30]** [v1.3.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.3) — NVIDIA NIM と Gemini 埋め込み対応、チャット履歴 / スキル / メモリを束ねる統一 Space コンテキスト、セッションスナップショット、RAG 再インデックスの耐性強化。
-> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — ユーザー作成 Skills(CRUD+チャット連携)、チャット入力の性能刷新と state の配置、`response_format` の非互換プロバイダ向け自動フォールバック、LAN リモートアクセス修正、サイドバーのバージョン表示、Deep Solve の画像添付、TutorBot WebSocket の自動起動、Book Library UI、可視化の全画面表示。
+> **[2026.4.29]** [v1.3.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.2) — 埋め込みエンドポイント URL の可視化、無効な永続ベクトル時の RAG 再インデックス耐性、思考モデル出力のメモリ整理、Deep Solve ランタイム修正。
-> **[2026.4.21]** [v1.2.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.1) — `agents.yaml` によるチャット各段階のトークン上限(8000 トークン応答)、CLI / WebSocket / Web UI で最終応答を再生成、RAG の `None` 埋め込みクラッシュ修正、Gemma の `json_object` 互換、暗いコードブロックの可読性。
+> **[2026.4.28]** [v1.3.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.1) — 安定性:より安全な RAG ルーティングと埋め込み検証、Docker 永続化、IME 安全な入力、Windows / GBK 堅牢性。
-> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — Book Engine による 14 種ブロックのマルチエージェント「リビングブック」コンパイラ、マルチドキュメント Co-Writer、HTML インタラクティブ可視化、チャットでの Question Bank @メンション、プロンプト外部化フェーズ 2、サイドバー刷新。
+> **[2026.4.27]** [v1.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.0) — バージョン付き KB インデックスと再インデックスワークフロー、ナレッジワークスペース刷新、新アダプタ付き埋め込み自動検出、Space ハブ。
-> **[2026.4.18]** [v1.1.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.2) — Schema 駆動の Channels タブとシークレットマスク、RAG を単一パイプラインへ集約、RAG/KB の整合性強化、チャットプロンプトの外部化、タイ語 README。
+> **[2026.4.25]** [v1.2.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.5) — チャット添付の永続化とファイルプレビュードロワー、添付を意識したケイパビリティパイプライン、TutorBot の Markdown エクスポート。
-> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — 全ケイパビリティ対応のユニバーサル「今すぐ回答」、Co-Writer のスクロール同期、ノートブック保存時のメッセージ選択、統一設定パネル、ストリーミング Stop ボタン、TutorBot 設定の原子的書き込み。
+> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — テキスト / コード / SVG 添付、ワンコマンドのセットアップツアー、Markdown チャットエクスポート、コンパクトな KB 管理 UI。
-> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) — LaTeX ブロック数式パースの刷新、`agents.yaml` 経由の LLM 診断プローブ、追加ヘッダ転送の修正、SaveToNotebook の UUID 修正、Docker とローカル LLM のガイダンス。
+> **[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.14]** [v1.1.0-beta](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0-beta) — URL ベースのブックマーク可能セッション、Snow テーマ、WebSocket ハートビートと自動再接続、ChatComposer の性能改善、埋め込みプロバイダレジストリの刷新、Serper 検索プロバイダ。
+> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — ユーザー作成 Skills、チャット入力の性能刷新、TutorBot 自動起動、Book Library UI、可視化の全画面表示。
+
+> **[2026.4.21]** [v1.2.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.1) — 段階ごとのトークン上限、全エントリポイントでの応答再生成、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) — Schema 駆動の Channels タブ、RAG の単一パイプライン集約、チャットプロンプトの外部化。
+
+> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — ユニバーサル「今すぐ回答」、Co-Writer のスクロール同期、統一設定パネル、ストリーミング Stop ボタン。
+
+<details>
+<summary><b>過去のリリース(2 週間より前)</b></summary>
+
+> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) — LaTeX ブロック数式パースの刷新、`agents.yaml` 経由の LLM 診断プローブ、Docker とローカル LLM のガイダンス。
+
+> **[2026.4.14]** [v1.1.0-beta](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0-beta) — URL ベースのブックマーク可能セッション、Snow テーマ、WebSocket ハートビートと自動再接続、埋め込みプロバイダレジストリの刷新。
> **[2026.4.13]** [v1.0.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.3) — ブックマークとカテゴリ付きクイズノートブック、Visualize での Mermaid、埋め込み不一致検出、Qwen/vLLM 互換、LM Studio と llama.cpp 対応、Glass テーマ。
@@ -58,9 +73,6 @@
> **[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、ガイド付き学習、永続メモリ。
-<details>
-<summary><b>過去のリリース</b></summary>
-
> **[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) — Docling 対応、ログ改善、バグ修正。
@@ -79,6 +91,8 @@
> **[2026.4.19]** 🎉 111 日で 20k スターに到達しました!ご支援に感謝します — 真にパーソナルで知的なチュターリングに向けて、継続的に改善を続けます。
+> **[2026.4.10]** 📄 論文が arXiv で公開されました。[プレプリント](https://arxiv.org/abs/2604.26962)で DeepTutor の設計とアイデアをご覧ください。
+
> **[2026.4.4]** お久しぶりです!✨ DeepTutor v1.0.0 がついに登場 — Apache-2.0 のもと、ゼロからの架構書き直し、TutorBot、柔軟なモード切替を備えたエージェントネイティブな進化です。新章の始まりです!
> **[2026.2.6]** 🚀 わずか 39 日で 10k スターに到達。コミュニティに感謝します!
diff --git a/assets/README/README_PL.md b/assets/README/README_PL.md
index 34de28c81..def86036b 100644
--- a/assets/README/README_PL.md
+++ b/assets/README/README_PL.md
@@ -10,7 +10,7 @@
[![Next.js 16](https://img.shields.io/badge/Next.js-16-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue?style=flat-square)](LICENSE)
[![GitHub release](https://img.shields.io/github/v/release/HKUDS/DeepTutor?style=flat-square&color=brightgreen)](https://github.com/HKUDS/DeepTutor/releases)
-[![arXiv](https://img.shields.io/badge/arXiv-Coming_Soon-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](#)
+[![arXiv](https://img.shields.io/badge/arXiv-2604.26962-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](https://arxiv.org/abs/2604.26962)
[![Discord](https://img.shields.io/badge/Discord-Community-5865F2?style=flat-square&logo=discord&logoColor=white)](https://discord.gg/eRsjPgMU4t)
[![Feishu](https://img.shields.io/badge/Feishu-Group-00D4AA?style=flat-square&logo=feishu&logoColor=white)](./Communication.md)
@@ -18,7 +18,7 @@
[Funkcje](#-kluczowe-funkcje) · [Jak zacząć](#-rozpocznij) · [Odkrywaj](#-odkrywaj-deeptutor) · [TutorBoty](#-tutorbot--trwali-autonomiczni-korepetytorzy-ai) · [CLI](#%EF%B8%8F-deeptutor-cli--interfejs-stworzony-dla-agentów) · [Roadmapa](#%EF%B8%8F-harmonogram) · [Społeczność](#-społeczność--ekosystem)
-[🇨🇳 中文](assets/README/README_CN.md) · [🇯🇵 日本語](assets/README/README_JA.md) · [🇪🇸 Español](assets/README/README_ES.md) · [🇫🇷 Français](assets/README/README_FR.md) · [🇸🇦 العربية](assets/README/README_AR.md) · [🇷🇺 Русский](assets/README/README_RU.md) · [🇮🇳 हिन्दी](assets/README/README_HI.md) · [🇵🇹 Português](assets/README/README_PT.md) · [🇹🇭 ภาษาไทย](assets/README/README_TH.md) · [🇵🇱 Polski](assets/README/README_PL.md)
+[🇬🇧 English](../../README.md) · [🇨🇳 中文](assets/README/README_CN.md) · [🇯🇵 日本語](assets/README/README_JA.md) · [🇪🇸 Español](assets/README/README_ES.md) · [🇫🇷 Français](assets/README/README_FR.md) · [🇸🇦 العربية](assets/README/README_AR.md) · [🇷🇺 Русский](assets/README/README_RU.md) · [🇮🇳 हिन्दी](assets/README/README_HI.md) · [🇵🇹 Português](assets/README/README_PT.md) · [🇹🇭 ภาษาไทย](assets/README/README_TH.md) · [🇵🇱 Polski](assets/README/README_PL.md)
</div>
@@ -28,17 +28,33 @@
### 📦 Wydania
-> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — Załączanie dokumentów bezpośrednio na czacie (PDF/DOCX/XLSX/PPTX), podgląd procesu myślowego modelu (reasoning), trzystopniowy przełącznik `send_dimensions` dla wektorów (embeddings), refaktoryzacja rdzenia dostawców LLM, edytor szablonów "Duszy" (Soul), zapisywanie notatek z poziomu Co-Writera, stabilniejsze przeciąganie i upuszczanie (drag & drop) w Bazie Wiedzy oraz lepsze zachowanie języka przy generowaniu pytań.
+> **[2026.4.30]** [v1.3.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.3) — Obsługa embeddingów NVIDIA NIM i Gemini, ujednolicony kontekst Space dla historii czatu / umiejętności / pamięci, migawki sesji, odporność ponownej indeksacji RAG.
-> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — Własne Umiejętności (Skills) tworzone przez użytkowników (pełen CRUD i integracja z czatem), potężna optymalizacja wydajności wprowadzania tekstu, automatyczny fallback `response_format` dla niekompatybilnych API, poprawka dla zdalnego dostępu po LAN, oznaczenie wersji na pasku bocznym, wsparcie dla obrazów w trybie Deep Solve, autostart WebSocketów dla TutorBota, nowy interfejs Biblioteki Książek oraz tryb pełnoekranowy dla wizualizacji.
+> **[2026.4.29]** [v1.3.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.2) — Przejrzyste adresy URL endpointów embeddingów, odporność ponownej indeksacji RAG przy nieprawidłowych zapisanych wektorach, czyszczenie pamięci dla wyjścia modeli rozumujących, poprawka runtime Deep Solve.
-> **[2026.4.21]** [v1.2.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.1) — Limity tokenów na etap rozmowy w `agents.yaml` (dla odpowiedzi na 8000 tokenów), opcja regeneracji ostatniej odpowiedzi w CLI / WebSocket / Web UI, naprawa błędu przy braku wektorów (`None`) w RAG, kompatybilność `json_object` dla modeli Gemma oraz lepsza czytelność ciemnych bloków kodu.
+> **[2026.4.28]** [v1.3.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.1) — Stabilność: bezpieczniejsze routowanie RAG i walidacja embeddingów, persystencja Docker, bezpieczne wprowadzanie z IME, odporność Windows/GBK.
-> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — Kompilator interaktywnych "żywych książek" oparty na wielu agentach (Book Engine) z 14 typami bloków, przestrzeń robocza Co-Writer do pracy z wieloma dokumentami, interaktywne wizualizacje HTML, oznaczanie (@) Banku Pytań na czacie, faza 2 eksternalizacji promptów oraz całkowicie przeprojektowany pasek boczny.
+> **[2026.4.27]** [v1.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.0) — Wersjonowane indeksy KB z przepływem ponownej indeksacji, przebudowana przestrzeń wiedzy, automatyczne wykrywanie embeddingów z nowymi adapterami, hub Space.
-> **[2026.4.18]** [v1.1.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.2) — Zakładka Kanałów oparta na schematach (z ukrywaniem haseł/kluczy), uproszczenie RAG do jednego potoku, poprawa spójności na linii RAG - Baza Wiedzy, eksternalizacja promptów czatu i README w języku tajskim.
+> **[2026.4.25]** [v1.2.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.5) — Trwałe załączniki czatu z szufladą podglądu plików, potoki zdolności świadome załączników, eksport Markdown TutorBot.
-> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — Uniwersalny przycisk "Odpowiedz teraz" dla wszystkich funkcji, synchronizacja przewijania w Co-Writerze, opcja "Zapisz do Notatnika" dla wiadomości, zunifikowany panel ustawień, przycisk zatrzymywania generowania (Stop) i atomowe zapisywanie konfiguracji TutorBota.
+> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — Załączniki tekst / kod / SVG, konfiguracja jednym poleceniem, eksport czatu Markdown, zwarty interfejs zarządzania KB.
+
+> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — Załączniki dokumentów (PDF/DOCX/XLSX/PPTX), blok rozumowania modelu, edytor szablonów Soul, zapis z Co-Writer do notesu.
+
+> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — System Skills tworzonych przez użytkownika, optymalizacja wydajności wpisywania w czacie, autostart TutorBot, UI biblioteki książek, wizualizacje pełnoekranowe.
+
+> **[2026.4.21]** [v1.2.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.1) — Limity tokenów na etap, ponowna generacja odpowiedzi we wszystkich punktach wejścia, poprawki zgodności RAG i Gemma.
+
+> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — Kompilator Book Engine „żywych książek”, Co-Writer wielodokumentowy, interaktywne wizualizacje HTML, @-wzmianki banku pytań na czacie.
+
+> **[2026.4.18]** [v1.1.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.2) — Zakładka Channels oparta na schemacie, konsolidacja RAG w jednym potoku, zewnętrzne prompty czatu.
+
+> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — Uniwersalne „Odpowiedz teraz”, synchronizacja przewijania Co-Writer, zunifikowany panel ustawień, przycisk Stop przy strumieniowaniu.
+
+
+<details>
+<summary><b>Starsze wydania (ponad 2 tygodnie temu)</b></summary>
> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) — Przepisanie parsera bloków matematycznych LaTeX, diagnostyka LLM przez `agents.yaml`, naprawa przekazywania dodatkowych nagłówków HTTP, poprawka UUID przy zapisywaniu notatek oraz nowe wskazówki dla środowisk Docker + lokalne LLM.
@@ -58,9 +74,6 @@
> **[2026.4.4]** [v1.0.0-beta.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.0-beta.1) — Całkowicie nowa architektura oparta na agentach (~200 tys. linii kodu): System wtyczek dla Narzędzi i Umiejętności, nowe CLI i SDK, TutorBot, Co-Writer, Przewodnik Nauki (Guided Learning) oraz długoterminowa pamięć.
-<details>
-<summary><b>Poprzednie wydania</b></summary>
-
> **[2026.1.23]** [v0.6.0](https://github.com/HKUDS/DeepTutor/releases/tag/v0.6.0) — Pamięć sesji, przyrostowe przesyłanie dokumentów, elastyczny import do RAG i pełne wsparcie języka chińskiego.
> **[2026.1.18]** [v0.5.2](https://github.com/HKUDS/DeepTutor/releases/tag/v0.5.2) — Integracja z Docling (RAG-Anything), optymalizacja logów i paczka mniejszych poprawek.
@@ -79,6 +92,8 @@
> **[2026.4.19]** 🎉 20 000 gwiazdek w 111 dni! Dziękujemy za wasze niesamowite wsparcie — pracujemy dalej, aby stworzyć prawdziwie spersonalizowane, inteligentne korepetycje dostępne dla każdego.
+> **[2026.4.10]** 📄 Nasz artykuł jest już na arXiv! Przeczytaj [preprint](https://arxiv.org/abs/2604.26962), aby poznać założenia i idee stojące za DeepTutor.
+
> **[2026.4.4]** Doczekaliśmy się! ✨ DeepTutor v1.0.0 jest już dostępny — to nasza ewolucja w kierunku architektury agentowej, przebudowana od podstaw. Wprowadzamy TutorBoty, płynne przełączanie trybów, a to wszystko na licencji Apache-2.0. Zaczynamy nowy rozdział!
> **[2026.2.6]** 🚀 Mamy 10 000 gwiazdek w zaledwie 39 dni! Ogromne podziękowania dla naszej rewelacyjnej społeczności.
diff --git a/assets/README/README_PT.md b/assets/README/README_PT.md
index 8b1645ea5..35d9970a7 100644
--- a/assets/README/README_PT.md
+++ b/assets/README/README_PT.md
@@ -10,7 +10,7 @@
[![Next.js 16](https://img.shields.io/badge/Next.js-16-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue?style=flat-square)](../../LICENSE)
[![GitHub release](https://img.shields.io/github/v/release/HKUDS/DeepTutor?style=flat-square&color=brightgreen)](https://github.com/HKUDS/DeepTutor/releases)
-[![arXiv](https://img.shields.io/badge/arXiv-Coming_Soon-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](#)
+[![arXiv](https://img.shields.io/badge/arXiv-2604.26962-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](https://arxiv.org/abs/2604.26962)
[![Discord](https://img.shields.io/badge/Discord-Community-5865F2?style=flat-square&logo=discord&logoColor=white)](https://discord.gg/eRsjPgMU4t)
[![Feishu](https://img.shields.io/badge/Feishu-Group-00D4AA?style=flat-square&logo=feishu&logoColor=white)](../../Communication.md)
@@ -18,7 +18,7 @@
[Recursos](#key-features) · [Começar](#get-started) · [Explorar](#explore-deeptutor) · [TutorBot](#tutorbot) · [CLI](#deeptutor-cli-guide) · [Roteiro](#roadmap) · [Comunidade](#community)
-[🇬🇧 English](../../README.md) · [🇨🇳 中文](README_CN.md) · [🇯🇵 日本語](README_JA.md) · [🇪🇸 Español](README_ES.md) · [🇫🇷 Français](README_FR.md) · [🇸🇦 العربية](README_AR.md) · [🇷🇺 Русский](README_RU.md) · [🇮🇳 हिन्दी](README_HI.md) · [🇵🇹 Português](README_PT.md) · [🇹🇭 ภาษาไทย](README_TH.md)
+[🇬🇧 English](../../README.md) · [🇨🇳 中文](README_CN.md) · [🇯🇵 日本語](README_JA.md) · [🇪🇸 Español](README_ES.md) · [🇫🇷 Français](README_FR.md) · [🇸🇦 العربية](README_AR.md) · [🇷🇺 Русский](README_RU.md) · [🇮🇳 हिन्दी](README_HI.md) · [🇵🇹 Português](README_PT.md) · [🇹🇭 ภาษาไทย](README_TH.md) · 🇵🇱 [Polski](README_PL.md)
</div>
@@ -28,17 +28,33 @@
### 📦 Lançamentos
-> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — Anexos de documentos no chat (PDF/DOCX/XLSX/PPTX), exibição do bloco de raciocínio do modelo, alternância tríade `send_dimensions` em embeddings, refactor do núcleo de provedores LLM, editor de modelos Soul, salvar no caderno no Co-Writer, arrastar e soltar na base de conhecimento e remoção resiliente, fidelidade idiomática na geração de questões.
+> **[2026.4.30]** [v1.3.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.3) — Suporte a embeddings NVIDIA NIM e Gemini, contexto Space unificado para histórico do chat / skills / memória, instantâneos de sessão, resiliência de reindexação RAG.
-> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — Skills criados pelo usuário (CRUD + integração no chat), melhoria de desempenho do input com colocação de estado, fallback automático de `response_format` para provedores incompatíveis, correção de acesso remoto na LAN, selo de versão na barra lateral, anexos de imagem no Deep Solve, início automático do WebSocket do TutorBot, UI da biblioteca de livros e modo tela cheia nas visualizações.
+> **[2026.4.29]** [v1.3.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.2) — URLs de endpoint de embedding transparentes, resiliência de reindexação RAG para vetores persistidos inválidos, limpeza de memória para saída de modelos de raciocínio, correção de runtime do Deep Solve.
-> **[2026.4.21]** [v1.2.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.1) — Limites de tokens por etapa em `agents.yaml` (respostas de 8000 tokens), regenerar a última resposta (CLI / WebSocket / Web UI), correção de falha RAG com embeddings `None`, compatibilidade Gemma `json_object`, legibilidade de blocos de código escuros.
+> **[2026.4.28]** [v1.3.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.1) — Estabilidade: roteamento RAG mais seguro e validação de embeddings, persistência Docker, entrada segura com IME, robustez Windows/GBK.
-> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — Book Engine: compilador multiagente de «livros vivos» com 14 tipos de blocos, espaço de trabalho Co-Writer multidocumento, visualizações HTML interativas, menções @ do banco de questões no chat, fase 2 de externalização de prompts e reformulação da barra lateral.
+> **[2026.4.27]** [v1.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.0) — Índices KB versionados com fluxo de reindexação, espaço de conhecimento reconstruído, autodetecção de embeddings com novos adaptadores, hub Space.
-> **[2026.4.18]** [v1.1.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.2) — Aba Channels orientada por schema com mascaramento de segredos; RAG unificado em um único pipeline; reforço de consistência RAG/KB; prompts de chat externalizados; README em tailandês.
+> **[2026.4.25]** [v1.2.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.5) — Anexos de chat persistentes com gaveta de pré-visualização, pipelines de capacidade cientes de anexos, exportação Markdown do TutorBot.
-> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — «Responder agora» universal em todas as capacidades; sincronização de rolagem no Co-Writer; seleção de mensagens ao salvar no caderno; painel de configurações unificado; botão Stop em streaming; gravação atômica da configuração do TutorBot.
+> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — Anexos de texto / código / SVG, tour de configuração em um comando, exportação do chat Markdown, UI compacta de gestão de KB.
+
+> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — Anexos de documentos (PDF/DOCX/XLSX/PPTX), exibição do bloco de raciocínio, editor de modelos Soul, salvar no caderno a partir do Co-Writer.
+
+> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — Skills criados pelo usuário, melhoria de desempenho do input de chat, início automático do TutorBot, UI da biblioteca de livros, visualização em tela cheia.
+
+> **[2026.4.21]** [v1.2.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.1) — Limites de tokens por etapa, regenerar resposta em todos os pontos de entrada, correções de compatibilidade RAG e Gemma.
+
+> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — Compilador Book Engine de «livros vivos», Co-Writer multidocumento, visualizações HTML interativas, menções @ do banco de questões no chat.
+
+> **[2026.4.18]** [v1.1.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.2) — Aba Channels orientada por schema, consolidação RAG em pipeline único, prompts de chat externalizados.
+
+> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — «Responder agora» universal, sincronização de rolagem no Co-Writer, painel de configurações unificado, botão Stop em streaming.
+
+
+<details>
+<summary><b>Lançamentos anteriores (há mais de 2 semanas)</b></summary>
> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) — Reformulação do parsing de LaTeX em bloco; sonda de diagnóstico LLM via `agents.yaml`; correção do encaminhamento de cabeçalhos extras; correção de UUID no SaveToNotebook; guia Docker + LLM local.
@@ -58,9 +74,6 @@
> **[2026.4.4]** [v1.0.0-beta.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.0-beta.1) — Reescrita nativa de agentes (~200k linhas): plugins Tools + Capabilities, CLI e SDK, TutorBot, Co-Writer, aprendizado guiado e memória persistente.
-<details>
-<summary><b>Lançamentos anteriores</b></summary>
-
> **[2026.1.23]** [v0.6.0](https://github.com/HKUDS/DeepTutor/releases/tag/v0.6.0) — Persistência de sessão, upload incremental, RAG flexível, localização em chinês.
> **[2026.1.18]** [v0.5.2](https://github.com/HKUDS/DeepTutor/releases/tag/v0.5.2) — Docling, logs, correções.
@@ -79,6 +92,8 @@
> **[2026.4.19]** 🎉 Alcançamos 20k estrelas em 111 dias! Obrigado pelo apoio — seguimos iterando rumo a um ensino realmente personalizado e inteligente.
+> **[2026.4.10]** 📄 Nosso artigo está no arXiv! Leia o [preprint](https://arxiv.org/abs/2604.26962) para conhecer o desenho e as ideias por trás do DeepTutor.
+
> **[2026.4.4]** Há quanto tempo! ✨ DeepTutor v1.0.0 chegou — evolução nativa de agentes com reescrita da arquitetura do zero, TutorBot e modos flexíveis sob Apache-2.0. Um novo capítulo começa!
> **[2026.2.6]** 🚀 10k estrelas em 39 dias — obrigado à comunidade!
diff --git a/assets/README/README_RU.md b/assets/README/README_RU.md
index 7ec302409..733ef0e2c 100644
--- a/assets/README/README_RU.md
+++ b/assets/README/README_RU.md
@@ -10,7 +10,7 @@
[![Next.js 16](https://img.shields.io/badge/Next.js-16-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue?style=flat-square)](../../LICENSE)
[![GitHub release](https://img.shields.io/github/v/release/HKUDS/DeepTutor?style=flat-square&color=brightgreen)](https://github.com/HKUDS/DeepTutor/releases)
-[![arXiv](https://img.shields.io/badge/arXiv-Coming_Soon-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](#)
+[![arXiv](https://img.shields.io/badge/arXiv-2604.26962-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](https://arxiv.org/abs/2604.26962)
[![Discord](https://img.shields.io/badge/Discord-Community-5865F2?style=flat-square&logo=discord&logoColor=white)](https://discord.gg/eRsjPgMU4t)
[![Feishu](https://img.shields.io/badge/Feishu-Group-00D4AA?style=flat-square&logo=feishu&logoColor=white)](../../Communication.md)
@@ -18,7 +18,7 @@
[Возможности](#key-features) · [Быстрый старт](#get-started) · [Обзор](#explore-deeptutor) · [TutorBot](#tutorbot) · [CLI](#deeptutor-cli-guide) · [Дорожная карта](#roadmap) · [Сообщество](#community)
-[🇬🇧 English](../../README.md) · [🇨🇳 中文](README_CN.md) · [🇯🇵 日本語](README_JA.md) · [🇪🇸 Español](README_ES.md) · [🇫🇷 Français](README_FR.md) · [🇸🇦 العربية](README_AR.md) · [🇮🇳 हिन्दी](README_HI.md) · [🇵🇹 Português](README_PT.md) · [🇹🇭 ภาษาไทย](README_TH.md)
+[🇬🇧 English](../../README.md) · [🇨🇳 中文](README_CN.md) · [🇯🇵 日本語](README_JA.md) · [🇪🇸 Español](README_ES.md) · [🇫🇷 Français](README_FR.md) · [🇸🇦 العربية](README_AR.md) · [🇮🇳 हिन्दी](README_HI.md) · [🇵🇹 Português](README_PT.md) · [🇹🇭 ภาษาไทย](README_TH.md) · 🇵🇱 [Polski](README_PL.md)
</div>
@@ -28,17 +28,33 @@
### 📦 Релизы
-> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — вложения документов в чат (PDF/DOCX/XLSX/PPTX), отображение «блока размышлений» у модели рассуждений, трёхсостояний `send_dimensions` для эмбеддингов, рефакторинг ядра LLM-провайдеров, редактор шаблонов Soul, сохранение в блокнот из Co-Writer, перетаскивание в базу знаний и устойчивое удаление, языковая точность при генерации вопросов.
+> **[2026.4.30]** [v1.3.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.3) — Поддержка эмбеддингов NVIDIA NIM и Gemini, единый контекст Space для истории чата / навыков / памяти, снимки сессий, устойчивость повторной индексации RAG.
-> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — пользовательские Skills (CRUD + интеграция в чат), оптимизация ввода и размещения состояния, авто-откат `response_format` для несовместимых провайдеров, исправление удалённого доступа по LAN, бейдж версии в боковой панели, вложения изображений в Deep Solve, авто-старт WebSocket TutorBot, UI библиотеки книг и полноэкранный режим визуализаций.
+> **[2026.4.29]** [v1.3.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.2) — Прозрачные URL эндпоинтов эмбеддингов, устойчивость повторной индексации RAG при неверных сохранённых векторах, очистка памяти для вывода thinking-моделей, исправление рантайма Deep Solve.
-> **[2026.4.21]** [v1.2.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.1) — лимиты токенов чата по этапам в `agents.yaml` (ответы до 8000 токенов), повторная генерация последнего ответа (CLI / WebSocket / Web UI), исправление падения RAG при `None` в эмбеддингах, совместимость Gemma с `json_object`, читаемость тёмных блоков кода.
+> **[2026.4.28]** [v1.3.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.1) — Стабильность: более безопасный роутинг RAG и проверка эмбеддингов, персистентность Docker, ввод безопасный для IME, устойчивость Windows/GBK.
-> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — Book Engine: мультиагентный компилятор «живых книг» с 14 типами блоков, многодокументный Co-Writer, интерактивные HTML-визуализации, @-упоминания банка вопросов в чате, фаза 2 выноса промптов, переработка боковой панели.
+> **[2026.4.27]** [v1.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.0) — Версионированные индексы KB с процессом переиндексации, перестроенное рабочее пространство знаний, автообнаружение эмбеддингов с новыми адаптерами, хаб Space.
-> **[2026.4.18]** [v1.1.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.2) — вкладка Channels на схеме с маскировкой секретов; единый конвейер RAG; укрепление согласованности RAG/KB; вынесенные промпты чата; README на тайском.
+> **[2026.4.25]** [v1.2.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.5) — Постоянные вложения в чате с ящиком предпросмотра, пайплайны возможностей с учётом вложений, экспорт Markdown для TutorBot.
-> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — универсальный «Ответить сейчас» во всех возможностях; синхронизация прокрутки Co-Writer; выбор сообщений при сохранении в блокнот; единая панель настроек; кнопка Stop при стриминге; атомарная запись конфигурации TutorBot.
+> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — Вложения текста / кода / SVG, тур настройки одной командой, экспорт чата в Markdown, компактный UI управления KB.
+
+> **[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, UI библиотеки книг, полноэкранные визуализации.
+
+> **[2026.4.21]** [v1.2.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.1) — Лимиты токенов по этапам, повторная генерация ответа во всех точках входа, исправления совместимости RAG и Gemma.
+
+> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — Компилятор Book Engine «живых книг», многодокументный Co-Writer, интерактивные HTML-визуализации, @-упоминания банка вопросов в чате.
+
+> **[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) — Универсальный «Ответить сейчас», синхронизация прокрутки Co-Writer, единая панель настроек, кнопка Stop при стриминге.
+
+
+<details>
+<summary><b>Прошлые релизы (более 2 недель назад)</b></summary>
> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) — переработка разбора блочных формул LaTeX; LLM-диагностика через `agents.yaml`; исправление пересылки дополнительных заголовков; исправление UUID в SaveToNotebook; руководство по Docker и локальным LLM.
@@ -58,9 +74,6 @@
> **[2026.4.4]** [v1.0.0-beta.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.0-beta.1) — агентно-нативная переработка (~200k строк): плагины Tools + Capabilities, CLI и SDK, TutorBot, Co-Writer, Guided Learning и постоянная память.
-<details>
-<summary><b>Прошлые релизы</b></summary>
-
> **[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) — Docling, логи, исправления.
@@ -79,6 +92,8 @@
> **[2026.4.19]** 🎉 20k звёзд за 111 дней! Спасибо за поддержку — продолжим итерации к по-настоящему персональному и умному обучению.
+> **[2026.4.10]** 📄 Наша статья опубликована на arXiv! Читайте [препринт](https://arxiv.org/abs/2604.26962), чтобы узнать о дизайне и идеях DeepTutor.
+
> **[2026.4.4]** Давно не виделись! ✨ Вышел DeepTutor v1.0.0 — агентно-нативная эволюция: архитектура переписана с нуля, TutorBot и гибкие режимы под Apache-2.0. Начинается новая глава!
> **[2026.2.6]** 🚀 10k звёзд за 39 дней — спасибо сообществу!
diff --git a/assets/README/README_TH.md b/assets/README/README_TH.md
index aa6fa0010..83e16f7ab 100644
--- a/assets/README/README_TH.md
+++ b/assets/README/README_TH.md
@@ -10,7 +10,7 @@
[![Next.js 16](https://img.shields.io/badge/Next.js-16-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue?style=flat-square)](../../LICENSE)
[![GitHub release](https://img.shields.io/github/v/release/HKUDS/DeepTutor?style=flat-square&color=brightgreen)](https://github.com/HKUDS/DeepTutor/releases)
-[![arXiv](https://img.shields.io/badge/arXiv-Coming_Soon-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](#)
+[![arXiv](https://img.shields.io/badge/arXiv-2604.26962-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](https://arxiv.org/abs/2604.26962)
[![Discord](https://img.shields.io/badge/Discord-Community-5865F2?style=flat-square&logo=discord&logoColor=white)](https://discord.gg/eRsjPgMU4t)
[![Feishu](https://img.shields.io/badge/Feishu-Group-00D4AA?style=flat-square&logo=feishu&logoColor=white)](../../Communication.md)
@@ -18,7 +18,7 @@
[คุณสมบัติเด่น](#-คุณสมบัติเด่น) · [เริ่มต้นใช้งาน](#-เริ่มต้นใช้งาน) · [สำรวจความสามารถ](#-สำรวจ-deeptutor) · [TutorBot](#-tutorbot--ติวเตอร์-ai-แบบถาวรและอัตโนมัติ) · [CLI](#%EF%B8%8F-deeptutor-cli--อินเทอร์เฟซแบบ-agent-native) · [ชุมชน](#-ชุมชนและระบบนิเวศ)
-[🇺🇸 English](../../README.md) · [🇨🇳 中文](README_CN.md) · [🇯🇵 日本語](README_JA.md) · [🇪🇸 Español](README_ES.md) · [🇫🇷 Français](README_FR.md) · [🇸🇦 العربية](README_AR.md) · [🇷🇺 Русский](README_RU.md) · [🇮🇳 हिन्दी](README_HI.md) · [🇵🇹 Português](README_PT.md) · [🇹🇭 ภาษาไทย](README_TH.md)
+[🇺🇸 English](../../README.md) · [🇨🇳 中文](README_CN.md) · [🇯🇵 日本語](README_JA.md) · [🇪🇸 Español](README_ES.md) · [🇫🇷 Français](README_FR.md) · [🇸🇦 العربية](README_AR.md) · [🇷🇺 Русский](README_RU.md) · [🇮🇳 हिन्दी](README_HI.md) · [🇵🇹 Português](README_PT.md) · [🇹🇭 ภาษาไทย](README_TH.md) · 🇵🇱 [Polski](README_PL.md)
</div>
@@ -28,17 +28,33 @@
### 📦 ประวัติการเผยแพร่
-> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — แนบเอกสารในแชต (PDF/DOCX/XLSX/PPTX) แสดงบล็อกการคิดของโมเดลให้เหตุผล สลับสามสถานะ `send_dimensions` ของ embedding รีแฟกเตอร์แกน LLM provider ตัวแก้เทมเพลต Soul บันทึก Co-Writer ลงสมุด ลากวางอัปโหลด knowledge base แก้การลบให้ทนทาน ความตรงภาษาในการสร้างคำถาม
+> **[2026.4.30]** [v1.3.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.3) — รองรับ embedding NVIDIA NIM และ Gemini, Space context รวมสำหรับประวัติแชต / สกิล / หน่วยความจำ, snapshot ของเซสชัน, ความทนทานของการทำดัชนี RAG ใหม่
-> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — ระบบ Skills ที่ผู้ใช้สร้าง (CRUD + ผสานแชต) ปรับประสิทธิ์ช่องแชตกับ state colocation `response_format` fallback อัตโนมัติเมื่อ provider ไม่รองรับ แก้ remote LAN ป้ายเวอร์ชันแถบข้าง แนบรูป Deep Solve TutorBot WebSocket สตาร์ทอัตโนมัติ UI ห้องสมุดหนังสือ โหมดเต็มจอ visualization
+> **[2026.4.29]** [v1.3.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.2) — URL ปลายทาง embedding โปร่งใส, ความทนทาน re-index RAG เมื่อเวกเตอร์ที่ persist ไม่ถูกต้อง, ทำความสะอาดหน่วยความจำสำหรับเอาต์พุตโมเดล thinking, แก้รันไทม์ Deep Solve
-> **[2026.4.21]** [v1.2.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.1) — กำหนดขีดจำกัดโทเคนต่อขั้นตอนใน `agents.yaml` (คำตอบ 8000 โทเคน), สร้างคำตอบล่าสุดใหม่ใน CLI / WebSocket / Web UI, แก้แครช RAG เมื่อ embedding เป็น `None`, รองรับ Gemma `json_object`, ปรับความอ่านง่ายของโค้ดบล็อกสีเข้ม
+> **[2026.4.28]** [v1.3.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.1) — เสถียรภาพ: RAG routing ปลอดภัยขึ้นและตรวจสอบ embedding, Docker persistence, อินพุตปลอดภัยกับ IME, ความทนทาน Windows/GBK
-> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — Book Engine คอมไพเลอร์หนังสือมีชีวิตแบบหลายเอเจนต์พร้อม 14 ประเภทบล็อก, พื้นที่ทำงาน Co-Writer หลายเอกสาร, การแสดงผล HTML แบบโต้ตอบ, @-mention ธนาคารคำถามในแชต, การแยก prompt ระยะที่ 2, และปรับปรุงแถบด้านข้าง
+> **[2026.4.27]** [v1.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.0) — ดัชนี KB แบบมีเวอร์ชันพร้อมเวิร์กโฟลว์ re-index, รีบิลด์ Knowledge workspace, embedding auto-discovery กับอะแดปเตอร์ใหม่, Space hub
-> **[2026.4.18]** [v1.1.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.2) — แท็บ Channels แบบ schema-driven พร้อมการปกปิดความลับ (secret masking) รวม RAG เป็น pipeline เดียว ปรับปรุงความสอดคล้อง RAG/KB แยก chat prompts ออกเป็นไฟล์ภายนอก และ README ภาษาไทย
+> **[2026.4.25]** [v1.2.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.5) — แนบไฟล์ในแชตถาวรพร้อมลิ้นชักพรีวิว, pipeline ความสามารถที่รับรู้แนบไฟล์, ส่งออก Markdown ของ TutorBot
-> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — ปุ่ม "ตอบเลย" ข้ามการ reasoning ได้ทุก capability, Co-Writer ปรับขนาด split + scroll sync ตามบรรทัด, บันทึกข้อความลง Notebook แบบเลือก message, ระบบ Notebook จริงครอบคลุม Knowledge/Guide/Save, แผงตั้งค่ารวมแบบพับได้, ปุ่ม Stop รอบการ streaming, refactor TutorBot config manager แบบ atomic write, ปรับ Light/Snow theme ใหม่ และขยาย test suite
+> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — แนบข้อความ / โค้ด / SVG, Setup Tour คำสั่งเดียว, ส่งออกแชต Markdown, UI จัดการ KB แบบกะทัดรัด
+
+> **[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 สตาร์ทอัตโนมัติ, UI ห้องสมุดหนังสือ, โหมดเต็มจอของการแสดงผล
+
+> **[2026.4.21]** [v1.2.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.1) — จำกัดโทเคนต่อขั้นตอน, สร้างคำตอบใหม่ได้ทุกจุดเข้า, แก้ความเข้ากันได้ของ RAG และ Gemma
+
+> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — คอมไพเลอร์ Book Engine «หนังสือมีชีวิต», Co-Writer หลายเอกสาร, การแสดงผล HTML แบบโต้ตอบ, @-mention ธนาคารคำถามในแชต
+
+> **[2026.4.18]** [v1.1.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.2) — แท็บ Channels แบบ schema-driven, รวม RAG เป็น pipeline เดียว, แยก chat prompts ออกเป็นไฟล์ภายนอก
+
+> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — ปุ่ม "ตอบเลย" ครอบคลุมทุกความสามารถ, Co-Writer scroll sync, แผงตั้งค่ารวม, ปุ่ม Stop ระหว่างสตรีม
+
+
+<details>
+<summary><b>รุ่นที่ผ่านมา (มากกว่า 2 สัปดาห์ที่แล้ว)</b></summary>
> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) — ปรับปรุงการ parse LaTeX block math, ตั้งค่า LLM probe ผ่าน agents.yaml, forward extra headers ใน LLM factory, แก้ UUID ของ SaveToNotebookModal, คำแนะนำ Docker + local LLM และขยาย test suite
@@ -58,9 +74,6 @@
> **[2026.4.4]** [v1.0.0-beta.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.0-beta.1) — เขียนสถาปัตยกรรมใหม่แบบ Agent-native (~200k บรรทัด) พร้อมโมเดลปลั๊กอิน 2 ชั้น (Tools + Capabilities), CLI & SDK entry points, TutorBot มัลติแชนแนล, Co-Writer, Guided Learning และ persistent memory
-<details>
-<summary><b>รุ่นเก่า</b></summary>
-
> **[2026.1.23]** [v0.6.0](https://github.com/HKUDS/DeepTutor/releases/tag/v0.6.0) — Session persistence, อัปโหลดเอกสารเพิ่มทีละไฟล์, import RAG pipeline ที่ยืดหยุ่น และ localization ภาษาจีนครบ
> **[2026.1.18]** [v0.5.2](https://github.com/HKUDS/DeepTutor/releases/tag/v0.5.2) — รองรับ Docling สำหรับ RAG-Anything, ปรับ logging system และแก้บั๊ก
@@ -79,6 +92,8 @@
> **[2026.4.19]** 🎉 ครบ 20k ดาวหลัง 111 วัน! ขอบคุณที่สนับสนุน — เราจะพัฒนาต่อเพื่อติวเตอร์เชิงบุคคลและฉลาดอย่างแท้จริง
+> **[2026.4.10]** 📄 งานวิจัยของเราลง arXiv แล้ว! อ่าน [พรีปรินต์](https://arxiv.org/abs/2604.26962) เพื่อทำความเข้าใจการออกแบบและแนวคิดของ DeepTutor
+
> **[2026.4.4]** นานมาแล้ว ✨ DeepTutor v1.0.0 มาถึงแล้ว — วิวัฒนาการแบบ agent-native ที่เขียนสถาปัตยกรรมใหม่ตั้งแต่ต้น พร้อม TutorBot และการสลับโหมดอย่างยืดหยุ่น ภายใต้สัญญาอนุญาต Apache-2.0 บทใหม่เริ่มต้นขึ้น เรื่องราวของเรายังดำเนินต่อไป!
> **[2026.2.6]** 🚀 เราไปถึง 10,000 ดาวภายในเพียง 39 วัน! ขอบคุณชุมชนที่ยอดเยี่ยมของเราสำหรับการสนับสนุน!
diff --git a/assets/releases/ver1-3-4.md b/assets/releases/ver1-3-4.md
new file mode 100644
index 000000000..16cadfd4c
--- /dev/null
+++ b/assets/releases/ver1-3-4.md
@@ -0,0 +1,142 @@
+# DeepTutor v1.3.4 Release Notes
+
+**Release Date:** 2026.05.01
+
+v1.3.4 turns the Book Engine and chat workspace into a tighter learning loop:
+book pages can now carry their own persistent chat sessions, books can be
+rebuilt from an existing spine, and regular chat turns can cite selected book
+pages alongside Space context. This release also improves language consistency,
+DeepSeek-style reasoning output handling, document extraction for RAG, logging
+infrastructure, and the public documentation around DeepTutor's arXiv paper.
+
+## Highlights
+
+### Book Engine, Page Chat, and Book References
+
+Book generation and reading now preserve more of the user's context and make it
+easier to iterate on a generated book without starting over.
+
+- **Book page chat uses the unified stream protocol** - the page chat panel now
+ uses the shared WebSocket client and stream-event renderer used by the main
+ chat workspace, so tool output, assistant events, attachments, and restored
+ session history behave consistently.
+- **Page chat sessions are persisted per book page** - each page can be bound to
+ a chat `session_id` through the new page-chat-session API, and reopening the
+ reader restores the page's conversation when available.
+- **Books can be rebuilt from the approved spine** - the new rebuild flow clears
+ generated page content and progress while keeping the confirmed outline, then
+ restarts compilation from that structure.
+- **Single-page regeneration keeps learner notes** - forced recompilation can
+ reset generated content while preserving user-authored note blocks and key
+ transition metadata.
+- **Regular chat can cite book pages** - the chat composer can attach selected
+ books and pages as request context, persist them in the turn snapshot, restore
+ them when sessions hydrate, and show them as removable context chips.
+- **Book context is cleaner for reasoning models** - selected book pages are
+ converted into bounded text references with thinking tags stripped before they
+ are injected into chat or page-side conversations.
+
+### Chat Language and Reasoning-Model Behavior
+
+Chat turns now follow the user's current language setting more reliably and are
+more tolerant of providers that return reasoning content differently.
+
+- **Language is part of each chat turn** - WebSocket requests can carry the
+ current language, and both agentic chat and classic chat append explicit
+ language instructions so answers match the active UI language.
+- **Regenerate and Answer Now use the current app language** - new turns and
+ regenerated turns read the latest stored language instead of relying only on
+ older session preferences.
+- **DeepSeek-style empty-content responses recover better** - OpenAI-compatible
+ providers can fall back to `reasoning_content` when a model returns an empty
+ visible `content` field.
+- **Book block writing can tune reasoning effort** - LLM-backed book block
+ generation now passes `reasoning_effort`, and structured JSON retries can
+ lower effort when reasoning-heavy models fail to return parseable JSON.
+
+### RAG, Documents, and Knowledge Base Recovery
+
+Document ingestion now uses the same extraction path across more file types and
+keeps re-indexing available in more recovery states.
+
+- **Office files route through parser extraction** - `.xlsx` and `.pptx` files
+ now join PDF and DOCX in the parser-backed routing path, with spreadsheet and
+ presentation categories available to downstream RAG logic.
+- **LlamaIndex loading uses shared document extraction** - parser-routed files
+ are read through `extract_text_from_path()`, use file-type-specific size
+ limits, and avoid unnecessary character truncation during indexing.
+- **DOCX extraction has a safer fallback path** - when `python-docx` cannot read
+ a file, the extractor can parse OOXML content through `defusedxml` instead of
+ failing immediately.
+- **Knowledge Base re-index controls are less fragile** - the web UI can expose
+ re-index actions for error and mismatch states without requiring an already
+ initialized RAG runtime, as long as source documents are available.
+- **Scanned or empty documents fail more clearly** - extraction and validation
+ now distinguish byte limits, character limits, empty parsed content, and
+ unsupported parser results more consistently.
+
+### Settings, Runtime State, and Logging
+
+This release continues the infrastructure cleanup needed for long-running local
+and server deployments.
+
+- **Settings shows clearer runtime state** - backend, LLM, embedding, and search
+ status are displayed as service cards with online state, timestamps, runtime
+ model details, and pending-apply indicators.
+- **`LLM_REASONING_EFFORT` is configurable** - reasoning effort can be supplied
+ through environment configuration and is included in runtime summaries.
+- **Logging uses the standard logger surface** - routers, agents, providers, RAG
+ code, and TutorBot integrations move away from the old custom logger module
+ toward standard `logging.getLogger(__name__)` usage plus a focused Loguru
+ bridge.
+- **Raw RAG debug log forwarding is quieter** - the RAG service no longer
+ forwards low-level logging handler output into user-facing event streams by
+ default.
+- **CI and lint coverage were refreshed** - workflow and test changes cover the
+ logging configuration path, process-log streaming, and lint consistency.
+
+### Documentation and Localization
+
+The project documentation now reflects the paper release and keeps localized
+README files aligned with the latest release cadence.
+
+- **The arXiv paper is linked from the README** - the main README badge and News
+ section now point to `2604.26962`.
+- **Localized READMEs were refreshed** - translated README files include the
+ latest release list, arXiv/news updates, and the expanded language navigation.
+- **Book, chat, settings, and rebuild copy is localized** - English and Chinese
+ app strings now cover the new Book chat, rebuild, language, attachment, and
+ runtime-state surfaces.
+
+## Tests
+
+- Added chat-language prompt coverage for per-turn language directives and
+ language-aware agentic chat behavior.
+- Added Book Engine coverage for book context extraction, page-chat session
+ binding, rebuild controls, forced page recompilation, and LLM JSON writing.
+- Added RAG and document-loader coverage for parser-routed files, Office
+ extraction paths, file-size limits, and re-index eligibility helpers.
+- Added provider/runtime coverage for `LLM_REASONING_EFFORT`, OpenAI-compatible
+ reasoning fallback behavior, and provider runtime summaries.
+- Added logging tests for configuration, context propagation, Loguru bridging,
+ process-log extraction, and task log streaming.
+- Updated frontend tests for document attachment handling, version reporting,
+ and Knowledge Base re-index helper behavior.
+
+## Upgrade Notes
+
+- CLI and server installs should refresh dependencies after upgrading. The CLI
+ extra and `requirements/cli.txt` now include `defusedxml>=0.7.1` for safer
+ XML parsing during Office document extraction.
+- Custom WebSocket clients can pass `book_references` and `language` on turn
+ start messages. Clients that persist request snapshots should store book
+ references alongside notebooks, history, skills, memory, and attachments.
+- Deployments that use reasoning models can set `LLM_REASONING_EFFORT` to tune
+ reasoning effort globally; per-profile and per-model values remain available
+ as lower-priority fallbacks.
+- Integrations that consumed raw RAG debug log events should rely on structured
+ status and tool events instead of low-level forwarded logger output.
+- Book clients should call the new page-chat-session and rebuild APIs when they
+ need page-level conversation persistence or spine-preserving regeneration.
+
+**Full Changelog**: https://github.com/HKUDS/DeepTutor/compare/v1.3.3...v1.3.4
diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.py
index 1088fb891..54140d573 100644
--- a/deeptutor/agents/chat/agentic_pipeline.py
+++ b/deeptutor/agents/chat/agentic_pipeline.py
@@ -34,6 +34,7 @@ from deeptutor.services.llm import (
stream as llm_stream,
)
from deeptutor.services.prompt import get_prompt_manager
+from deeptutor.services.prompt.language import append_language_directive
from deeptutor.tools.builtin import BUILTIN_TOOL_NAMES
from deeptutor.utils.json_parser import parse_json_response
@@ -518,7 +519,7 @@ class AgenticChatPipeline:
trace_meta = build_trace_metadata(
call_id=new_call_id("chat-answer-now"),
phase="responding",
- label="Answer now",
+ label=self._t("labels.answer_now", default="Answer now"),
call_kind="llm_final_response",
trace_id="chat-answer-now",
trace_role="response",
@@ -1381,11 +1382,12 @@ class AgenticChatPipeline:
)
has_rag = "rag" in enabled_tools
rag_hint = self._t("responding.rag_hint") if has_rag else ""
- return self._t(
+ system_prompt = self._t(
"responding.system",
tool_list=tool_list or self._fallback_empty_tool_list(),
rag_hint=rag_hint,
)
+ return append_language_directive(system_prompt, self.language)
def _acting_user_prompt(self, context: UnifiedContext, thinking_text: str) -> str:
return self._t(
diff --git a/deeptutor/agents/chat/chat_agent.py b/deeptutor/agents/chat/chat_agent.py
index 6e6bc86e7..f532c9443 100644
--- a/deeptutor/agents/chat/chat_agent.py
+++ b/deeptutor/agents/chat/chat_agent.py
@@ -15,6 +15,7 @@ from typing import Any, AsyncGenerator
from deeptutor.agents.base_agent import BaseAgent
from deeptutor.runtime.registry.tool_registry import get_tool_registry
+from deeptutor.services.prompt.language import append_language_directive
class ChatAgent(BaseAgent):
@@ -245,7 +246,12 @@ class ChatAgent(BaseAgent):
"""
messages = []
- system_parts = [self.get_prompt("system", "You are a helpful AI assistant.")]
+ system_parts = [
+ append_language_directive(
+ self.get_prompt("system", "You are a helpful AI assistant."),
+ self.language,
+ )
+ ]
if context:
context_template = self.get_prompt("context_template", "Reference context:\n{context}")
system_parts.append(context_template.format(context=context))
diff --git a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml b/deeptutor/agents/chat/prompts/en/agentic_chat.yaml
index ef7cc6e14..f825579a5 100644
--- a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml
+++ b/deeptutor/agents/chat/prompts/en/agentic_chat.yaml
@@ -12,6 +12,7 @@ labels:
final_response: "Final response"
tool_call: "Tool call"
retrieve: "Retrieve"
+ answer_now: "Answer now"
# ---------------------------------------------------------------------------
# Thinking stage
diff --git a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml b/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml
index 47f01f53e..68074b8c1 100644
--- a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml
+++ b/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml
@@ -7,11 +7,12 @@
# 各阶段标签(用于 trace metadata,前端展示)
# ---------------------------------------------------------------------------
labels:
- reasoning: "Reasoning"
- observation: "Observation"
- final_response: "Final response"
- tool_call: "Tool call"
- retrieve: "Retrieve"
+ reasoning: "推理中"
+ observation: "整理观察"
+ final_response: "生成回答"
+ tool_call: "调用工具"
+ retrieve: "检索"
+ answer_now: "直接回答"
# ---------------------------------------------------------------------------
# Thinking 阶段
diff --git a/deeptutor/api/routers/book.py b/deeptutor/api/routers/book.py
index 58e8f02ad..4706e38b5 100644
--- a/deeptutor/api/routers/book.py
+++ b/deeptutor/api/routers/book.py
@@ -124,6 +124,17 @@ class SupplementRequest(BaseModel):
topic: str
+class PageChatSessionRequest(BaseModel):
+ book_id: str
+ page_id: str
+ session_id: str
+
+
+class RebuildBookRequest(BaseModel):
+ book_id: str
+ auto_compile: bool = True
+
+
# ─────────────────────────────────────────────────────────────────────────────
# REST endpoints
# ─────────────────────────────────────────────────────────────────────────────
@@ -435,6 +446,32 @@ async def supplement(req: SupplementRequest) -> dict[str, Any]:
return {"block": block.model_dump(mode="json")}
[email protected]("/books/page-chat-session")
+async def set_page_chat_session(req: PageChatSessionRequest) -> dict[str, Any]:
+ engine = get_book_engine()
+ book = engine.set_page_chat_session(
+ book_id=req.book_id,
+ page_id=req.page_id,
+ session_id=req.session_id,
+ )
+ if book is None:
+ raise HTTPException(status_code=404, detail="Book or page not found")
+ return {"book": book.model_dump(mode="json")}
+
+
[email protected]("/books/rebuild")
+async def rebuild_book(req: RebuildBookRequest) -> dict[str, Any]:
+ engine = get_book_engine()
+ try:
+ pages = await engine.rebuild_book(book_id=req.book_id, auto_compile=req.auto_compile)
+ except ValueError as exc:
+ raise HTTPException(status_code=404, detail=str(exc))
+ except Exception as exc: # noqa: BLE001
+ logger.error(f"rebuild_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]}
+
+
# ─────────────────────────────────────────────────────────────────────────────
# WebSocket – streamed Book events
# ─────────────────────────────────────────────────────────────────────────────
diff --git a/deeptutor/api/routers/chat.py b/deeptutor/api/routers/chat.py
index 8ef19bba9..6467e122c 100644
--- a/deeptutor/api/routers/chat.py
+++ b/deeptutor/api/routers/chat.py
@@ -112,8 +112,16 @@ async def websocket_chat(websocket: WebSocket):
while True:
# Receive message
data = await websocket.receive_json()
- # Use current UI language (fallback to config/main.yaml system.language)
- language = get_ui_language(default=config.get("system", {}).get("language", "en"))
+ # Prefer the client-sent UI language for this turn; fall back to
+ # persisted Settings so prompt loading tracks the language switch.
+ requested_language = str(data.get("language") or "").lower().strip()
+ language = (
+ "zh"
+ if requested_language.startswith("zh")
+ else "en"
+ if requested_language.startswith("en")
+ else get_ui_language(default=config.get("system", {}).get("language", "en"))
+ )
message = data.get("message", "").strip()
session_id = data.get("session_id")
explicit_history = data.get("history") # Optional override
diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.py
index 81b6e1157..5500dccef 100644
--- a/deeptutor/api/routers/knowledge.py
+++ b/deeptutor/api/routers/knowledge.py
@@ -1094,7 +1094,8 @@ async def reindex_knowledge_base(
try:
manager = get_kb_manager()
kb_name = _resolve_registered_kb_name(manager, kb_name)
- _load_kb_entry_or_404(manager, kb_name)
+ kb_entry = _load_kb_entry_or_404(manager, kb_name)
+ force_reindex = str(kb_entry.get("status") or "").lower() == "error"
from deeptutor.services.rag.embedding_signature import signature_from_embedding_config
from deeptutor.services.rag.index_versioning import (
@@ -1113,7 +1114,7 @@ async def reindex_knowledge_base(
kb_dir = _kb_base_dir / kb_name
matching_version = find_matching_version(kb_dir, signature)
- if matching_version and matching_version.get("layout") == "flat":
+ if matching_version and matching_version.get("layout") == "flat" and not force_reindex:
return {
"message": (
f"Knowledge base '{kb_name}' already has an index for the "
diff --git a/deeptutor/book/blocks/_llm_writer.py b/deeptutor/book/blocks/_llm_writer.py
index 0fc8ad582..034a47d3f 100644
--- a/deeptutor/book/blocks/_llm_writer.py
+++ b/deeptutor/book/blocks/_llm_writer.py
@@ -18,6 +18,7 @@ from deeptutor.services.llm import (
complete as llm_complete,
)
from deeptutor.services.prompt.language import append_language_directive
+from deeptutor.utils.json_parser import parse_json_response
async def llm_text(
@@ -28,6 +29,7 @@ async def llm_text(
temperature: float = 0.4,
response_format: dict[str, Any] | None = None,
language: str | None = None,
+ reasoning_effort: str | None = None,
) -> str:
"""Run an LLM completion for a Book block / agent.
@@ -47,6 +49,8 @@ async def llm_text(
kwargs.update(get_token_limit_kwargs(model, max_tokens))
if response_format:
kwargs["response_format"] = response_format
+ if reasoning_effort is not None:
+ kwargs["reasoning_effort"] = reasoning_effort
response = await llm_complete(
prompt=user_prompt,
system_prompt=system_prompt,
@@ -60,4 +64,70 @@ async def llm_text(
return clean_thinking_tags(response, binding, model).strip()
-__all__ = ["llm_text"]
+def _normalize_json_payload(data: Any, expected_key: str | None = None) -> dict[str, Any]:
+ """Normalize common LLM JSON shapes into an object for block generators."""
+ if isinstance(data, dict):
+ return data
+
+ if isinstance(data, list):
+ if expected_key:
+ if len(data) == 1 and isinstance(data[0], dict) and expected_key in data[0]:
+ return data[0]
+ return {expected_key: data}
+ if len(data) == 1 and isinstance(data[0], dict):
+ return data[0]
+
+ return {}
+
+
+def _json_has_expected(data: dict[str, Any], expected_key: str | None) -> bool:
+ if not data:
+ return False
+ if expected_key is None:
+ return True
+ value = data.get(expected_key)
+ return bool(value)
+
+
+async def llm_json(
+ *,
+ user_prompt: str,
+ system_prompt: str,
+ max_tokens: int = 1200,
+ temperature: float = 0.4,
+ language: str | None = None,
+ expected_key: str | None = None,
+) -> dict[str, Any]:
+ """Run a structured JSON LLM call with robust parsing and one safe retry.
+
+ Reasoning models can spend the whole response budget on hidden/scratchpad
+ tokens and leave the visible JSON object empty. For structured book blocks
+ we first honor the configured reasoning mode, then retry once with minimal
+ reasoning if parsing fails or the expected top-level key is missing.
+ """
+
+ async def _once(reasoning_effort: str | None) -> dict[str, Any]:
+ raw = await llm_text(
+ user_prompt=user_prompt,
+ system_prompt=system_prompt,
+ max_tokens=max_tokens,
+ temperature=temperature,
+ response_format={"type": "json_object"},
+ language=language,
+ reasoning_effort=reasoning_effort,
+ )
+ parsed = parse_json_response(raw, fallback={})
+ return _normalize_json_payload(parsed, expected_key=expected_key)
+
+ data = await _once(None)
+ if _json_has_expected(data, expected_key):
+ return data
+
+ retry_data = await _once("minimal")
+ if _json_has_expected(retry_data, expected_key):
+ retry_data.setdefault("_metadata", {})["reasoning_retry"] = "minimal"
+ return retry_data
+ return data or retry_data
+
+
+__all__ = ["llm_json", "llm_text"]
diff --git a/deeptutor/book/blocks/base.py b/deeptutor/book/blocks/base.py
index 172d0e508..2dee46db3 100644
--- a/deeptutor/book/blocks/base.py
+++ b/deeptutor/book/blocks/base.py
@@ -35,6 +35,42 @@ class GenerationFailure(Exception):
"""Raised by a generator to mark the block as ERROR."""
+def _classify_failure(message: str) -> str:
+ lower = (message or "").lower()
+ if "json" in lower or "object found" in lower or "parse" in lower:
+ return "json_parse"
+ if "empty" in lower or "did not return" in lower or "returned no" in lower:
+ return "empty_response"
+ if "timeout" in lower or "timed out" in lower or "stalled" in lower:
+ return "timeout"
+ if "rate limit" in lower or "429" in lower:
+ return "rate_limit"
+ if "<think" in lower or "reasoning_content" in lower or "prompt" in lower:
+ return "prompt_leak"
+ if "api" in lower or "llm" in lower or "provider" in lower:
+ return "provider_error"
+ return "generator_error"
+
+
+def _failure_metadata(exc: Exception, source: str) -> dict[str, Any]:
+ message = str(exc)
+ kind = _classify_failure(message)
+ return {
+ "kind": kind,
+ "message": message,
+ "retryable": kind
+ in {
+ "json_parse",
+ "empty_response",
+ "timeout",
+ "rate_limit",
+ "provider_error",
+ "generator_error",
+ },
+ "source": source,
+ }
+
+
@dataclass
class BlockContext:
"""Everything a generator might need outside the block itself."""
@@ -92,6 +128,10 @@ class BlockGenerator(ABC):
except GenerationFailure as exc:
block.status = BlockStatus.ERROR
block.error = str(exc)
+ block.metadata = {
+ **block.metadata,
+ "failure": _failure_metadata(exc, self.__class__.__name__),
+ }
return block
except asyncio.CancelledError:
raise
@@ -99,6 +139,10 @@ class BlockGenerator(ABC):
logger.warning(f"Generator {self.__class__.__name__} raised: {exc}", exc_info=True)
block.status = BlockStatus.ERROR
block.error = str(exc)
+ block.metadata = {
+ **block.metadata,
+ "failure": _failure_metadata(exc, self.__class__.__name__),
+ }
return block
block.payload = payload or {}
@@ -106,6 +150,7 @@ class BlockGenerator(ABC):
block.source_anchors = anchors
if metadata:
block.metadata = {**block.metadata, **metadata}
+ block.metadata.pop("failure", None)
block.status = BlockStatus.READY
return block
diff --git a/deeptutor/book/blocks/code.py b/deeptutor/book/blocks/code.py
index 4f4a23558..d2da71522 100644
--- a/deeptutor/book/blocks/code.py
+++ b/deeptutor/book/blocks/code.py
@@ -10,11 +10,10 @@ Prompts live in ``deeptutor/book/prompts/{en,zh}/code.yaml``.
from __future__ import annotations
-import json
from typing import Any
from ..models import BlockType, SourceAnchor
-from ._llm_writer import llm_text
+from ._llm_writer import llm_json
from ._prompts import get_book_prompt, load_book_prompts
from .base import BlockContext, BlockGenerator, GenerationFailure
@@ -41,19 +40,19 @@ class CodeGenerator(BlockGenerator):
intent=intent,
language=language,
)
- raw = await llm_text(
+ data = await llm_json(
user_prompt=user_prompt,
system_prompt=get_book_prompt(prompts, "system"),
max_tokens=900,
temperature=0.3,
- response_format={"type": "json_object"},
language=ctx.language,
)
- data = _safe_json(raw)
code = str(data.get("code") or "").strip()
if not code:
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.")
return (
{
"language": str(data.get("language") or language).strip() or language,
@@ -62,22 +61,8 @@ class CodeGenerator(BlockGenerator):
"intent": intent,
},
[],
- {},
+ data.get("_metadata") if isinstance(data.get("_metadata"), dict) else {},
)
-def _safe_json(raw: str) -> dict[str, Any]:
- raw = raw.strip()
- if raw.startswith("```"):
- raw = raw.strip("`")
- idx = raw.find("\n")
- if idx > 0 and not raw[:idx].strip().startswith("{"):
- raw = raw[idx + 1 :]
- try:
- data = json.loads(raw)
- except json.JSONDecodeError:
- return {}
- return data if isinstance(data, dict) else {}
-
-
__all__ = ["CodeGenerator"]
diff --git a/deeptutor/book/blocks/deep_dive.py b/deeptutor/book/blocks/deep_dive.py
index d247b9f99..33d4f054a 100644
--- a/deeptutor/book/blocks/deep_dive.py
+++ b/deeptutor/book/blocks/deep_dive.py
@@ -10,11 +10,10 @@ Prompts live in ``deeptutor/book/prompts/{en,zh}/deep_dive.yaml``.
from __future__ import annotations
-import json
from typing import Any
from ..models import BlockType, SourceAnchor
-from ._llm_writer import llm_text
+from ._llm_writer import llm_json
from ._prompts import get_book_prompt, load_book_prompts
from .base import BlockContext, BlockGenerator, GenerationFailure
@@ -35,18 +34,14 @@ class DeepDiveGenerator(BlockGenerator):
chapter_title=chapter_title,
chapter_summary=chapter_summary or none_label,
)
- raw = await llm_text(
+ data = await llm_json(
user_prompt=user_prompt,
system_prompt=get_book_prompt(prompts, "system"),
max_tokens=500,
temperature=0.4,
- response_format={"type": "json_object"},
language=ctx.language,
+ expected_key="suggestions",
)
- try:
- data = json.loads(raw)
- except json.JSONDecodeError:
- data = {}
suggestions_raw = data.get("suggestions") if isinstance(data, dict) else None
suggestions: list[dict[str, str]] = []
if isinstance(suggestions_raw, list):
@@ -64,7 +59,11 @@ class DeepDiveGenerator(BlockGenerator):
)
if not suggestions:
raise GenerationFailure("LLM returned no deep-dive suggestions.")
- return ({"suggestions": suggestions}, [], {})
+ return (
+ {"suggestions": suggestions},
+ [],
+ data.get("_metadata") if isinstance(data.get("_metadata"), dict) else {},
+ )
__all__ = ["DeepDiveGenerator"]
diff --git a/deeptutor/book/blocks/flash_cards.py b/deeptutor/book/blocks/flash_cards.py
index 11009964f..f54ac2eea 100644
--- a/deeptutor/book/blocks/flash_cards.py
+++ b/deeptutor/book/blocks/flash_cards.py
@@ -8,11 +8,10 @@ Prompts live in ``deeptutor/book/prompts/{en,zh}/flash_cards.yaml``.
from __future__ import annotations
-import json
from typing import Any
from ..models import BlockType, SourceAnchor
-from ._llm_writer import llm_text
+from ._llm_writer import llm_json
from ._prompts import get_book_prompt, load_book_prompts
from .base import BlockContext, BlockGenerator, GenerationFailure
@@ -37,18 +36,14 @@ class FlashCardsGenerator(BlockGenerator):
chapter_summary=chapter_summary or none_label,
objectives_inline="; ".join(objectives) or none_label,
)
- raw = await llm_text(
+ data = await llm_json(
user_prompt=user_prompt,
system_prompt=system_prompt,
max_tokens=900,
temperature=0.4,
- response_format={"type": "json_object"},
language=ctx.language,
+ expected_key="cards",
)
- try:
- data = json.loads(raw)
- except json.JSONDecodeError:
- data = {}
cards_raw = data.get("cards") if isinstance(data, dict) else None
cards: list[dict[str, str]] = []
if isinstance(cards_raw, list):
@@ -68,7 +63,11 @@ class FlashCardsGenerator(BlockGenerator):
)
if not cards:
raise GenerationFailure("LLM did not return any flashcards.")
- return ({"cards": cards}, [], {})
+ return (
+ {"cards": cards},
+ [],
+ data.get("_metadata") if isinstance(data.get("_metadata"), dict) else {},
+ )
__all__ = ["FlashCardsGenerator"]
diff --git a/deeptutor/book/blocks/section.py b/deeptutor/book/blocks/section.py
index 719e02443..6dcc651be 100644
--- a/deeptutor/book/blocks/section.py
+++ b/deeptutor/book/blocks/section.py
@@ -22,14 +22,11 @@ for ``SectionBlock.tsx`` on the frontend (see Phase 4.d).
from __future__ import annotations
import asyncio
-import json
import logging
from typing import Any
-from deeptutor.utils.json_parser import parse_json_response
-
from ..models import BlockType, SourceAnchor, SourceChunk
-from ._llm_writer import llm_text
+from ._llm_writer import llm_json, llm_text
from ._prompts import get_book_prompt, load_book_prompts
from ._rag_helpers import optional_rag_lookup
from .base import BlockContext, BlockGenerator, GenerationFailure
@@ -189,19 +186,18 @@ class SectionGenerator(BlockGenerator):
rag_section=rag_section,
)
try:
- raw = await llm_text(
+ payload = await llm_json(
user_prompt=user_prompt,
system_prompt=get_book_prompt(prompts, "outline_system"),
max_tokens=900,
temperature=0.4,
- response_format={"type": "json_object"},
language=ctx.language,
+ expected_key="subsections",
)
except Exception as exc:
logger.warning(f"SectionGenerator outline LLM failed: {exc}")
return _fallback_outline(focus_topic, objectives, target_words, ctx.language)
- payload = parse_json_response(raw, logger_instance=logger, fallback={})
if not isinstance(payload, dict):
return _fallback_outline(focus_topic, objectives, target_words, ctx.language)
@@ -352,8 +348,3 @@ def _fallback_outline(
__all__ = ["SectionGenerator"]
-
-
-# Tiny safety net — keep ``json`` import in use even when only the
-# ``parse_json_response`` path runs (avoids ``F401`` in some lint setups).
-_unused = json # noqa: F841
diff --git a/deeptutor/book/blocks/timeline.py b/deeptutor/book/blocks/timeline.py
index 34ba9fd85..7fecab285 100644
--- a/deeptutor/book/blocks/timeline.py
+++ b/deeptutor/book/blocks/timeline.py
@@ -8,11 +8,10 @@ Prompts live in ``deeptutor/book/prompts/{en,zh}/timeline.yaml``.
from __future__ import annotations
-import json
from typing import Any
from ..models import BlockType, SourceAnchor
-from ._llm_writer import llm_text
+from ._llm_writer import llm_json
from ._prompts import get_book_prompt, load_book_prompts
from .base import BlockContext, BlockGenerator, GenerationFailure
@@ -33,18 +32,14 @@ class TimelineGenerator(BlockGenerator):
chapter_title=chapter_title,
chapter_summary=chapter_summary or none_label,
)
- raw = await llm_text(
+ data = await llm_json(
user_prompt=user_prompt,
system_prompt=get_book_prompt(prompts, "system"),
max_tokens=800,
temperature=0.4,
- response_format={"type": "json_object"},
language=ctx.language,
+ expected_key="events",
)
- try:
- data = json.loads(raw)
- except json.JSONDecodeError:
- data = {}
events_raw = data.get("events") if isinstance(data, dict) else None
events: list[dict[str, str]] = []
if isinstance(events_raw, list):
@@ -60,7 +55,11 @@ class TimelineGenerator(BlockGenerator):
)
if not events:
raise GenerationFailure("LLM did not return any timeline events.")
- return ({"events": events}, [], {})
+ return (
+ {"events": events},
+ [],
+ data.get("_metadata") if isinstance(data.get("_metadata"), dict) else {},
+ )
__all__ = ["TimelineGenerator"]
diff --git a/deeptutor/book/compiler.py b/deeptutor/book/compiler.py
index 4aaa72a6a..73cb63b3e 100644
--- a/deeptutor/book/compiler.py
+++ b/deeptutor/book/compiler.py
@@ -242,6 +242,7 @@ class BookCompiler:
"block_type": block.type.value,
"status": block.status.value,
"error": block.error,
+ "failure": block.metadata.get("failure") if block.metadata else None,
"payload_keys": list(block.payload.keys()),
},
stage=STAGE_BLOCK,
diff --git a/deeptutor/book/context.py b/deeptutor/book/context.py
new file mode 100644
index 000000000..f9030da0e
--- /dev/null
+++ b/deeptutor/book/context.py
@@ -0,0 +1,435 @@
+"""Utilities for turning selected book pages into chat context.
+
+The chat runtime consumes this module from two places:
+
+* the main chat page when a user picks pages via ``@book``;
+* the book reader side panel, which automatically references the current page.
+
+Keep this module pure and storage-backed only. It should not call an LLM or
+depend on FastAPI so it remains cheap to unit test and reuse.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+import re
+from typing import Any, Iterable, Sequence
+
+from .models import Block, BlockStatus, BlockType, Book, Chapter, Page, Spine
+from .storage import BookStorage, get_book_storage
+
+DEFAULT_MAX_CONTEXT_CHARS = 32_000
+DEFAULT_MAX_PAGE_CHARS = 12_000
+DEFAULT_MAX_BLOCK_CHARS = 4_000
+
+_THINK_RE = re.compile(r"<think\b[^>]*>.*?</think>", re.IGNORECASE | re.DOTALL)
+
+
+@dataclass(frozen=True)
+class NormalizedBookReference:
+ """One selected book with the page ids that should be sent to chat."""
+
+ book_id: str
+ page_ids: list[str]
+
+ def model_dump(self) -> dict[str, Any]:
+ return {"book_id": self.book_id, "page_ids": list(self.page_ids)}
+
+
+@dataclass
+class BookContextResult:
+ """Serialized book context plus non-fatal issues encountered while loading."""
+
+ text: str = ""
+ references: list[dict[str, Any]] = field(default_factory=list)
+ warnings: list[str] = field(default_factory=list)
+
+
+def normalize_book_references(value: Any) -> list[NormalizedBookReference]:
+ """Validate and de-duplicate the public ``book_references`` payload."""
+
+ if not isinstance(value, Sequence) or isinstance(value, (str, bytes, bytearray)):
+ return []
+
+ refs: list[NormalizedBookReference] = []
+ seen_books: set[str] = set()
+ for item in value:
+ if not isinstance(item, dict):
+ continue
+ book_id = str(item.get("book_id") or "").strip()
+ raw_page_ids = item.get("page_ids") or []
+ if (
+ not book_id
+ or not isinstance(raw_page_ids, Sequence)
+ or isinstance(raw_page_ids, (str, bytes, bytearray))
+ ):
+ continue
+
+ page_ids: list[str] = []
+ seen_pages: set[str] = set()
+ for raw_page_id in raw_page_ids:
+ page_id = str(raw_page_id or "").strip()
+ if not page_id or page_id in seen_pages:
+ continue
+ seen_pages.add(page_id)
+ page_ids.append(page_id)
+
+ if not page_ids:
+ continue
+
+ if book_id in seen_books:
+ existing = next((ref for ref in refs if ref.book_id == book_id), None)
+ if existing is not None:
+ for page_id in page_ids:
+ if page_id not in existing.page_ids:
+ existing.page_ids.append(page_id)
+ continue
+
+ seen_books.add(book_id)
+ refs.append(NormalizedBookReference(book_id=book_id, page_ids=page_ids))
+
+ return refs
+
+
+def build_book_context(
+ book_references: Any,
+ *,
+ storage: BookStorage | None = None,
+ max_chars: int = DEFAULT_MAX_CONTEXT_CHARS,
+ page_char_limit: int = DEFAULT_MAX_PAGE_CHARS,
+ block_char_limit: int = DEFAULT_MAX_BLOCK_CHARS,
+) -> BookContextResult:
+ """Load selected book pages and serialize them into compact LLM context."""
+
+ refs = normalize_book_references(book_references)
+ if not refs:
+ return BookContextResult()
+
+ store = storage or get_book_storage()
+ warnings: list[str] = []
+ sections: list[str] = []
+
+ for ref in refs:
+ book = store.load_book(ref.book_id)
+ if book is None:
+ warnings.append(f"book_not_found:{ref.book_id}")
+ continue
+
+ spine = store.load_spine(ref.book_id)
+ page_sections: list[str] = []
+ for page_id in ref.page_ids:
+ page = store.load_page(ref.book_id, page_id)
+ if page is None:
+ warnings.append(f"page_not_found:{ref.book_id}:{page_id}")
+ continue
+ chapter = spine.chapter_by_id(page.chapter_id) if spine else None
+ page_text = _serialize_page(
+ book=book,
+ spine=spine,
+ chapter=chapter,
+ page=page,
+ page_char_limit=page_char_limit,
+ block_char_limit=block_char_limit,
+ )
+ if page_text:
+ page_sections.append(page_text)
+
+ if page_sections:
+ sections.append(_serialize_book_header(book) + "\n\n" + "\n\n".join(page_sections))
+
+ text = _clip("\n\n---\n\n".join(sections), max_chars)
+ references = [ref.model_dump() for ref in refs]
+ return BookContextResult(text=text, references=references, warnings=warnings)
+
+
+def _serialize_book_header(book: Book) -> str:
+ lines = [f"# Book: {_clean(book.title) or book.id}"]
+ if book.description:
+ lines.append(f"Description: {_clip(_clean(book.description), 800)}")
+ if book.language:
+ lines.append(f"Language: {_clean(book.language)}")
+ return "\n".join(lines)
+
+
+def _serialize_page(
+ *,
+ book: Book,
+ spine: Spine | None,
+ chapter: Chapter | None,
+ page: Page,
+ page_char_limit: int,
+ block_char_limit: int,
+) -> str:
+ lines: list[str] = []
+ chapter_title = chapter.title if chapter else ""
+ lines.append(f"## Page: {_clean(page.title) or page.id}")
+ if chapter_title:
+ lines.append(f"Chapter: {_clean(chapter_title)}")
+ if chapter and chapter.summary:
+ lines.append(f"Chapter summary: {_clip(_clean(chapter.summary), 1200)}")
+ objectives = page.learning_objectives or (chapter.learning_objectives if chapter else [])
+ if objectives:
+ lines.append("Learning objectives:")
+ lines.extend(f"- {_clip(_clean(obj), 300)}" for obj in objectives if _clean(obj))
+ if page.status:
+ lines.append(f"Page status: {getattr(page.status, 'value', page.status)}")
+ if spine and spine.exploration_summary:
+ lines.append(f"Book source summary: {_clip(_clean(spine.exploration_summary), 1000)}")
+
+ block_texts = [
+ serialized
+ for block in page.blocks
+ if (serialized := _serialize_block(block, block_char_limit=block_char_limit))
+ ]
+ if block_texts:
+ lines.append("Page content:")
+ lines.extend(block_texts)
+ if page.error:
+ lines.append(f"Page error: {_clip(_clean(page.error), 600)}")
+ return _clip("\n".join(lines), page_char_limit)
+
+
+def _serialize_block(block: Block, *, block_char_limit: int) -> str:
+ block_type = _enum_value(block.type)
+ status = _enum_value(block.status)
+ if status == BlockStatus.HIDDEN.value:
+ return ""
+
+ heading = f"### Block: {_clean(block.title) or block_type}"
+ if block_type:
+ heading += f" ({block_type})"
+
+ if status != BlockStatus.READY.value:
+ details = [heading, f"Status: {status or 'unknown'}"]
+ if block.error:
+ details.append(f"Error: {_clip(_clean(block.error), 500)}")
+ return "\n".join(details)
+
+ payload = block.payload if isinstance(block.payload, dict) else {}
+ body = _payload_for_type(block_type, payload)
+ if not body and block.error:
+ body = f"Error: {_clip(_clean(block.error), 500)}"
+ if not body:
+ return ""
+ return _clip(f"{heading}\n{body}", block_char_limit)
+
+
+def _payload_for_type(block_type: str, payload: dict[str, Any]) -> str:
+ bridge = _join_text_fields(payload, ("bridge_text", "transition_in"))
+ main = ""
+ if block_type in {BlockType.TEXT.value, BlockType.USER_NOTE.value}:
+ main = _join_text_fields(payload, ("content", "body", "text", "markdown"))
+ elif block_type == BlockType.CALLOUT.value:
+ label = _clean(payload.get("label"))
+ body = _clean(payload.get("body"))
+ main = "\n".join(part for part in (label, body) if part)
+ elif block_type == BlockType.SECTION.value:
+ main = _format_section(payload)
+ elif block_type == BlockType.QUIZ.value:
+ main = _format_quiz(payload)
+ elif block_type == BlockType.FLASH_CARDS.value:
+ main = _format_flash_cards(payload)
+ elif block_type == BlockType.TIMELINE.value:
+ main = _format_timeline(payload)
+ elif block_type == BlockType.CODE.value:
+ main = _format_code(payload)
+ elif block_type == BlockType.DEEP_DIVE.value:
+ main = _format_deep_dive(payload)
+ elif block_type in {
+ BlockType.FIGURE.value,
+ BlockType.INTERACTIVE.value,
+ BlockType.ANIMATION.value,
+ BlockType.CONCEPT_GRAPH.value,
+ }:
+ main = _format_visual_summary(payload)
+ else:
+ main = _safe_payload_summary(payload)
+
+ return "\n".join(part for part in (bridge, main) if part)
+
+
+def _format_section(payload: dict[str, Any]) -> str:
+ lines: list[str] = []
+ if intro := _clean(payload.get("intro")):
+ lines.append(intro)
+ subsections = payload.get("subsections")
+ if isinstance(subsections, list):
+ for item in subsections:
+ if not isinstance(item, dict):
+ continue
+ heading = _clean(item.get("heading"))
+ body = _clean(item.get("body"))
+ focus = _clean(item.get("focus"))
+ if heading:
+ lines.append(f"#### {heading}")
+ if focus:
+ lines.append(f"Focus: {focus}")
+ if body:
+ lines.append(body)
+ if takeaway := _clean(payload.get("key_takeaway")):
+ lines.append(f"Key takeaway: {takeaway}")
+ return "\n".join(lines)
+
+
+def _format_quiz(payload: dict[str, Any]) -> str:
+ questions = payload.get("questions")
+ if not isinstance(questions, list):
+ return _join_text_fields(payload, ("topic", "question", "explanation"))
+ lines: list[str] = []
+ for idx, item in enumerate(questions[:8], start=1):
+ if not isinstance(item, dict):
+ continue
+ question = _clean(item.get("question"))
+ if not question:
+ continue
+ lines.append(f"Q{idx}: {question}")
+ options = item.get("options")
+ if isinstance(options, dict) and options:
+ option_text = "; ".join(
+ f"{_clean(key)}. {_clean(value)}" for key, value in options.items()
+ )
+ if option_text:
+ lines.append(f"Options: {option_text}")
+ if answer := _clean(item.get("correct_answer")):
+ lines.append(f"Answer: {answer}")
+ if explanation := _clean(item.get("explanation")):
+ lines.append(f"Explanation: {explanation}")
+ return "\n".join(lines)
+
+
+def _format_flash_cards(payload: dict[str, Any]) -> str:
+ cards = payload.get("cards")
+ if not isinstance(cards, list):
+ return ""
+ lines: list[str] = []
+ for idx, item in enumerate(cards[:12], start=1):
+ if not isinstance(item, dict):
+ continue
+ front = _clean(item.get("front"))
+ back = _clean(item.get("back"))
+ hint = _clean(item.get("hint"))
+ if front and back:
+ suffix = f" Hint: {hint}" if hint else ""
+ lines.append(f"Card {idx}: {front} -> {back}{suffix}")
+ return "\n".join(lines)
+
+
+def _format_timeline(payload: dict[str, Any]) -> str:
+ events = payload.get("events")
+ if not isinstance(events, list):
+ return ""
+ lines: list[str] = []
+ for item in events[:10]:
+ if not isinstance(item, dict):
+ continue
+ date = _clean(item.get("date"))
+ title = _clean(item.get("title"))
+ description = _clean(item.get("description"))
+ line = " - ".join(part for part in (date, title, description) if part)
+ if line:
+ lines.append(line)
+ return "\n".join(lines)
+
+
+def _format_code(payload: dict[str, Any]) -> str:
+ lines: list[str] = []
+ if intent := _clean(payload.get("intent")):
+ lines.append(f"Intent: {intent}")
+ if explanation := _clean(payload.get("explanation")):
+ lines.append(f"Explanation: {explanation}")
+ code = _clean(payload.get("code"))
+ if code:
+ language = _clean(payload.get("language")) or "code"
+ lines.append(f"Code ({language}):\n{_clip(code, 1200)}")
+ return "\n".join(lines)
+
+
+def _format_deep_dive(payload: dict[str, Any]) -> str:
+ suggestions = payload.get("suggestions")
+ if not isinstance(suggestions, list):
+ return ""
+ lines: list[str] = []
+ for item in suggestions[:6]:
+ if not isinstance(item, dict):
+ continue
+ topic = _clean(item.get("topic"))
+ rationale = _clean(item.get("rationale"))
+ if topic:
+ lines.append(f"- {topic}" + (f": {rationale}" if rationale else ""))
+ return "\n".join(lines)
+
+
+def _format_visual_summary(payload: dict[str, Any]) -> str:
+ lines = [_join_text_fields(payload, ("description", "summary", "caption", "chart_type"))]
+ key_points = payload.get("key_points")
+ if isinstance(key_points, list):
+ for point in key_points[:8]:
+ if text := _clean(point):
+ lines.append(f"- {text}")
+ return "\n".join(part for part in lines if part)
+
+
+def _safe_payload_summary(payload: dict[str, Any]) -> str:
+ return "\n".join(_iter_safe_strings(payload, max_items=16))
+
+
+def _iter_safe_strings(value: Any, *, max_items: int) -> Iterable[str]:
+ emitted = 0
+
+ def walk(node: Any, key: str = "") -> Iterable[str]:
+ nonlocal emitted
+ if emitted >= max_items:
+ return
+ lowered = key.lower()
+ if lowered in {"code", "html", "svg", "content", "artifact", "artifacts"}:
+ return
+ if isinstance(node, str):
+ text = _clean(node)
+ if text:
+ emitted += 1
+ yield _clip(text, 500)
+ return
+ if isinstance(node, dict):
+ for child_key, child_value in node.items():
+ yield from walk(child_value, str(child_key))
+ if emitted >= max_items:
+ break
+ elif isinstance(node, list):
+ for child in node:
+ yield from walk(child, key)
+ if emitted >= max_items:
+ break
+
+ yield from walk(value)
+
+
+def _join_text_fields(payload: dict[str, Any], keys: Sequence[str]) -> str:
+ return "\n".join(text for key in keys if (text := _clean(payload.get(key))))
+
+
+def _enum_value(value: Any) -> str:
+ return str(getattr(value, "value", value) or "")
+
+
+def _clean(value: Any) -> str:
+ text = str(value or "")
+ text = _THINK_RE.sub("", text)
+ text = text.replace("</think>", "").replace("<think>", "")
+ text = re.sub(r"\n{3,}", "\n\n", text)
+ return text.strip()
+
+
+def _clip(text: str, limit: int) -> str:
+ text = _clean(text)
+ if limit <= 0 or len(text) <= limit:
+ return text
+ head = max(0, limit - 40)
+ return text[:head].rstrip() + "\n...[truncated]"
+
+
+__all__ = [
+ "BookContextResult",
+ "NormalizedBookReference",
+ "build_book_context",
+ "normalize_book_references",
+]
diff --git a/deeptutor/book/engine.py b/deeptutor/book/engine.py
index c824ceaec..5305584f4 100644
--- a/deeptutor/book/engine.py
+++ b/deeptutor/book/engine.py
@@ -33,6 +33,7 @@ from __future__ import annotations
import asyncio
from dataclasses import dataclass, field
import logging
+import time
from typing import Any
from deeptutor.core.stream_bus import StreamBus
@@ -149,6 +150,51 @@ class BookEngine:
runtime.worker.cancel()
return self.storage.delete_book(book_id)
+ def set_page_chat_session(self, *, book_id: str, page_id: str, session_id: str) -> Book | None:
+ """Persist the chat session associated with a specific book page."""
+ book = self.storage.load_book(book_id)
+ page = self.storage.load_page(book_id, page_id)
+ clean_session_id = (session_id or "").strip()
+ if book is None or page is None or not clean_session_id:
+ return None
+
+ metadata = dict(book.metadata or {})
+ mapping = metadata.get("page_chat_sessions")
+ if not isinstance(mapping, dict):
+ mapping = {}
+ mapping[str(page_id)] = clean_session_id
+ metadata["page_chat_sessions"] = mapping
+ book.metadata = metadata
+ book.updated_at = time.time()
+ self.storage.save_book(book)
+ self.storage.append_log(
+ book_id,
+ f"page chat session mapped ({page_id} → {clean_session_id})",
+ op="page_chat",
+ )
+ return book
+
+ @staticmethod
+ def _reset_page_for_force_compile(page: Page) -> None:
+ """Reset generated block outputs while preserving user-authored notes."""
+ for block in page.blocks:
+ if block.type == BlockType.USER_NOTE:
+ continue
+ preserved_metadata = {
+ key: value
+ for key, value in (block.metadata or {}).items()
+ if key in {"transition_in", "deep_dive_page_id"}
+ }
+ block.status = BlockStatus.PENDING
+ block.payload = {}
+ block.error = ""
+ block.source_anchors = []
+ block.metadata = preserved_metadata
+ block.updated_at = time.time()
+ page.status = PageStatus.PENDING
+ page.error = ""
+ page.updated_at = time.time()
+
# ── Stage 1: Ideation ────────────────────────────────────────────────
async def create_book(
@@ -598,6 +644,56 @@ class BookEngine:
await self._enqueue_pending_pages(book_id, pages, stream=stream)
return pages
+ async def rebuild_book(
+ self,
+ *,
+ book_id: str,
+ stream: StreamBus | None = None,
+ auto_compile: bool = True,
+ ) -> list[Page]:
+ """Regenerate all pages while preserving the confirmed proposal/spine."""
+ book = self.storage.load_book(book_id)
+ spine = self.storage.load_spine(book_id)
+ 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
+
+ for page in self.storage.list_pages(book_id):
+ self.storage.delete_page(book_id, page.id)
+ for chapter in spine.chapters:
+ chapter.page_ids = []
+ self.storage.save_spine(spine)
+ self.storage.save_progress(Progress(book_id=book_id))
+
+ book.status = BookStatus.SPINE_READY
+ book.page_count = 0
+ book.updated_at = time.time()
+ self.storage.save_book(book)
+ self.storage.append_log(
+ book_id,
+ f"rebuild requested (preserve_spine=true, auto_compile={auto_compile})",
+ op="rebuild",
+ )
+
+ return await self.confirm_spine(
+ book_id=book_id,
+ edited_spine=spine,
+ stream=stream,
+ auto_compile=auto_compile,
+ )
+
# ── Stage 3-4: compile a single page (current page) ──────────────────
async def compile_page(
@@ -616,6 +712,9 @@ class BookEngine:
raise ValueError(f"Cannot compile page – missing book/spine/page ({book_id}/{page_id})")
if page.status == PageStatus.READY and not force:
return page
+ if force and page.content_type != ContentType.OVERVIEW:
+ self._reset_page_for_force_compile(page)
+ self.storage.save_page(page)
chapter = spine.chapter_by_id(page.chapter_id)
if chapter is None:
diff --git a/deeptutor/logging/process_stream.py b/deeptutor/logging/process_stream.py
index 076fa7183..8a80ec719 100644
--- a/deeptutor/logging/process_stream.py
+++ b/deeptutor/logging/process_stream.py
@@ -79,7 +79,7 @@ class ProcessLogHandler(logging.Handler):
loop = asyncio.get_running_loop()
except RuntimeError:
return
- loop.create_task(result)
+ asyncio.ensure_future(result, loop=loop)
except Exception:
self.handleError(record)
diff --git a/deeptutor/services/config/env_store.py b/deeptutor/services/config/env_store.py
index 1a61204ff..5f945174f 100644
--- a/deeptutor/services/config/env_store.py
+++ b/deeptutor/services/config/env_store.py
@@ -18,6 +18,7 @@ ENV_KEY_ORDER = (
"LLM_API_KEY",
"LLM_HOST",
"LLM_API_VERSION",
+ "LLM_REASONING_EFFORT",
"EMBEDDING_BINDING",
"EMBEDDING_MODEL",
"EMBEDDING_API_KEY",
@@ -110,6 +111,9 @@ class EnvStore:
"api_key": values.get("LLM_API_KEY", os.getenv("LLM_API_KEY", "")),
"host": values.get("LLM_HOST", os.getenv("LLM_HOST", "")),
"api_version": values.get("LLM_API_VERSION", os.getenv("LLM_API_VERSION", "")),
+ "reasoning_effort": values.get(
+ "LLM_REASONING_EFFORT", os.getenv("LLM_REASONING_EFFORT", "")
+ ),
},
embedding={
"binding": values.get(
diff --git a/deeptutor/services/config/provider_runtime.py b/deeptutor/services/config/provider_runtime.py
index 0751dea09..2c9321d56 100644
--- a/deeptutor/services/config/provider_runtime.py
+++ b/deeptutor/services/config/provider_runtime.py
@@ -421,7 +421,12 @@ def resolve_llm_runtime_config(
"api_version", ""
)
active_extra_headers = _to_headers((profile or {}).get("extra_headers"))
- reasoning_effort = _as_str((model or {}).get("reasoning_effort")) or None
+ reasoning_effort = (
+ _as_str(env_values.get("LLM_REASONING_EFFORT"))
+ or _as_str(summary.llm.get("reasoning_effort"))
+ or _as_str((model or {}).get("reasoning_effort"))
+ or None
+ )
context_window = _coerce_optional_int((model or {}).get("context_window"))
if context_window is None:
context_window = _coerce_optional_int((model or {}).get("context_window_tokens"))
diff --git a/deeptutor/services/llm/config.py b/deeptutor/services/llm/config.py
index 386d5afff..ba833c16f 100644
--- a/deeptutor/services/llm/config.py
+++ b/deeptutor/services/llm/config.py
@@ -165,6 +165,7 @@ def _get_llm_config_from_env() -> LLMConfig:
api_key = _strip_value(env_store.get("LLM_API_KEY"))
base_url = _strip_value(env_store.get("LLM_HOST"))
api_version = _strip_value(env_store.get("LLM_API_VERSION"))
+ reasoning_effort = _strip_value(env_store.get("LLM_REASONING_EFFORT"))
# Validate required configuration
if not model:
@@ -182,6 +183,7 @@ def _get_llm_config_from_env() -> LLMConfig:
api_key=api_key or "",
base_url=base_url,
api_version=api_version,
+ reasoning_effort=reasoning_effort or None,
)
diff --git a/deeptutor/services/llm/provider_core/openai_compat_provider.py b/deeptutor/services/llm/provider_core/openai_compat_provider.py
index c40d18ae0..b9579779c 100644
--- a/deeptutor/services/llm/provider_core/openai_compat_provider.py
+++ b/deeptutor/services/llm/provider_core/openai_compat_provider.py
@@ -531,6 +531,8 @@ class OpenAICompatProvider(LLMProvider):
finish_reason = ch.finish_reason
if not content and m.content:
content = m.content
+ if not content and getattr(m, "reasoning_content", None):
+ content = m.reasoning_content
if not content and getattr(m, "reasoning", None):
content = m.reasoning
diff --git a/deeptutor/services/llm/utils.py b/deeptutor/services/llm/utils.py
index b0be583c7..35b7c90d5 100644
--- a/deeptutor/services/llm/utils.py
+++ b/deeptutor/services/llm/utils.py
@@ -149,18 +149,18 @@ def clean_thinking_tags(
return ""
closed_pattern = re.compile(
- r"<\s*(?P<tag>think(?:ing)?)\b[^>]*>.*?<\s*/\s*(?P=tag)\s*>",
+ r"`?<\s*(?P<tag>think(?:ing)?)\b[^>]*>`?.*?`?<\s*/\s*(?P=tag)\s*>`?",
re.DOTALL | re.IGNORECASE,
)
cleaned = re.sub(closed_pattern, "", content)
# Streaming providers can surface a final partial block if the request is
# interrupted after reasoning has started. Never expose that scratchpad.
unclosed_pattern = re.compile(
- r"<\s*think(?:ing)?\b[^>]*>.*$",
+ r"`?<\s*think(?:ing)?\b[^>]*>`?.*$",
re.DOTALL | re.IGNORECASE,
)
cleaned = re.sub(unclosed_pattern, "", cleaned)
- cleaned = re.sub(r"<\s*/\s*think(?:ing)?\s*>", "", cleaned, flags=re.IGNORECASE)
+ cleaned = re.sub(r"`?<\s*/\s*think(?:ing)?\s*>`?", "", cleaned, flags=re.IGNORECASE)
return cleaned.strip()
diff --git a/deeptutor/services/rag/file_routing.py b/deeptutor/services/rag/file_routing.py
index d4e5f1d00..328d5122a 100644
--- a/deeptutor/services/rag/file_routing.py
+++ b/deeptutor/services/rag/file_routing.py
@@ -22,6 +22,8 @@ class DocumentType(Enum):
TEXT = "text"
MARKDOWN = "markdown"
DOCX = "docx"
+ SPREADSHEET = "spreadsheet"
+ PRESENTATION = "presentation"
IMAGE = "image"
UNKNOWN = "unknown"
@@ -39,12 +41,14 @@ class FileTypeRouter:
"""File type router for the RAG pipeline.
Classifies files before processing to route them to appropriate handlers:
- - PDF files -> PDF parsing
+ - PDF / Office files -> parser-based text extraction
- Text files -> Direct read (fast, simple)
- Unsupported -> Skip with warning
"""
- PARSER_EXTENSIONS = {".pdf"}
+ PDF_EXTENSIONS = {".pdf"}
+ OFFICE_EXTENSIONS = {".docx", ".xlsx", ".pptx"}
+ PARSER_EXTENSIONS = PDF_EXTENSIONS | OFFICE_EXTENSIONS
TEXT_EXTENSIONS = {
# Plain text & docs
@@ -169,7 +173,6 @@ class FileTypeRouter:
".dockerfile",
}
- DOCX_EXTENSIONS = {".docx", ".doc"}
IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff", ".tif"}
@classmethod
@@ -177,12 +180,16 @@ class FileTypeRouter:
"""Classify a single file by its type."""
ext = Path(file_path).suffix.lower()
- if ext in cls.PARSER_EXTENSIONS:
+ if ext in cls.PDF_EXTENSIONS:
return DocumentType.PDF
elif ext in cls.TEXT_EXTENSIONS:
return DocumentType.TEXT
- elif ext in cls.DOCX_EXTENSIONS:
+ elif ext == ".docx":
return DocumentType.DOCX
+ elif ext == ".xlsx":
+ return DocumentType.SPREADSHEET
+ elif ext == ".pptx":
+ return DocumentType.PRESENTATION
elif ext in cls.IMAGE_EXTENSIONS:
return DocumentType.IMAGE
else:
@@ -215,7 +222,12 @@ class FileTypeRouter:
for path in file_paths:
doc_type = cls.get_document_type(path)
- if doc_type == DocumentType.PDF:
+ if doc_type in (
+ DocumentType.PDF,
+ DocumentType.DOCX,
+ DocumentType.SPREADSHEET,
+ DocumentType.PRESENTATION,
+ ):
parser_files.append(path)
elif doc_type in (DocumentType.TEXT, DocumentType.MARKDOWN):
text_files.append(path)
@@ -274,7 +286,13 @@ class FileTypeRouter:
def needs_parser(cls, file_path: str) -> bool:
"""Quick check if a single file needs parser processing."""
doc_type = cls.get_document_type(file_path)
- return doc_type in (DocumentType.PDF, DocumentType.DOCX, DocumentType.IMAGE)
+ return doc_type in (
+ DocumentType.PDF,
+ DocumentType.DOCX,
+ DocumentType.SPREADSHEET,
+ DocumentType.PRESENTATION,
+ DocumentType.IMAGE,
+ )
@classmethod
def is_text_readable(cls, file_path: str) -> bool:
diff --git a/deeptutor/services/rag/pipelines/llamaindex/document_loader.py b/deeptutor/services/rag/pipelines/llamaindex/document_loader.py
index de1f84453..b22141d7d 100644
--- a/deeptutor/services/rag/pipelines/llamaindex/document_loader.py
+++ b/deeptutor/services/rag/pipelines/llamaindex/document_loader.py
@@ -9,6 +9,8 @@ from typing import Iterable
from llama_index.core import Document
from deeptutor.services.rag.file_routing import FileTypeRouter
+from deeptutor.utils.document_extractor import DocumentExtractionError, extract_text_from_path
+from deeptutor.utils.document_validator import DocumentValidator
class LlamaIndexDocumentLoader:
@@ -23,8 +25,8 @@ class LlamaIndexDocumentLoader:
for file_path_str in classification.parser_files:
file_path = Path(file_path_str)
- self.logger.info(f"Parsing PDF: {file_path.name}")
- text = self._extract_pdf_text(file_path)
+ self.logger.info(f"Parsing document: {file_path.name}")
+ text = self._extract_parser_text(file_path)
self._append_if_nonempty(documents, file_path, text)
for file_path_str in classification.text_files:
@@ -38,6 +40,18 @@ class LlamaIndexDocumentLoader:
return documents
+ def _extract_parser_text(self, file_path: Path) -> str:
+ max_bytes = (
+ DocumentValidator.MAX_PDF_SIZE
+ if file_path.suffix.lower() == ".pdf"
+ else DocumentValidator.MAX_FILE_SIZE
+ )
+ try:
+ return extract_text_from_path(file_path, max_bytes=max_bytes, max_chars=None)
+ except (DocumentExtractionError, OSError) as exc:
+ self.logger.error(f"Failed to extract {file_path.name}: {exc}")
+ return ""
+
def _append_if_nonempty(self, documents: list[Document], file_path: Path, text: str) -> None:
if text.strip():
documents.append(
@@ -52,18 +66,3 @@ class LlamaIndexDocumentLoader:
self.logger.info(f"Loaded: {file_path.name} ({len(text)} chars)")
else:
self.logger.warning(f"Skipped empty document: {file_path.name}")
-
- def _extract_pdf_text(self, file_path: Path) -> str:
- try:
- import fitz # PyMuPDF
-
- doc = fitz.open(file_path)
- texts = [page.get_text() for page in doc]
- doc.close()
- return "\n\n".join(texts)
- except ImportError:
- self.logger.warning("PyMuPDF not installed. Cannot extract PDF text.")
- return ""
- except Exception as exc:
- self.logger.error(f"Failed to extract PDF text: {exc}")
- return ""
diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.py
index c69555e74..40c51c106 100644
--- a/deeptutor/services/session/turn_runtime.py
+++ b/deeptutor/services/session/turn_runtime.py
@@ -67,6 +67,7 @@ def _request_snapshot_metadata(
notebook_references: list[Any],
history_references: list[Any],
question_notebook_references: list[Any],
+ book_references: list[Any],
requested_skills: list[str],
memory_references: Sequence[str],
) -> dict[str, Any]:
@@ -88,6 +89,8 @@ def _request_snapshot_metadata(
snapshot["historyReferences"] = history_references
if question_notebook_references:
snapshot["questionNotebookReferences"] = question_notebook_references
+ if book_references:
+ snapshot["bookReferences"] = book_references
if requested_skills:
snapshot["skills"] = requested_skills
if memory_references:
@@ -444,6 +447,12 @@ class TurnRuntimeManager:
preferences = session.get("preferences") or {}
overrides = overrides or {}
+ snapshot = {}
+ metadata = last_user.get("metadata") or {}
+ if isinstance(metadata, dict):
+ candidate = metadata.get("request_snapshot") or metadata.get("requestSnapshot")
+ if isinstance(candidate, dict):
+ snapshot = candidate
capability = str(
overrides.get("capability")
@@ -492,6 +501,11 @@ class TurnRuntimeManager:
if overrides.get("history_references") is not None
else preferences.get("history_references") or []
),
+ "book_references": list(
+ overrides.get("book_references")
+ if overrides.get("book_references") is not None
+ else snapshot.get("bookReferences") or []
+ ),
"config": config,
}
return await self.start_turn(payload)
@@ -583,6 +597,7 @@ class TurnRuntimeManager:
try:
from deeptutor.agents.notebook import NotebookAnalysisAgent
+ from deeptutor.book.context import build_book_context
from deeptutor.core.context import Attachment, UnifiedContext
from deeptutor.runtime.orchestrator import ChatOrchestrator
from deeptutor.services.llm.config import get_llm_config
@@ -601,10 +616,13 @@ class TurnRuntimeManager:
notebook_references = payload.get("notebook_references", []) or []
history_references = payload.get("history_references", []) or []
question_notebook_references = payload.get("question_notebook_references", []) or []
+ book_context_result = build_book_context(payload.get("book_references", []) or [])
+ book_references = book_context_result.references
memory_references = _extract_memory_references(payload)
notebook_context = ""
history_context = ""
question_bank_context = ""
+ book_context = book_context_result.text
import base64 as _b64
import uuid as _uuid
@@ -821,6 +839,8 @@ class TurnRuntimeManager:
context_parts: list[str] = []
if document_texts:
context_parts.append("[Attached Documents]\n" + "\n\n".join(document_texts))
+ if book_context:
+ context_parts.append(f"[Book Context]\n{book_context}")
if notebook_context:
context_parts.append(f"[Notebook Context]\n{notebook_context}")
if history_context:
@@ -850,6 +870,7 @@ class TurnRuntimeManager:
notebook_references=notebook_references,
history_references=history_references,
question_notebook_references=question_notebook_references,
+ book_references=book_references,
requested_skills=requested_skills,
memory_references=memory_references,
),
@@ -879,6 +900,9 @@ class TurnRuntimeManager:
"notebook_references": notebook_references,
"history_references": history_references,
"question_notebook_references": question_notebook_references,
+ "book_references": book_references,
+ "book_context": book_context,
+ "book_context_warnings": book_context_result.warnings,
"memory_references": memory_references,
"question_bank_context": question_bank_context,
"memory_context": memory_context,
diff --git a/deeptutor/tutorbot/providers/openai_compat_provider.py b/deeptutor/tutorbot/providers/openai_compat_provider.py
index c0c1f5aea..6691757ec 100644
--- a/deeptutor/tutorbot/providers/openai_compat_provider.py
+++ b/deeptutor/tutorbot/providers/openai_compat_provider.py
@@ -365,6 +365,8 @@ class OpenAICompatProvider(LLMProvider):
finish_reason = ch.finish_reason
if not content and m.content:
content = m.content
+ if not content and getattr(m, "reasoning_content", None):
+ content = m.reasoning_content
if not content and getattr(m, "reasoning", None):
content = m.reasoning
diff --git a/deeptutor/utils/document_extractor.py b/deeptutor/utils/document_extractor.py
index 0a76690a6..5754d6cf6 100644
--- a/deeptutor/utils/document_extractor.py
+++ b/deeptutor/utils/document_extractor.py
@@ -21,7 +21,13 @@ import base64
from collections.abc import Iterable
import io
import logging
-from pathlib import PurePosixPath
+from pathlib import Path, PurePosixPath
+import re
+from typing import Any
+import zipfile
+
+from defusedxml import ElementTree as DefusedElementTree
+from defusedxml.common import DefusedXmlException
from deeptutor.services.rag.file_routing import FileTypeRouter
@@ -56,7 +62,7 @@ except ImportError: # pragma: no cover
logger = logging.getLogger(__name__)
-_OFFICE_EXTENSIONS: frozenset[str] = frozenset({".pdf", ".docx", ".xlsx", ".pptx"})
+_OFFICE_EXTENSIONS: frozenset[str] = frozenset(FileTypeRouter.PARSER_EXTENSIONS)
# Text-like formats are sourced from the KB file router so chat and KB stay
# in sync. Adding a new code / config extension in one place propagates here.
TEXT_LIKE_EXTENSIONS: frozenset[str] = frozenset(FileTypeRouter.TEXT_EXTENSIONS)
@@ -129,17 +135,26 @@ def _check_magic(ext: str, data: bytes, filename: str) -> None:
)
-def extract_text_from_bytes(filename: str, data: bytes) -> str:
+def extract_text_from_bytes(
+ filename: str,
+ data: bytes,
+ *,
+ max_bytes: int | None = MAX_DOC_BYTES,
+ max_chars: int | None = MAX_EXTRACTED_CHARS_PER_DOC,
+) -> str:
"""Extract text from a single document's raw bytes.
Raises a ``DocumentExtractionError`` subclass on failure. Successful
- output is truncated to ``MAX_EXTRACTED_CHARS_PER_DOC`` with a notice.
+ output is truncated to ``max_chars`` with a notice when ``max_chars`` is
+ not ``None``. ``max_bytes`` is configurable so the KB indexer can reuse
+ the same parsers with its larger upload policy while chat keeps the
+ stricter per-turn limit.
"""
if not data:
raise EmptyDocumentError(f"{filename} is empty", filename=filename)
- if len(data) > MAX_DOC_BYTES:
+ if max_bytes is not None and len(data) > max_bytes:
raise DocumentTooLargeError(
- f"{filename} exceeds the {MAX_DOC_BYTES // (1024 * 1024)} MB per-file limit",
+ f"{filename} exceeds the {max_bytes // (1024 * 1024)} MB per-file limit",
filename=filename,
)
@@ -166,7 +181,23 @@ def extract_text_from_bytes(filename: str, data: bytes) -> str:
if not text.strip():
raise EmptyDocumentError(f"{filename}: no extractable text", filename=filename)
- return _truncate(text, MAX_EXTRACTED_CHARS_PER_DOC)
+ return _truncate(text, max_chars) if max_chars is not None else text
+
+
+def extract_text_from_path(
+ file_path: str | Path,
+ *,
+ max_bytes: int | None = MAX_DOC_BYTES,
+ max_chars: int | None = MAX_EXTRACTED_CHARS_PER_DOC,
+) -> str:
+ """Extract text from a file path using the same bytes-based parsers."""
+ path = Path(file_path)
+ return extract_text_from_bytes(
+ path.name,
+ path.read_bytes(),
+ max_bytes=max_bytes,
+ max_chars=max_chars,
+ )
def _extract_pdf(data: bytes, filename: str) -> str:
@@ -215,24 +246,45 @@ def _extract_pdf(data: bytes, filename: str) -> str:
def _extract_docx(data: bytes, filename: str) -> str:
+ primary_error: Exception | None = None
+ primary_text = ""
+ if DocxDocument is not None:
+ try:
+ doc = DocxDocument(io.BytesIO(data))
+ paragraphs = [p.text for p in doc.paragraphs if p.text and p.text.strip()]
+ primary_text = "\n\n".join(paragraphs)
+ except Exception as exc:
+ primary_error = exc
+ logger.info("python-docx failed on %s; falling back to raw OOXML: %s", filename, exc)
+
+ fallback = _extract_docx_ooxml(data, filename)
+ if fallback.strip() and (not primary_text.strip() or len(fallback) > len(primary_text) * 1.2):
+ return fallback
+ if primary_text.strip():
+ return primary_text
+
if DocxDocument is None:
- raise CorruptDocumentError(f"{filename}: python-docx not installed", filename=filename)
- try:
- doc = DocxDocument(io.BytesIO(data))
- except Exception as exc:
raise CorruptDocumentError(
- f"{filename}: failed to open DOCX ({exc})", filename=filename
- ) from exc
- paragraphs = [p.text for p in doc.paragraphs if p.text and p.text.strip()]
- return "\n\n".join(paragraphs)
+ f"{filename}: python-docx not installed and OOXML fallback found no text",
+ filename=filename,
+ )
+ if primary_error is not None:
+ raise CorruptDocumentError(
+ f"{filename}: failed to open DOCX ({primary_error})", filename=filename
+ ) from primary_error
+ return ""
def _extract_xlsx(data: bytes, filename: str) -> str:
if load_workbook is None:
- raise CorruptDocumentError(f"{filename}: openpyxl not installed", filename=filename)
+ return _extract_xlsx_ooxml(data, filename)
try:
wb = load_workbook(io.BytesIO(data), read_only=True, data_only=True)
except Exception as exc:
+ logger.info("openpyxl failed on %s; falling back to raw OOXML: %s", filename, exc)
+ fallback = _extract_xlsx_ooxml(data, filename)
+ if fallback.strip():
+ return fallback
raise CorruptDocumentError(
f"{filename}: failed to open XLSX ({exc})", filename=filename
) from exc
@@ -254,10 +306,14 @@ def _extract_xlsx(data: bytes, filename: str) -> str:
def _extract_pptx(data: bytes, filename: str) -> str:
if PptxPresentation is None:
- raise CorruptDocumentError(f"{filename}: python-pptx not installed", filename=filename)
+ return _extract_pptx_ooxml(data, filename)
try:
prs = PptxPresentation(io.BytesIO(data))
except Exception as exc:
+ logger.info("python-pptx failed on %s; falling back to raw OOXML: %s", filename, exc)
+ fallback = _extract_pptx_ooxml(data, filename)
+ if fallback.strip():
+ return fallback
raise CorruptDocumentError(
f"{filename}: failed to open PPTX ({exc})", filename=filename
) from exc
@@ -286,6 +342,180 @@ def _extract_text_like(data: bytes, filename: str) -> str:
) from exc
+def _open_ooxml(data: bytes, filename: str) -> zipfile.ZipFile:
+ try:
+ return zipfile.ZipFile(io.BytesIO(data))
+ except zipfile.BadZipFile as exc:
+ raise CorruptDocumentError(
+ f"{filename}: failed to open Office ZIP package ({exc})", filename=filename
+ ) from exc
+
+
+def _local_name(tag: str) -> str:
+ return tag.rsplit("}", 1)[-1] if "}" in tag else tag
+
+
+def _parse_xml_member(zf: zipfile.ZipFile, member: str, filename: str) -> Any | None:
+ try:
+ raw = zf.read(member)
+ except KeyError:
+ return None
+ try:
+ return DefusedElementTree.fromstring(raw)
+ except (DefusedElementTree.ParseError, DefusedXmlException) as exc:
+ raise CorruptDocumentError(
+ f"{filename}: failed to parse {member} ({exc})", filename=filename
+ ) from exc
+
+
+def _collect_ooxml_text(node: Any) -> str:
+ parts: list[str] = []
+ for child in node.iter():
+ name = _local_name(child.tag)
+ if name == "t" and child.text:
+ parts.append(child.text)
+ elif name == "tab":
+ parts.append("\t")
+ elif name in {"br", "cr"}:
+ parts.append("\n")
+ return "".join(parts).strip()
+
+
+def _extract_paragraph_text(root: Any) -> list[str]:
+ paragraphs: list[str] = []
+ for node in root.iter():
+ if _local_name(node.tag) != "p":
+ continue
+ text = _collect_ooxml_text(node)
+ if text:
+ paragraphs.append(text)
+ if paragraphs:
+ return paragraphs
+ text = _collect_ooxml_text(root)
+ return [text] if text else []
+
+
+def _extract_docx_ooxml(data: bytes, filename: str) -> str:
+ with _open_ooxml(data, filename) as zf:
+ names = zf.namelist()
+ content_members = ["word/document.xml"]
+ content_members.extend(
+ sorted(
+ name
+ for name in names
+ if re.match(r"word/(header|footer|footnotes|endnotes|comments)\d*\.xml$", name)
+ )
+ )
+
+ chunks: list[str] = []
+ for member in content_members:
+ root = _parse_xml_member(zf, member, filename)
+ if root is None:
+ continue
+ chunks.extend(_extract_paragraph_text(root))
+ return "\n\n".join(chunks)
+
+
+def _xlsx_shared_strings(zf: zipfile.ZipFile, filename: str) -> list[str]:
+ root = _parse_xml_member(zf, "xl/sharedStrings.xml", filename)
+ if root is None:
+ return []
+ strings: list[str] = []
+ for node in root:
+ if _local_name(node.tag) != "si":
+ continue
+ strings.append(_collect_ooxml_text(node))
+ return strings
+
+
+def _xlsx_sheet_names(zf: zipfile.ZipFile, filename: str) -> dict[str, str]:
+ root = _parse_xml_member(zf, "xl/workbook.xml", filename)
+ if root is None:
+ return {}
+ out: dict[str, str] = {}
+ index = 1
+ for node in root.iter():
+ if _local_name(node.tag) != "sheet":
+ continue
+ sheet_name = node.attrib.get("name") or f"sheet{index}"
+ sheet_id = node.attrib.get("sheetId") or str(index)
+ out[f"xl/worksheets/sheet{sheet_id}.xml"] = sheet_name
+ index += 1
+ return out
+
+
+def _xlsx_cell_text(cell: Any, shared_strings: list[str]) -> str:
+ cell_type = cell.attrib.get("t", "")
+ if cell_type == "inlineStr":
+ return _collect_ooxml_text(cell)
+
+ value = ""
+ for child in cell:
+ if _local_name(child.tag) == "v":
+ value = child.text or ""
+ break
+
+ if cell_type == "s":
+ try:
+ return shared_strings[int(value)]
+ except (ValueError, IndexError):
+ return value
+ return value
+
+
+def _extract_xlsx_ooxml(data: bytes, filename: str) -> str:
+ with _open_ooxml(data, filename) as zf:
+ shared_strings = _xlsx_shared_strings(zf, filename)
+ sheet_names = _xlsx_sheet_names(zf, filename)
+ sheet_members = sorted(
+ (name for name in zf.namelist() if re.match(r"xl/worksheets/sheet\d+\.xml$", name)),
+ key=lambda name: [
+ int(part) if part.isdigit() else part for part in re.split(r"(\d+)", name)
+ ],
+ )
+
+ sheets: list[str] = []
+ for index, member in enumerate(sheet_members, 1):
+ root = _parse_xml_member(zf, member, filename)
+ if root is None:
+ continue
+ rows: list[str] = []
+ for row in root.iter():
+ if _local_name(row.tag) != "row":
+ continue
+ cells = [
+ _xlsx_cell_text(cell, shared_strings)
+ for cell in row
+ if _local_name(cell.tag) == "c"
+ ]
+ row_text = "\t".join(cells)
+ if row_text.strip():
+ rows.append(row_text)
+ if rows:
+ sheet_name = sheet_names.get(member, f"sheet{index}")
+ sheets.append(f"--- Sheet: {sheet_name} ---\n" + "\n".join(rows))
+ return "\n\n".join(sheets)
+
+
+def _extract_pptx_ooxml(data: bytes, filename: str) -> str:
+ with _open_ooxml(data, filename) as zf:
+ slide_members = sorted(
+ (name for name in zf.namelist() if re.match(r"ppt/slides/slide\d+\.xml$", name)),
+ key=lambda name: [
+ int(part) if part.isdigit() else part for part in re.split(r"(\d+)", name)
+ ],
+ )
+ slides: list[str] = []
+ for index, member in enumerate(slide_members, 1):
+ root = _parse_xml_member(zf, member, filename)
+ if root is None:
+ continue
+ paragraphs = _extract_paragraph_text(root)
+ if paragraphs:
+ slides.append(f"--- Slide {index} ---\n" + "\n".join(paragraphs))
+ return "\n\n".join(slides)
+
+
def _collect_pptx_shape_text(shape, out: list[str]) -> None:
"""Recurse into groups + tables, same semantics as nanobot's version."""
sub_shapes = getattr(shape, "shapes", None)
diff --git a/deeptutor/utils/document_validator.py b/deeptutor/utils/document_validator.py
index 11c6c6925..442619644 100644
--- a/deeptutor/utils/document_validator.py
+++ b/deeptutor/utils/document_validator.py
@@ -109,9 +109,17 @@ class DocumentValidator:
f"Unsupported file type: {ext}. Allowed types: {', '.join(exts_to_check)}"
)
- # Additional MIME type validation for security
+ # Additional MIME type validation for the legacy/default policy. For
+ # caller-provided extension policies (for example the KB router's
+ # FileTypeRouter list), the extension set is already the source of
+ # truth; mimetypes is extension-derived and incomplete for many code
+ # and config formats.
guessed_mime, _ = mimetypes.guess_type(safe_name.lower())
- if guessed_mime and guessed_mime not in DocumentValidator.ALLOWED_MIME_TYPES:
+ if (
+ allowed_extensions is None
+ and guessed_mime
+ and guessed_mime not in DocumentValidator.ALLOWED_MIME_TYPES
+ ):
raise ValueError(
f"MIME type validation failed: {guessed_mime}. File may be malicious or corrupted."
)
diff --git a/pyproject.toml b/pyproject.toml
index b4c632cb9..607a89f23 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -54,6 +54,7 @@ cli = [
"openpyxl>=3.1.0",
"python-pptx>=1.0.0",
"pypdf>=4.0.0",
+ "defusedxml>=0.7.1",
]
# Web/API server (CLI + FastAPI). Mirrors requirements/server.txt.
diff --git a/requirements/cli.txt b/requirements/cli.txt
index 85044a3f8..bf1fcb65d 100644
--- a/requirements/cli.txt
+++ b/requirements/cli.txt
@@ -47,6 +47,7 @@ python-docx>=1.1.0
openpyxl>=3.1.0
python-pptx>=1.0.0
pypdf>=4.0.0
+defusedxml>=0.7.1
# --- Web search ---
ddgs>=9.9.1
diff --git a/tests/agents/chat/test_language_prompts.py b/tests/agents/chat/test_language_prompts.py
new file mode 100644
index 000000000..68c2bde5a
--- /dev/null
+++ b/tests/agents/chat/test_language_prompts.py
@@ -0,0 +1,61 @@
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from deeptutor.agents.chat.agentic_pipeline import AgenticChatPipeline
+from deeptutor.agents.chat.chat_agent import ChatAgent
+
+
[email protected](autouse=True)
+def _fake_llm_config(monkeypatch: pytest.MonkeyPatch) -> None:
+ cfg = SimpleNamespace(
+ binding="openai",
+ model="gpt-test",
+ api_key="sk-test",
+ base_url="https://example.test/v1",
+ api_version=None,
+ )
+ monkeypatch.setattr(
+ "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
+ lambda: cfg,
+ )
+ monkeypatch.setattr("deeptutor.agents.base_agent.get_llm_config", lambda: cfg)
+
+
+def test_agentic_chat_final_prompt_uses_selected_language(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ class FakeRegistry:
+ def build_prompt_text(self, *_args, **_kwargs) -> str:
+ return "- tool"
+
+ monkeypatch.setattr(
+ "deeptutor.agents.chat.agentic_pipeline.get_tool_registry",
+ lambda: FakeRegistry(),
+ )
+
+ zh_prompt = AgenticChatPipeline(language="zh")._responding_system_prompt([])
+ en_prompt = AgenticChatPipeline(language="en")._responding_system_prompt([])
+
+ assert "你是 DeepTutor 的最终回答阶段" in zh_prompt
+ assert "请严格使用中文" in zh_prompt
+ assert "You are DeepTutor's final response stage" in en_prompt
+ assert "Write ALL reader-facing text" in en_prompt
+
+
+def test_legacy_chat_agent_system_prompt_uses_selected_language() -> None:
+ zh_messages = ChatAgent(language="zh", config={}).build_messages(
+ message="解释梯度下降",
+ history=[],
+ )
+ en_messages = ChatAgent(language="en", config={}).build_messages(
+ message="Explain gradient descent",
+ history=[],
+ )
+
+ assert "你是 DeepTutor" in zh_messages[0]["content"]
+ assert "请严格使用中文" in zh_messages[0]["content"]
+ assert "You are DeepTutor" in en_messages[0]["content"]
+ assert "Write ALL reader-facing text" in en_messages[0]["content"]
diff --git a/tests/api/test_knowledge_router.py b/tests/api/test_knowledge_router.py
index 6056d294b..eeb27cf63 100644
--- a/tests/api/test_knowledge_router.py
+++ b/tests/api/test_knowledge_router.py
@@ -114,9 +114,13 @@ def test_supported_file_types_returns_upload_policy() -> None:
assert response.status_code == 200
payload = response.json()
assert ".pdf" in payload["extensions"]
+ assert ".docx" in payload["extensions"]
+ assert ".xlsx" in payload["extensions"]
+ assert ".pptx" in payload["extensions"]
assert ".md" in payload["extensions"]
assert payload["max_file_size_bytes"] > payload["max_pdf_size_bytes"] > 0
assert ".pdf" in payload["accept"]
+ assert ".docx" in payload["accept"]
def test_create_kb_does_not_require_llm_precheck(monkeypatch, tmp_path: Path) -> None:
@@ -349,6 +353,46 @@ def test_reindex_accepts_default_alias(monkeypatch, tmp_path: Path) -> None:
assert manager.config["knowledge_bases"]["actual-kb"]["status"] == "initializing"
+def test_reindex_error_status_bypasses_existing_match_noop(monkeypatch, tmp_path: Path) -> None:
+ manager = _FakeKBManager(tmp_path / "knowledge_bases")
+ manager.config["knowledge_bases"]["failed-kb"] = {
+ "path": "failed-kb",
+ "status": "error",
+ "progress": {"stage": "error", "message": "previous indexing failed"},
+ }
+ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)
+ monkeypatch.setattr(knowledge_router_module, "_kb_base_dir", manager.base_dir)
+
+ class _Signature:
+ def hash(self) -> str:
+ return "sig"
+
+ embedding_signature = importlib.import_module("deeptutor.services.rag.embedding_signature")
+ index_versioning = importlib.import_module("deeptutor.services.rag.index_versioning")
+ monkeypatch.setattr(
+ embedding_signature, "signature_from_embedding_config", lambda: _Signature()
+ )
+ monkeypatch.setattr(
+ index_versioning,
+ "find_matching_version",
+ lambda *_args, **_kwargs: {"layout": "flat", "ready": True},
+ )
+
+ async def _noop_reindex_task(*_args, **_kwargs):
+ return None
+
+ monkeypatch.setattr(knowledge_router_module, "run_reindex_task", _noop_reindex_task)
+
+ with TestClient(_build_app()) as client:
+ response = client.post("/api/v1/knowledge/failed-kb/reindex")
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["noop"] is False
+ assert isinstance(body.get("task_id"), str) and body["task_id"]
+ assert manager.config["knowledge_bases"]["failed-kb"]["status"] == "initializing"
+
+
def test_update_config_coerces_legacy_provider_to_llamaindex() -> None:
"""Legacy `rag_provider` values are accepted and normalized to llamaindex."""
diff --git a/tests/api/test_unified_ws_turn_runtime.py b/tests/api/test_unified_ws_turn_runtime.py
index b2b67378d..9f0e606de 100644
--- a/tests/api/test_unified_ws_turn_runtime.py
+++ b/tests/api/test_unified_ws_turn_runtime.py
@@ -27,6 +27,7 @@ async def test_turn_runtime_replays_events_and_materializes_messages(
) -> None:
store = SQLiteSessionStore(tmp_path / "chat_history.db")
runtime = TurnRuntimeManager(store)
+ captured: dict[str, object] = {}
class FakeContextBuilder:
def __init__(self, *_args, **_kwargs) -> None:
@@ -52,7 +53,9 @@ async def test_turn_runtime_replays_events_and_materializes_messages(
)
class FakeOrchestrator:
- async def handle(self, _context):
+ async def handle(self, context):
+ captured["user_message"] = context.user_message
+ captured["metadata"] = context.metadata
yield StreamEvent(
type=StreamEventType.CONTENT,
source="chat",
@@ -67,6 +70,14 @@ async def test_turn_runtime_replays_events_and_materializes_messages(
"deeptutor.services.session.context_builder.ContextBuilder", FakeContextBuilder
)
monkeypatch.setattr("deeptutor.runtime.orchestrator.ChatOrchestrator", FakeOrchestrator)
+ monkeypatch.setattr(
+ "deeptutor.book.context.build_book_context",
+ lambda *_args, **_kwargs: SimpleNamespace(
+ text="## Page: Signal Basics\nA selected page.",
+ references=[{"book_id": "book-1", "page_ids": ["page-1"]}],
+ warnings=[],
+ ),
+ )
monkeypatch.setattr(
"deeptutor.services.memory.get_memory_service",
lambda: SimpleNamespace(
@@ -91,6 +102,7 @@ async def test_turn_runtime_replays_events_and_materializes_messages(
"language": "en",
"skills": ["proof-checker"],
"memory_references": ["summary"],
+ "book_references": [{"book_id": "book-1", "page_ids": ["page-1"]}],
"config": {},
}
)
@@ -107,6 +119,14 @@ async def test_turn_runtime_replays_events_and_materializes_messages(
assert [message["role"] for message in detail["messages"]] == ["user", "assistant"]
assert detail["messages"][0]["metadata"]["request_snapshot"]["skills"] == ["proof-checker"]
assert detail["messages"][0]["metadata"]["request_snapshot"]["memoryReferences"] == ["summary"]
+ assert detail["messages"][0]["metadata"]["request_snapshot"]["bookReferences"] == [
+ {"book_id": "book-1", "page_ids": ["page-1"]}
+ ]
+ assert "[Book Context]" in str(captured["user_message"])
+ assert "A selected page." in str(captured["user_message"])
+ assert captured["metadata"] and captured["metadata"]["book_references"] == [
+ {"book_id": "book-1", "page_ids": ["page-1"]}
+ ]
assert detail["messages"][1]["content"] == "Hello Frank"
assert detail["preferences"] == {
"capability": "chat",
diff --git a/tests/book/test_context.py b/tests/book/test_context.py
new file mode 100644
index 000000000..74ee2ea4a
--- /dev/null
+++ b/tests/book/test_context.py
@@ -0,0 +1,150 @@
+from __future__ import annotations
+
+from deeptutor.book.context import build_book_context, normalize_book_references
+from deeptutor.book.models import (
+ Block,
+ BlockStatus,
+ BlockType,
+ Book,
+ Chapter,
+ Page,
+ PageStatus,
+ Spine,
+)
+
+
+class FakeBookStorage:
+ def __init__(self) -> None:
+ self.book = Book(
+ id="book-1",
+ title="Fourier Notes",
+ description="A compact guide",
+ language="en",
+ )
+ self.spine = Spine(
+ book_id="book-1",
+ chapters=[
+ Chapter(
+ id="ch-1",
+ title="Signals",
+ summary="Signals are decomposed into bases.",
+ learning_objectives=["Define a signal", "Explain basis functions"],
+ )
+ ],
+ exploration_summary="The source material emphasizes intuition.",
+ )
+ self.page = Page(
+ id="page-1",
+ book_id="book-1",
+ chapter_id="ch-1",
+ title="Signal Basics",
+ learning_objectives=["Understand time and frequency domains"],
+ status=PageStatus.READY,
+ blocks=[
+ Block(
+ type=BlockType.TEXT,
+ status=BlockStatus.READY,
+ title="Intro",
+ payload={
+ "body": "A signal maps time to values. <think>hidden reasoning</think>",
+ },
+ ),
+ Block(
+ type=BlockType.SECTION,
+ status=BlockStatus.READY,
+ title="Core idea",
+ payload={
+ "intro": "We compare signals with reusable patterns.",
+ "subsections": [
+ {
+ "heading": "Basis",
+ "body": "A basis lets us rebuild complex signals.",
+ }
+ ],
+ "key_takeaway": "A coefficient measures alignment.",
+ },
+ ),
+ Block(
+ type=BlockType.CODE,
+ status=BlockStatus.READY,
+ title="Demo",
+ payload={
+ "language": "python",
+ "explanation": "Sample a sine wave.",
+ "code": "print('sample')\n" * 200,
+ },
+ ),
+ Block(
+ type=BlockType.INTERACTIVE,
+ status=BlockStatus.READY,
+ title="Widget",
+ payload={
+ "description": "Drag frequency to see phase changes.",
+ "code": {"content": "<html>" + ("x" * 5000) + "</html>"},
+ },
+ ),
+ Block(
+ type=BlockType.QUIZ,
+ status=BlockStatus.ERROR,
+ title="Check",
+ error="provider timeout",
+ ),
+ ],
+ )
+
+ def load_book(self, book_id: str) -> Book | None:
+ return self.book if book_id == "book-1" else None
+
+ def load_spine(self, book_id: str) -> Spine | None:
+ return self.spine if book_id == "book-1" else None
+
+ def load_page(self, book_id: str, page_id: str) -> Page | None:
+ return self.page if book_id == "book-1" and page_id == "page-1" else None
+
+
+def test_normalize_book_references_merges_and_filters() -> None:
+ refs = normalize_book_references(
+ [
+ {"book_id": "book-1", "page_ids": ["page-1", "page-1", "page-2"]},
+ {"book_id": "", "page_ids": ["x"]},
+ {"book_id": "book-1", "page_ids": ["page-3"]},
+ {"book_id": "book-2", "page_ids": "bad"},
+ ]
+ )
+
+ assert [ref.model_dump() for ref in refs] == [
+ {"book_id": "book-1", "page_ids": ["page-1", "page-2", "page-3"]}
+ ]
+
+
+def test_build_book_context_serializes_readable_page_content() -> None:
+ result = build_book_context(
+ [{"book_id": "book-1", "page_ids": ["page-1"]}],
+ storage=FakeBookStorage(), # type: ignore[arg-type]
+ max_chars=8000,
+ block_char_limit=1500,
+ )
+
+ assert result.references == [{"book_id": "book-1", "page_ids": ["page-1"]}]
+ assert result.warnings == []
+ assert "# Book: Fourier Notes" in result.text
+ assert "Chapter: Signals" in result.text
+ assert "A signal maps time to values." in result.text
+ assert "hidden reasoning" not in result.text
+ assert "A basis lets us rebuild complex signals." in result.text
+ assert "Code (python):" in result.text
+ assert "...[truncated]" in result.text
+ assert "Drag frequency to see phase changes." in result.text
+ assert "<html>" not in result.text
+ assert "Status: error" in result.text
+ assert "provider timeout" in result.text
+
+
+def test_build_book_context_reports_missing_refs() -> None:
+ result = build_book_context(
+ [{"book_id": "missing", "page_ids": ["page-1"]}],
+ storage=FakeBookStorage(), # type: ignore[arg-type]
+ )
+
+ assert result.text == ""
+ assert result.warnings == ["book_not_found:missing"]
diff --git a/tests/book/test_engine_controls.py b/tests/book/test_engine_controls.py
new file mode 100644
index 000000000..a7e8910af
--- /dev/null
+++ b/tests/book/test_engine_controls.py
@@ -0,0 +1,30 @@
+from __future__ import annotations
+
+from deeptutor.book.engine import BookEngine
+from deeptutor.book.models import Block, BlockStatus, BlockType, Page, PageStatus
+
+
+def test_force_compile_reset_preserves_user_notes() -> None:
+ generated = Block(
+ type=BlockType.CODE,
+ status=BlockStatus.READY,
+ payload={"code": "print(1)"},
+ source_anchors=[],
+ metadata={"generation_ms": 10, "transition_in": "bridge"},
+ )
+ note = Block(
+ type=BlockType.USER_NOTE,
+ status=BlockStatus.READY,
+ payload={"body": "keep me"},
+ )
+ page = Page(status=PageStatus.READY, error="", blocks=[generated, note])
+
+ BookEngine._reset_page_for_force_compile(page)
+
+ assert page.status == PageStatus.PENDING
+ assert generated.status == BlockStatus.PENDING
+ assert generated.payload == {}
+ assert generated.error == ""
+ assert generated.metadata == {"transition_in": "bridge"}
+ assert note.status == BlockStatus.READY
+ assert note.payload == {"body": "keep me"}
diff --git a/tests/book/test_llm_writer.py b/tests/book/test_llm_writer.py
new file mode 100644
index 000000000..b21b805d2
--- /dev/null
+++ b/tests/book/test_llm_writer.py
@@ -0,0 +1,60 @@
+from __future__ import annotations
+
+import pytest
+
+from deeptutor.book.blocks import _llm_writer
+
+
+async def test_llm_json_normalizes_array_to_expected_key(monkeypatch: pytest.MonkeyPatch) -> None:
+ async def fake_llm_text(**_: object) -> str:
+ return '[{"front": "A", "back": "B"}]'
+
+ monkeypatch.setattr(_llm_writer, "llm_text", fake_llm_text)
+
+ data = await _llm_writer.llm_json(
+ user_prompt="cards",
+ system_prompt="system",
+ expected_key="cards",
+ )
+
+ assert data == {"cards": [{"front": "A", "back": "B"}]}
+
+
+async def test_llm_json_uses_single_object_from_array(monkeypatch: pytest.MonkeyPatch) -> None:
+ async def fake_llm_text(**_: object) -> str:
+ return '[{"code": "print(1)", "language": "python"}]'
+
+ monkeypatch.setattr(_llm_writer, "llm_text", fake_llm_text)
+
+ data = await _llm_writer.llm_json(user_prompt="code", system_prompt="system")
+
+ assert data["code"] == "print(1)"
+ assert data["language"] == "python"
+
+
+async def test_llm_json_retries_structured_calls_with_minimal_reasoning(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ calls: list[str | None] = []
+
+ async def fake_llm_text(**kwargs: object) -> str:
+ effort = kwargs.get("reasoning_effort")
+ calls.append(effort if isinstance(effort, str) else None)
+ if effort == "minimal":
+ return '{"events": [{"date": "2026", "title": "Ready"}]}'
+ return ""
+
+ monkeypatch.setattr(_llm_writer, "llm_text", fake_llm_text)
+
+ data = await _llm_writer.llm_json(
+ user_prompt="timeline",
+ system_prompt="system",
+ expected_key="events",
+ )
+
+ assert calls == [None, "minimal"]
+ assert data["events"][0]["title"] == "Ready"
+ assert data["_metadata"]["reasoning_retry"] == "minimal"
diff --git a/tests/services/config/test_provider_runtime.py b/tests/services/config/test_provider_runtime.py
index 5d3161cc4..92a6c1e7f 100644
--- a/tests/services/config/test_provider_runtime.py
+++ b/tests/services/config/test_provider_runtime.py
@@ -267,6 +267,44 @@ def test_llm_context_window_passes_through_from_catalog(tmp_path: Path) -> None:
assert resolved.context_window == 128000
+def test_llm_reasoning_effort_env_overrides_catalog(tmp_path: Path) -> None:
+ env_path = tmp_path / ".env"
+ env_path.write_text(
+ "\n".join(
+ [
+ "LLM_BINDING=openai",
+ "LLM_MODEL=gpt-4o-mini",
+ "LLM_API_KEY=sk-test",
+ "LLM_HOST=https://api.openai.com/v1",
+ "LLM_REASONING_EFFORT=minimal",
+ ]
+ )
+ + "\n",
+ encoding="utf-8",
+ )
+ catalog = _build_catalog(
+ llm_profile={
+ "id": "llm-p",
+ "name": "LLM",
+ "binding": "openai",
+ "base_url": "https://api.openai.com/v1",
+ "api_key": "sk-test",
+ "api_version": "",
+ "extra_headers": {},
+ "models": [
+ {
+ "id": "llm-m",
+ "name": "GPT 4o mini",
+ "model": "gpt-4o-mini",
+ "reasoning_effort": "high",
+ }
+ ],
+ }
+ )
+ resolved = resolve_llm_runtime_config(catalog=catalog, env_store=EnvStore(path=env_path))
+ assert resolved.reasoning_effort == "minimal"
+
+
def test_search_fallback_to_duckduckgo_without_key(tmp_path: Path) -> None:
catalog = _build_catalog(
search_profile={
diff --git a/tests/services/llm/test_utils.py b/tests/services/llm/test_utils.py
index 0b6d2e4ba..57d581481 100644
--- a/tests/services/llm/test_utils.py
+++ b/tests/services/llm/test_utils.py
@@ -71,6 +71,11 @@ def test_clean_thinking_tags_handles_unclosed_blocks() -> None:
assert clean_thinking_tags("Edited text\n<think>still reasoning") == "Edited text"
+def test_clean_thinking_tags_handles_backtick_wrapped_tags() -> None:
+ """Post-markdown-normalized thinking tags should also be stripped."""
+ assert clean_thinking_tags("`<think>`ignore`</think>`Hello") == "Hello"
+
+
def test_extract_response_content() -> None:
"""Response content extraction should handle mapping payloads."""
payload = {"content": [{"text": "Hello"}, {"text": "World"}]}
diff --git a/tests/services/rag/test_file_routing.py b/tests/services/rag/test_file_routing.py
index de15188a7..e77a74ee6 100644
--- a/tests/services/rag/test_file_routing.py
+++ b/tests/services/rag/test_file_routing.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import asyncio
from pathlib import Path
import pytest
@@ -24,6 +25,8 @@ class TestExtensionClassification:
("script.py", DocumentType.TEXT),
("config.yaml", DocumentType.TEXT),
("paper.docx", DocumentType.DOCX),
+ ("sheet.xlsx", DocumentType.SPREADSHEET),
+ ("deck.pptx", DocumentType.PRESENTATION),
("photo.png", DocumentType.IMAGE),
],
)
@@ -47,13 +50,21 @@ class TestClassifyFiles:
def test_routes_pdf_to_parser_text_to_text(self, tmp_path: Path) -> None:
pdf = tmp_path / "a.pdf"
pdf.write_bytes(b"%PDF-1.4")
+ docx = tmp_path / "a.docx"
+ docx.write_bytes(b"PK\x03\x04")
+ xlsx = tmp_path / "a.xlsx"
+ xlsx.write_bytes(b"PK\x03\x04")
+ pptx = tmp_path / "a.pptx"
+ pptx.write_bytes(b"PK\x03\x04")
txt = tmp_path / "a.txt"
txt.write_text("hi")
png = tmp_path / "a.png"
png.write_bytes(b"\x89PNG\r\n")
- cls = FileTypeRouter.classify_files([str(pdf), str(txt), str(png)])
- assert cls.parser_files == [str(pdf)]
+ cls = FileTypeRouter.classify_files(
+ [str(pdf), str(docx), str(xlsx), str(pptx), str(txt), str(png)]
+ )
+ assert cls.parser_files == [str(pdf), str(docx), str(xlsx), str(pptx)]
assert cls.text_files == [str(txt)]
assert cls.unsupported == [str(png)]
@@ -68,6 +79,9 @@ class TestSupportedExtensionsAndGlobs:
def test_get_supported_extensions_covers_pdf_and_text(self) -> None:
exts = FileTypeRouter.get_supported_extensions()
assert ".pdf" in exts
+ assert ".docx" in exts
+ assert ".xlsx" in exts
+ assert ".pptx" in exts
assert ".md" in exts
assert ".txt" in exts
@@ -87,22 +101,30 @@ class TestSupportedExtensionsAndGlobs:
nested.mkdir()
nested_upper = nested / "README.MD"
nested_upper.write_text("nested", encoding="utf-8")
+ deck = tmp_path / "DECK.PPTX"
+ deck.write_bytes(b"PK\x03\x04")
ignored = tmp_path / "image.PNG"
ignored.write_bytes(b"\x89PNG\r\n")
assert [path.name for path in FileTypeRouter.collect_supported_files(tmp_path)] == [
+ "DECK.PPTX",
"notes.md",
"REPORT.PDF",
]
assert [
path.name for path in FileTypeRouter.collect_supported_files(tmp_path, recursive=True)
- ] == ["README.MD", "notes.md", "REPORT.PDF"]
+ ] == ["DECK.PPTX", "README.MD", "notes.md", "REPORT.PDF"]
class TestQuickHelpers:
def test_needs_parser_for_pdf(self) -> None:
assert FileTypeRouter.needs_parser("paper.pdf") is True
+ def test_needs_parser_for_office_documents(self) -> None:
+ assert FileTypeRouter.needs_parser("paper.docx") is True
+ assert FileTypeRouter.needs_parser("sheet.xlsx") is True
+ assert FileTypeRouter.needs_parser("deck.pptx") is True
+
def test_needs_parser_false_for_text(self) -> None:
assert FileTypeRouter.needs_parser("notes.md") is False
@@ -113,16 +135,15 @@ class TestQuickHelpers:
assert FileTypeRouter.is_text_readable("doc.pdf") is False
class TestReadTextFile:
- async def test_reads_utf8(self, tmp_path: Path) -> None:
+ def test_reads_utf8(self, tmp_path: Path) -> None:
path = tmp_path / "u.txt"
path.write_text("héllo", encoding="utf-8")
- content = await FileTypeRouter.read_text_file(str(path))
+ content = asyncio.run(FileTypeRouter.read_text_file(str(path)))
assert content == "héllo"
- async def test_reads_gbk_fallback(self, tmp_path: Path) -> None:
+ def test_reads_gbk_fallback(self, tmp_path: Path) -> None:
path = tmp_path / "g.txt"
path.write_bytes("中文测试".encode("gbk"))
- content = await FileTypeRouter.read_text_file(str(path))
+ content = asyncio.run(FileTypeRouter.read_text_file(str(path)))
assert "中文" in content
diff --git a/tests/services/rag/test_llamaindex_document_loader.py b/tests/services/rag/test_llamaindex_document_loader.py
new file mode 100644
index 000000000..5eeae61b0
--- /dev/null
+++ b/tests/services/rag/test_llamaindex_document_loader.py
@@ -0,0 +1,79 @@
+"""Tests for LlamaIndex document loading."""
+
+from __future__ import annotations
+
+import asyncio
+import io
+from pathlib import Path
+
+from docx import Document as DocxDocument
+from openpyxl import Workbook
+from pptx import Presentation
+from pptx.util import Inches
+import pytest
+
+
+def _make_docx(paragraphs: list[str]) -> bytes:
+ doc = DocxDocument()
+ for paragraph in paragraphs:
+ doc.add_paragraph(paragraph)
+ buffer = io.BytesIO()
+ doc.save(buffer)
+ return buffer.getvalue()
+
+
+def _make_xlsx(rows: list[list[object]]) -> bytes:
+ workbook = Workbook()
+ sheet = workbook.active
+ sheet.title = "Data"
+ for row in rows:
+ sheet.append(row)
+ buffer = io.BytesIO()
+ workbook.save(buffer)
+ return buffer.getvalue()
+
+
+def _make_pptx(texts: list[str]) -> bytes:
+ presentation = Presentation()
+ slide = presentation.slides.add_slide(presentation.slide_layouts[5])
+ for index, text in enumerate(texts):
+ text_box = slide.shapes.add_textbox(
+ Inches(1),
+ Inches(1 + index * 0.5),
+ Inches(6),
+ Inches(0.5),
+ )
+ text_box.text_frame.text = text
+ buffer = io.BytesIO()
+ presentation.save(buffer)
+ return buffer.getvalue()
+
+
+def test_loader_extracts_chat_supported_office_files(tmp_path: Path) -> None:
+ pytest.importorskip("llama_index.core")
+ from deeptutor.services.rag.pipelines.llamaindex.document_loader import (
+ LlamaIndexDocumentLoader,
+ )
+
+ docx_path = tmp_path / "notes.docx"
+ docx_path.write_bytes(_make_docx(["Docx paragraph"]))
+ xlsx_path = tmp_path / "book.xlsx"
+ xlsx_path.write_bytes(_make_xlsx([["cell-a", 42]]))
+ pptx_path = tmp_path / "slides.pptx"
+ pptx_path.write_bytes(_make_pptx(["Slide title", "Slide body"]))
+
+ documents = asyncio.run(
+ LlamaIndexDocumentLoader().load([str(docx_path), str(xlsx_path), str(pptx_path)])
+ )
+
+ assert {doc.metadata["file_name"] for doc in documents} == {
+ "notes.docx",
+ "book.xlsx",
+ "slides.pptx",
+ }
+ all_text = "\n".join(doc.text for doc in documents)
+ assert "Docx paragraph" in all_text
+ assert "cell-a" in all_text
+ assert "42" in all_text
+ assert "Slide title" in all_text
+ assert "Slide body" in all_text
diff --git a/tests/services/session/test_regenerate.py b/tests/services/session/test_regenerate.py
index 5285422c6..23c55fd9e 100644
--- a/tests/services/session/test_regenerate.py
+++ b/tests/services/session/test_regenerate.py
@@ -138,6 +138,7 @@ def _seed_session(
*,
user_content: str = "what is 2+2?",
assistant_content: str | None = "4",
+ user_metadata: dict[str, Any] | None = None,
) -> tuple[str, int, int | None]:
"""Create a session with a user (and optional assistant) message."""
session = asyncio.run(store.create_session())
@@ -160,6 +161,7 @@ def _seed_session(
content=user_content,
capability="chat",
attachments=[{"type": "file", "filename": "a.pdf"}],
+ metadata=user_metadata,
)
)
assistant_id: int | None = None
@@ -203,6 +205,25 @@ class TestRegenerateLastTurn:
assert [m["id"] for m in remaining] == [user_id]
assert assistant_id is not None and assistant_id not in {m["id"] for m in remaining}
+ def test_replays_book_references_from_request_snapshot(self, store: SQLiteSessionStore) -> None:
+ sid, _, _ = _seed_session(
+ store,
+ user_metadata={
+ "request_snapshot": {
+ "bookReferences": [{"book_id": "book-1", "page_ids": ["page-1"]}]
+ }
+ },
+ )
+ runtime = TurnRuntimeManager(store=store)
+ recorder = _FakeStartTurnRecorder()
+
+ with patch.object(runtime, "start_turn", new=recorder):
+ asyncio.run(runtime.regenerate_last_turn(sid))
+
+ assert recorder.calls[0]["book_references"] == [
+ {"book_id": "book-1", "page_ids": ["page-1"]}
+ ]
+
def test_user_tail_is_kept_and_no_delete(self, store: SQLiteSessionStore) -> None:
sid, user_id, _ = _seed_session(store, assistant_content=None)
runtime = TurnRuntimeManager(store=store)
diff --git a/tests/utils/test_document_extractor.py b/tests/utils/test_document_extractor.py
index 38550d5c5..66f0608db 100644
--- a/tests/utils/test_document_extractor.py
+++ b/tests/utils/test_document_extractor.py
@@ -11,6 +11,7 @@ from pptx import Presentation
from pptx.util import Inches
import pytest
+from deeptutor.utils import document_extractor as document_extractor_module
from deeptutor.utils.document_extractor import (
MAX_DOC_BYTES,
MAX_EXTRACTED_CHARS_PER_DOC,
@@ -20,6 +21,7 @@ from deeptutor.utils.document_extractor import (
UnsupportedDocumentError,
extract_documents_from_records,
extract_text_from_bytes,
+ extract_text_from_path,
is_document_extension,
)
@@ -106,6 +108,25 @@ class TestExtractDocx:
assert "Hello world" in text
assert "Second paragraph" in text
+ def test_path_helper_can_disable_chat_truncation(self, tmp_path) -> None:
+ data = _make_docx(["a" * (MAX_EXTRACTED_CHARS_PER_DOC + 10)])
+ path = tmp_path / "long.docx"
+ path.write_bytes(data)
+
+ text = extract_text_from_path(path, max_chars=None)
+
+ assert len(text) > MAX_EXTRACTED_CHARS_PER_DOC
+ assert "truncated" not in text
+
+ def test_ooxml_fallback_without_python_docx(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(document_extractor_module, "DocxDocument", None)
+ data = _make_docx(["Fallback paragraph", "第二段"])
+
+ text = extract_text_from_bytes("doc.docx", data)
+
+ assert "Fallback paragraph" in text
+ assert "第二段" in text
+
class TestExtractXlsx:
def test_multiple_sheets(self) -> None:
@@ -121,6 +142,16 @@ class TestExtractXlsx:
assert "a1" in text and "42" in text
assert "x" in text
+ def test_ooxml_fallback_without_openpyxl(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(document_extractor_module, "load_workbook", None)
+ data = _make_xlsx({"Alpha": [["name", "score"], ["alice", 98]]})
+
+ text = extract_text_from_bytes("book.xlsx", data)
+
+ assert "--- Sheet: Alpha ---" in text
+ assert "alice" in text
+ assert "98" in text
+
class TestExtractPptx:
def test_basic_slides(self) -> None:
@@ -131,6 +162,16 @@ class TestExtractPptx:
assert "Slide 1 title" in text
assert "Slide 2 only text" in text
+ def test_ooxml_fallback_without_python_pptx(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(document_extractor_module, "PptxPresentation", None)
+ data = _make_pptx([["Fallback slide", "第二行"]])
+
+ text = extract_text_from_bytes("deck.pptx", data)
+
+ assert "--- Slide 1 ---" in text
+ assert "Fallback slide" in text
+ assert "第二行" in text
+
class TestExtractTextLike:
def test_plain_txt(self) -> None:
diff --git a/tests/utils/test_document_validator.py b/tests/utils/test_document_validator.py
index fd2daf623..15b0f7a1e 100644
--- a/tests/utils/test_document_validator.py
+++ b/tests/utils/test_document_validator.py
@@ -22,3 +22,23 @@ def test_validate_upload_safety_strips_windows_path_components() -> None:
)
assert safe_name == "报告.md"
+
+
+def test_validate_upload_safety_accepts_chat_office_formats_for_kb_policy() -> None:
+ safe_name = DocumentValidator.validate_upload_safety(
+ "Lecture Notes.DOCX",
+ 1024,
+ allowed_extensions=FileTypeRouter.get_supported_extensions(),
+ )
+
+ assert safe_name == "Lecture Notes.docx"
+
+
+def test_validate_upload_safety_custom_policy_allows_supported_code_mimes() -> None:
+ safe_name = DocumentValidator.validate_upload_safety(
+ "solver.PY",
+ 1024,
+ allowed_extensions=FileTypeRouter.get_supported_extensions(),
+ )
+
+ assert safe_name == "solver.py"
diff --git a/web/app/(utility)/settings/page.tsx b/web/app/(utility)/settings/page.tsx
index eae043c32..7a657870b 100644
--- a/web/app/(utility)/settings/page.tsx
+++ b/web/app/(utility)/settings/page.tsx
@@ -4,6 +4,7 @@
import { Suspense, useCallback, useEffect, useRef, useState } from "react";
import {
Brain,
+ CheckCircle2,
ChevronDown,
ChevronRight,
Database,
@@ -96,6 +97,8 @@ type SystemStatus = {
search: { status: string; provider?: string; error?: string };
};
+const SERVICES = ["llm", "embedding", "search"] as const;
+
// ---------------------------------------------------------------------------
function cloneCatalog(catalog: Catalog): Catalog {
@@ -137,6 +140,46 @@ function serviceIcon(service: ServiceName) {
return <Search className="h-3.5 w-3.5" />;
}
+function serviceLabel(
+ service: ServiceName,
+ t: (key: string) => string,
+): string {
+ if (service === "llm") return t("LLM");
+ if (service === "embedding") return t("Embedding");
+ return t("Search");
+}
+
+function activeProfileDetail(
+ profile: CatalogProfile | null,
+ service: ServiceName,
+ t: (key: string) => string,
+): string {
+ if (!profile) return t("No profile");
+ if (service === "search") return profile.provider || t("No provider");
+ return profile.base_url || t("No endpoint");
+}
+
+function activeModelDetail(
+ profile: CatalogProfile | null,
+ model: CatalogModel | null,
+ service: ServiceName,
+ t: (key: string) => string,
+): string {
+ if (service === "search") return profile?.provider || t("No provider");
+ return model?.model || model?.name || t("No model selected");
+}
+
+function servicePendingApply(
+ catalog: Catalog,
+ draft: Catalog,
+ service: ServiceName,
+): boolean {
+ return (
+ JSON.stringify(catalog.services[service]) !==
+ JSON.stringify(draft.services[service])
+ );
+}
+
function statusDotClass(configured: boolean, hasError: boolean): string {
if (hasError) return "bg-red-400";
if (configured) return "bg-emerald-500";
@@ -629,6 +672,22 @@ function SettingsPageContent() {
searchProviderRaw === "perplexity" &&
!String(activeProfile?.api_key || "").trim();
+ // Category-label typography. English looks great with `uppercase` + wide
+ // letter-spacing, but CJK glyphs are already square blocks — extra tracking
+ // pushes them apart and `uppercase` is a no-op. For zh we drop both and
+ // bump size by ~1px to keep visual weight comparable.
+ const labelClass = (size: "sm" | "md" | "lg"): string => {
+ if (language === "zh") {
+ if (size === "sm") return "text-[10.5px] font-medium";
+ if (size === "lg") return "text-[12px] font-medium";
+ return "text-[11px] font-medium";
+ }
+ if (size === "sm")
+ return "text-[9.5px] font-semibold uppercase tracking-[0.16em]";
+ if (size === "lg") return "text-[11px] uppercase tracking-[0.16em]";
+ return "text-[10px] font-semibold uppercase tracking-[0.16em]";
+ };
+
useEffect(() => {
setShowApiKey(false);
}, [activeService, activeProfile?.id]);
@@ -1002,8 +1061,8 @@ function SettingsPageContent() {
</div>
</div>
- {/* ── Preferences & Runtime ── */}
- <div className="mb-8 flex flex-wrap items-center gap-x-8 gap-y-3 border-b border-[var(--border)]/50 pb-6">
+ {/* ── Preferences ── */}
+ <div className="mb-5 flex flex-wrap items-center gap-x-8 gap-y-3">
<div className="flex items-center gap-2">
<span className="text-[12px] text-[var(--muted-foreground)]">
{t("Theme")}
@@ -1051,38 +1110,112 @@ function SettingsPageContent() {
))}
</div>
</div>
+ </div>
- <div className="ml-auto flex items-center gap-4 text-[12px] text-[var(--muted-foreground)]">
- <span className="flex items-center gap-1.5">
- <span
- className={`inline-block h-1.5 w-1.5 rounded-full ${statusDotClass(status?.backend.status === "online", false)}`}
- />
- {t("Backend")}
- </span>
- <span className="flex items-center gap-1.5">
- <span
- className={`inline-block h-1.5 w-1.5 rounded-full ${statusDotClass(Boolean(status?.llm.model), Boolean(status?.llm.error))}`}
- />
- {t("LLM")}
- {status?.llm.model && (
- <span className="text-[var(--muted-foreground)]/50">
- · {status.llm.model}
- </span>
- )}
- </span>
- <span className="flex items-center gap-1.5">
- <span
- className={`inline-block h-1.5 w-1.5 rounded-full ${statusDotClass(Boolean(status?.embeddings.model), Boolean(status?.embeddings.error))}`}
- />
- {t("Emb")}
- </span>
- <span className="flex items-center gap-1.5">
+ {/* ── Runtime status ── */}
+ <div className="mb-8 grid grid-cols-2 overflow-hidden rounded-xl border border-[var(--border)]/60 sm:grid-cols-4">
+ <div
+ className="px-4 py-3.5"
+ title={status?.backend.timestamp || t("Backend status")}
+ >
+ <div className="flex items-center gap-2">
<span
- className={`inline-block h-1.5 w-1.5 rounded-full ${statusDotClass(Boolean(status?.search.provider), false)}`}
+ className={`h-1.5 w-1.5 rounded-full ${statusDotClass(
+ status?.backend.status === "online",
+ false,
+ )}`}
/>
- {t("Search")}
- </span>
+ <span className={`${labelClass("md")} text-[var(--muted-foreground)]`}>
+ {t("Backend")}
+ </span>
+ </div>
+ <div className="mt-2 truncate text-[13px] font-medium text-[var(--foreground)]">
+ {status?.backend.status === "online"
+ ? t("Online")
+ : t("Checking")}
+ </div>
+ <div className="mt-0.5 truncate text-[11px] text-[var(--muted-foreground)]">
+ {(() => {
+ const ts = status?.backend.timestamp;
+ if (!ts) return "—";
+ const parsed = new Date(ts);
+ if (Number.isNaN(parsed.getTime())) return "";
+ return parsed.toLocaleTimeString(
+ language === "zh" ? "zh-CN" : "en-US",
+ { hour: "2-digit", minute: "2-digit" },
+ );
+ })()}
+ </div>
</div>
+
+ {SERVICES.map((service, i) => {
+ const profile = getActiveProfile(draft, service);
+ const model = getActiveModel(draft, service);
+ const serviceStatus =
+ service === "llm"
+ ? status?.llm
+ : service === "embedding"
+ ? status?.embeddings
+ : status?.search;
+ const runtimeModel =
+ service === "llm"
+ ? status?.llm.model
+ : service === "embedding"
+ ? status?.embeddings.model
+ : undefined;
+ const configured =
+ service === "search"
+ ? Boolean(profile?.provider || status?.search.provider)
+ : Boolean(model?.model || runtimeModel);
+ const pendingApply = servicePendingApply(catalog, draft, service);
+ const detail = activeModelDetail(profile, model, service, t);
+ const profileName = profile?.name || t("No profile");
+ const isActiveTab = activeService === service;
+ const borderClasses =
+ i === 0
+ ? "border-l border-[var(--border)]/40"
+ : i === 1
+ ? "border-t border-[var(--border)]/40 sm:border-t-0 sm:border-l"
+ : "border-t border-l border-[var(--border)]/40 sm:border-t-0";
+ return (
+ <button
+ key={service}
+ type="button"
+ onClick={() => setActiveService(service)}
+ title={`${serviceLabel(service, t)} · ${profileName} · ${detail}`}
+ className={`relative px-4 py-3.5 text-left transition-colors ${borderClasses} ${
+ isActiveTab
+ ? "bg-[var(--muted)]/55"
+ : "hover:bg-[var(--muted)]/30"
+ }`}
+ >
+ <div className="flex items-center gap-2">
+ <span
+ className={`h-1.5 w-1.5 rounded-full ${statusDotClass(
+ configured,
+ Boolean(serviceStatus?.error),
+ )}`}
+ />
+ <span
+ className={`truncate ${labelClass("md")} text-[var(--muted-foreground)]`}
+ >
+ {serviceLabel(service, t)}
+ </span>
+ {pendingApply && (
+ <span className="ml-auto shrink-0 text-[10px] font-medium text-amber-600 dark:text-amber-400">
+ {t("Pending")}
+ </span>
+ )}
+ </div>
+ <div className="mt-2 truncate text-[13px] font-medium text-[var(--foreground)]">
+ {detail}
+ </div>
+ <div className="mt-0.5 truncate text-[11px] text-[var(--muted-foreground)]">
+ {profileName}
+ </div>
+ </button>
+ );
+ })}
</div>
{/* ── Service Configuration ── */}
@@ -1131,35 +1264,85 @@ function SettingsPageContent() {
{activeProfile ? (
<div className="grid grid-cols-[200px_1fr] gap-5">
{/* ── Profile list ── */}
- <div className="space-y-1">
- {draft.services[activeService].profiles.map((profile) => (
- <button
- key={profile.id}
- onClick={() =>
- mutateCatalog((next) => {
- next.services[activeService].active_profile_id =
- profile.id;
- if (activeService !== "search") {
- next.services[activeService].active_model_id =
- profile.models[0]?.id ?? null;
- }
- })
- }
- className={`w-full rounded-lg px-3 py-2.5 text-left transition-colors ${
- profile.id ===
- draft.services[activeService].active_profile_id
- ? "bg-[var(--muted)] text-[var(--foreground)]"
- : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/50"
- }`}
- >
- <div className="text-[13px] font-medium">
- {profile.name}
- </div>
- <div className="mt-0.5 truncate text-[11px] text-[var(--muted-foreground)]">
- {profile.base_url || t("No endpoint")}
- </div>
- </button>
- ))}
+ <div className="space-y-2">
+ {draft.services[activeService].profiles.map((profile) => {
+ const isActive =
+ profile.id ===
+ draft.services[activeService].active_profile_id;
+ const activeProfileModel =
+ activeService === "search"
+ ? null
+ : (profile.models.find(
+ (model) =>
+ model.id ===
+ draft.services[activeService].active_model_id,
+ ) ??
+ profile.models[0] ??
+ null);
+ const profileDetail = activeProfileDetail(
+ profile,
+ activeService,
+ t,
+ );
+ const modelDetail = activeModelDetail(
+ profile,
+ activeProfileModel,
+ activeService,
+ t,
+ );
+ return (
+ <button
+ key={profile.id}
+ onClick={() =>
+ mutateCatalog((next) => {
+ next.services[activeService].active_profile_id =
+ profile.id;
+ if (activeService !== "search") {
+ next.services[activeService].active_model_id =
+ profile.models[0]?.id ?? null;
+ }
+ })
+ }
+ className={`relative w-full overflow-hidden rounded-xl px-3.5 py-3 text-left transition-colors ${
+ isActive
+ ? "bg-[var(--muted)]/60 text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/30"
+ }`}
+ >
+ {isActive && (
+ <span className="absolute inset-y-3 left-0 w-0.5 rounded-r-full bg-[var(--foreground)]/80" />
+ )}
+ <div className="truncate text-[13px] font-semibold">
+ {profile.name}
+ </div>
+ <div className="mt-0.5 truncate text-[11px] text-[var(--muted-foreground)]">
+ {profileDetail}
+ </div>
+ {isActive ? (
+ <div className="mt-2.5 border-t border-[var(--border)]/40 pt-2">
+ <div
+ className={`${labelClass("sm")} text-[var(--muted-foreground)]/70`}
+ >
+ {activeService === "search"
+ ? t("Active provider")
+ : t("Active model")}
+ </div>
+ <div className="mt-0.5 truncate text-[12px] font-medium text-[var(--foreground)]">
+ {modelDetail}
+ </div>
+ </div>
+ ) : (
+ activeService !== "search" && (
+ <div className="mt-1 text-[11px] text-[var(--muted-foreground)]/60">
+ {t("{{count}} models", {
+ count: profile.models.length,
+ })}
+ </div>
+ )
+ )}
+ </button>
+ );
+ })}
<button
onClick={removeActiveProfile}
disabled={!activeProfile}
@@ -1394,11 +1577,18 @@ function SettingsPageContent() {
className={`rounded-lg px-3 py-1.5 text-[13px] transition-colors ${
model.id ===
draft.services[activeService].active_model_id
- ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"
+ ? "bg-[var(--foreground)] font-medium text-[var(--background)] shadow-sm"
: "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/50"
}`}
>
- {model.name}
+ <span className="inline-flex items-center gap-1.5">
+ {model.id ===
+ draft.services[activeService]
+ .active_model_id && (
+ <CheckCircle2 className="h-3 w-3" />
+ )}
+ {model.name}
+ </span>
</button>
))}
</div>
@@ -1448,7 +1638,9 @@ function SettingsPageContent() {
</div>
<div className="rounded-xl border border-[var(--border)]/70 bg-[var(--muted)]/30 px-3.5 py-3">
<div className="flex items-center justify-between gap-3">
- <div className="text-[11px] uppercase tracking-[0.16em] text-[var(--muted-foreground)]/70">
+ <div
+ className={`${labelClass("lg")} text-[var(--muted-foreground)]/70`}
+ >
{t("Source")}
</div>
<span className="rounded-full border border-[var(--border)]/70 bg-[var(--card)] px-2.5 py-1 text-[11px] font-medium text-[var(--foreground)]">
diff --git a/web/app/(workspace)/book/components/BookChatPanel.tsx b/web/app/(workspace)/book/components/BookChatPanel.tsx
index 66d7e39e1..2aedd54a8 100644
--- a/web/app/(workspace)/book/components/BookChatPanel.tsx
+++ b/web/app/(workspace)/book/components/BookChatPanel.tsx
@@ -1,15 +1,59 @@
"use client";
import { useEffect, useRef, useState } from "react";
-import { Send, Loader2, MessageSquare, X } from "lucide-react";
-import { wsUrl } from "@/lib/api";
-import MarkdownRenderer from "@/components/common/MarkdownRenderer";
+import type {
+ ChangeEvent,
+ ClipboardEvent,
+ KeyboardEvent,
+ MouseEvent as ReactMouseEvent,
+} from "react";
+import {
+ FileText,
+ Loader2,
+ MessageSquare,
+ Paperclip,
+ Send,
+ X,
+} from "lucide-react";
+import { useTranslation } from "react-i18next";
+import AssistantResponse from "@/components/common/AssistantResponse";
+import { useAppShell } from "@/context/AppShellContext";
+import { getSession } from "@/lib/session-api";
+import {
+ ATTACHMENT_ACCEPT,
+ classifyFile,
+ formatBytes,
+ MAX_ATTACHMENT_BYTES,
+ MAX_TOTAL_ATTACHMENT_BYTES,
+} from "@/lib/doc-attachments";
+import {
+ extractBase64FromDataUrl,
+ readFileAsDataUrl,
+} from "@/lib/file-attachments";
+import { shouldSubmitOnEnter } from "@/lib/composer-keyboard";
+import { shouldAppendEventContent } from "@/lib/stream";
+import {
+ UnifiedWSClient,
+ type StartTurnMessage,
+ type StreamEvent,
+} from "@/lib/unified-ws";
+import type { MessageAttachment } from "@/context/UnifiedChatContext";
import type { Page, Book } from "@/lib/book-types";
interface ChatMessage {
role: "user" | "assistant";
content: string;
streaming?: boolean;
+ attachments?: MessageAttachment[];
+ events?: StreamEvent[];
+}
+
+interface PendingAttachment {
+ type: "image" | "file" | "pdf";
+ filename: string;
+ base64: string;
+ mimeType: string;
+ size: number;
}
export interface BookChatPanelProps {
@@ -17,6 +61,36 @@ export interface BookChatPanelProps {
page: Page | null;
open: boolean;
onClose: () => void;
+ initialSessionId?: string | null;
+ onSessionResolved?: (sessionId: string) => void;
+}
+
+function attachmentTypeFor(file: File): PendingAttachment["type"] | null {
+ const kind = classifyFile(file);
+ if (!kind) return null;
+ if (kind === "image") return "image";
+ return file.type === "application/pdf" ||
+ file.name.toLowerCase().endsWith(".pdf")
+ ? "pdf"
+ : "file";
+}
+
+function outgoingAttachment(attachment: PendingAttachment) {
+ return {
+ type: attachment.type,
+ filename: attachment.filename,
+ base64: attachment.base64,
+ mime_type: attachment.mimeType,
+ };
+}
+
+function messageAttachment(attachment: PendingAttachment): MessageAttachment {
+ return {
+ type: attachment.type,
+ filename: attachment.filename,
+ base64: attachment.base64,
+ mime_type: attachment.mimeType,
+ };
}
export default function BookChatPanel({
@@ -24,25 +98,80 @@ export default function BookChatPanel({
page,
open,
onClose,
+ initialSessionId = null,
+ onSessionResolved,
}: BookChatPanelProps) {
+ const { t } = useTranslation();
+ const { language: appLanguage } = useAppShell();
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [input, setInput] = useState("");
const [busy, setBusy] = useState(false);
+ const [width, setWidth] = useState(360);
+ const [attachments, setAttachments] = useState<PendingAttachment[]>([]);
+ const [attachmentError, setAttachmentError] = useState<string | null>(null);
const sessionIdRef = useRef<string | null>(null);
- const socketRef = useRef<WebSocket | null>(null);
+ const clientRef = useRef<UnifiedWSClient | null>(null);
+ const retryTimersRef = useRef<Set<ReturnType<typeof setTimeout>>>(new Set());
const scrollerRef = useRef<HTMLDivElement | null>(null);
+ const fileInputRef = useRef<HTMLInputElement | null>(null);
+ const dragRef = useRef<{ startX: number; startWidth: number } | null>(null);
+ const isComposingRef = useRef(false);
+
+ useEffect(() => {
+ const raw = window.localStorage.getItem("deeptutor.bookChat.width");
+ const parsed = Number(raw);
+ if (Number.isFinite(parsed) && parsed >= 300 && parsed <= 720) {
+ setWidth(parsed);
+ }
+ }, []);
+
+ useEffect(() => {
+ window.localStorage.setItem("deeptutor.bookChat.width", String(width));
+ }, [width]);
useEffect(() => {
return () => {
- socketRef.current?.close();
- socketRef.current = null;
+ retryTimersRef.current.forEach((timer) => clearTimeout(timer));
+ retryTimersRef.current.clear();
+ clientRef.current?.disconnect();
+ clientRef.current = null;
};
}, []);
useEffect(() => {
- sessionIdRef.current = null;
+ let cancelled = false;
+ retryTimersRef.current.forEach((timer) => clearTimeout(timer));
+ retryTimersRef.current.clear();
+ clientRef.current?.disconnect();
+ clientRef.current = null;
+ sessionIdRef.current = initialSessionId || null;
setMessages([]);
- }, [book?.id]);
+ setAttachments([]);
+ setAttachmentError(null);
+ setBusy(false);
+
+ if (!open || !initialSessionId) return;
+ void getSession(initialSessionId)
+ .then((session) => {
+ if (cancelled) return;
+ const restored = (session.messages || [])
+ .filter((m) => m.role === "user" || m.role === "assistant")
+ .map((m) => ({
+ role: m.role as "user" | "assistant",
+ content: String(m.content || ""),
+ attachments: m.attachments || [],
+ events: m.events || [],
+ }));
+ setMessages(restored);
+ })
+ .catch(() => {
+ if (!cancelled) sessionIdRef.current = null;
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [book?.id, page?.id, initialSessionId, open]);
useEffect(() => {
if (scrollerRef.current) {
@@ -50,125 +179,246 @@ export default function BookChatPanel({
}
}, [messages]);
- function ensureSocket(): WebSocket {
- const existing = socketRef.current;
- if (existing && existing.readyState === WebSocket.OPEN) {
- return existing;
- }
- if (existing && existing.readyState === WebSocket.CONNECTING) {
- return existing;
+ function handleEvent(event: StreamEvent) {
+ if (event.type === "session") {
+ const metadata = (event.metadata || {}) as Record<string, unknown>;
+ const sessionId =
+ typeof metadata.session_id === "string"
+ ? metadata.session_id
+ : typeof event.session_id === "string"
+ ? event.session_id
+ : "";
+ if (sessionId) {
+ sessionIdRef.current = sessionId;
+ onSessionResolved?.(sessionId);
+ }
+ return;
}
- const ws = new WebSocket(wsUrl("/api/v1/chat"));
- socketRef.current = ws;
- ws.onmessage = (event) => {
- try {
- const data = JSON.parse(event.data);
- switch (data.type) {
- case "session":
- sessionIdRef.current = data.session_id;
- break;
- case "stream":
- setMessages((prev) => {
- const next = [...prev];
- const last = next[next.length - 1];
- if (last && last.role === "assistant" && last.streaming) {
- next[next.length - 1] = {
- ...last,
- content: last.content + String(data.content || ""),
- };
- } else {
- next.push({
- role: "assistant",
- content: String(data.content || ""),
- streaming: true,
- });
- }
- return next;
- });
- break;
- case "result":
- setMessages((prev) => {
- const next = [...prev];
- const last = next[next.length - 1];
- if (last && last.role === "assistant") {
- next[next.length - 1] = {
- ...last,
- content: data.content || last.content,
- streaming: false,
- };
- } else {
- next.push({
- role: "assistant",
- content: String(data.content || ""),
- });
- }
- return next;
- });
- setBusy(false);
- break;
- case "error":
- setMessages((prev) => [
- ...prev,
- { role: "assistant", content: `❌ ${data.message || "error"}` },
- ]);
- setBusy(false);
- break;
- default:
- break;
+
+ if (event.type === "done") {
+ setMessages((prev) => {
+ const next = [...prev];
+ const last = next[next.length - 1];
+ if (last?.role === "assistant") {
+ next[next.length - 1] = { ...last, streaming: false };
}
- } catch {
- // ignore
+ return next;
+ });
+ setBusy(false);
+ return;
+ }
+
+ if (event.type === "error") {
+ setMessages((prev) => [
+ ...prev,
+ {
+ role: "assistant",
+ content: event.content || t("Error"),
+ streaming: false,
+ },
+ ]);
+ setBusy(false);
+ return;
+ }
+
+ setMessages((prev) => {
+ const next = [...prev];
+ const last = next[next.length - 1];
+ const contentDelta = shouldAppendEventContent(event)
+ ? event.content || ""
+ : "";
+ if (last && last.role === "assistant" && last.streaming) {
+ next[next.length - 1] = {
+ ...last,
+ content: last.content + contentDelta,
+ events: [...(last.events || []), event],
+ };
+ } else if (contentDelta || event.type !== "content") {
+ next.push({
+ role: "assistant",
+ content: contentDelta,
+ streaming: true,
+ events: [event],
+ });
}
- };
- ws.onclose = () => {
- socketRef.current = null;
+ return next;
+ });
+ }
+
+ function ensureClient(): UnifiedWSClient {
+ if (clientRef.current) return clientRef.current;
+ const client = new UnifiedWSClient(handleEvent, () => setBusy(false));
+ clientRef.current = client;
+ client.connect();
+ return client;
+ }
+
+ function sendWithRetry(
+ client: UnifiedWSClient,
+ payload: StartTurnMessage,
+ attempt = 0,
+ ) {
+ if (client.connected) {
+ client.send(payload);
+ return;
+ }
+ if (attempt >= 10) {
setBusy(false);
+ setMessages((prev) => [
+ ...prev,
+ {
+ role: "assistant",
+ content: t("Connection failed. Please try again."),
+ },
+ ]);
+ return;
+ }
+ const timer = setTimeout(() => {
+ retryTimersRef.current.delete(timer);
+ sendWithRetry(client, payload, attempt + 1);
+ }, 200);
+ retryTimersRef.current.add(timer);
+ }
+
+ function beginResize(event: ReactMouseEvent<HTMLDivElement>) {
+ event.preventDefault();
+ dragRef.current = { startX: event.clientX, startWidth: width };
+ const onMove = (moveEvent: MouseEvent) => {
+ const drag = dragRef.current;
+ if (!drag) return;
+ const next = Math.max(
+ 300,
+ Math.min(720, drag.startWidth + drag.startX - moveEvent.clientX),
+ );
+ setWidth(next);
+ };
+ const onUp = () => {
+ dragRef.current = null;
+ window.removeEventListener("mousemove", onMove);
+ window.removeEventListener("mouseup", onUp);
};
- ws.onerror = () => setBusy(false);
- return ws;
+ window.addEventListener("mousemove", onMove);
+ window.addEventListener("mouseup", onUp);
}
- function buildContextPreface(): string {
- const lines: string[] = [];
- if (book?.title) lines.push(`Book: ${book.title}`);
- if (page?.title) lines.push(`Current page: ${page.title}`);
- if (page?.learning_objectives?.length) {
- lines.push(`Objectives: ${page.learning_objectives.join("; ")}`);
+ function filterFiles(files: File[]): File[] {
+ setAttachmentError(null);
+ const currentTotal = attachments.reduce((sum, file) => sum + file.size, 0);
+ let nextTotal = currentTotal;
+ const accepted: File[] = [];
+ for (const file of files) {
+ const type = attachmentTypeFor(file);
+ if (!type) {
+ setAttachmentError(t("Unsupported file type."));
+ continue;
+ }
+ if (file.size > MAX_ATTACHMENT_BYTES) {
+ setAttachmentError(
+ t("File is too large ({{size}}).", { size: formatBytes(file.size) }),
+ );
+ continue;
+ }
+ if (nextTotal + file.size > MAX_TOTAL_ATTACHMENT_BYTES) {
+ setAttachmentError(t("Attachments exceed the total upload limit."));
+ continue;
+ }
+ nextTotal += file.size;
+ accepted.push(file);
}
- return lines.join("\n");
+ return accepted;
+ }
+
+ async function addFiles(files: File[]) {
+ const accepted = filterFiles(files);
+ if (!accepted.length) return;
+ const next = await Promise.all(
+ accepted.map(async (file) => {
+ const dataUrl = await readFileAsDataUrl(file);
+ return {
+ type: attachmentTypeFor(file) || "file",
+ filename: file.name,
+ base64: extractBase64FromDataUrl(dataUrl),
+ mimeType: file.type || "application/octet-stream",
+ size: file.size,
+ } satisfies PendingAttachment;
+ }),
+ );
+ setAttachments((prev) => [...prev, ...next]);
+ }
+
+ function handleFileInputChange(event: ChangeEvent<HTMLInputElement>) {
+ const picked = Array.from(event.target.files || []);
+ if (picked.length) void addFiles(picked);
+ event.target.value = "";
+ }
+
+ function handlePaste(event: ClipboardEvent<HTMLTextAreaElement>) {
+ const files = Array.from(event.clipboardData.files || []);
+ if (!files.length) return;
+ event.preventDefault();
+ void addFiles(files);
}
async function send() {
const text = input.trim();
- if (!text || busy) return;
- setMessages((prev) => [...prev, { role: "user", content: text }]);
+ if ((!text && attachments.length === 0) || busy || !book || !page) return;
+ const userContent =
+ text ||
+ (attachments.some((item) => item.type === "image")
+ ? t(
+ "Please analyze the attached image(s) using this chapter as context.",
+ )
+ : t("Please use the attached file(s) and this chapter as context."));
+ const sentAttachments = attachments.map(messageAttachment);
+ setMessages((prev) => [
+ ...prev,
+ { role: "user", content: userContent, attachments: sentAttachments },
+ ]);
setInput("");
+ setAttachments([]);
+ setAttachmentError(null);
setBusy(true);
- const ws = ensureSocket();
- const payload = {
- message: text,
+
+ const client = ensureClient();
+ const payload: StartTurnMessage = {
+ type: "start_turn",
+ content: userContent,
session_id: sessionIdRef.current,
- kb_name: book?.knowledge_bases?.[0] || "",
- enable_rag: !!(book?.knowledge_bases && book.knowledge_bases.length > 0),
- enable_web_search: false,
- context: buildContextPreface(),
+ capability: "chat",
+ tools: book.knowledge_bases?.length ? ["rag"] : [],
+ knowledge_bases: book.knowledge_bases || [],
+ attachments: attachments.map(outgoingAttachment),
+ language: appLanguage,
+ book_references: [{ book_id: book.id, page_ids: [page.id] }],
};
- const dispatch = () => ws.send(JSON.stringify(payload));
- if (ws.readyState === WebSocket.OPEN) {
- dispatch();
- } else {
- ws.addEventListener("open", dispatch, { once: true });
- }
+ sendWithRetry(client, payload);
}
if (!open) return null;
return (
- <aside className="flex h-full w-[360px] shrink-0 flex-col border-l border-[var(--border)] bg-[var(--card)]/40 backdrop-blur">
+ <aside
+ className="relative flex h-full shrink-0 flex-col border-l border-[var(--border)] bg-[var(--card)]/40 backdrop-blur"
+ style={{ width }}
+ >
+ <div
+ role="separator"
+ aria-orientation="vertical"
+ title={t("Drag to resize")}
+ onMouseDown={beginResize}
+ className="absolute inset-y-0 left-0 z-10 w-1 cursor-col-resize bg-transparent transition-colors hover:bg-[var(--primary)]/30"
+ />
<header className="flex items-center justify-between border-b border-[var(--border)] px-4 py-3">
- <div className="flex items-center gap-2 text-sm font-medium text-[var(--foreground)]">
- <MessageSquare className="h-4 w-4 text-[var(--primary)]" />
- Page Chat
+ <div className="min-w-0">
+ <div className="flex items-center gap-2 text-sm font-medium text-[var(--foreground)]">
+ <MessageSquare className="h-4 w-4 text-[var(--primary)]" />
+ {t("Page Chat")}
+ </div>
+ {page?.title && (
+ <div className="mt-1 truncate text-[11px] text-[var(--muted-foreground)]">
+ {t("Context")}: {page.title}
+ </div>
+ )}
</div>
<button
onClick={onClose}
@@ -180,9 +430,10 @@ export default function BookChatPanel({
<div ref={scrollerRef} className="flex-1 overflow-y-auto px-4 py-3">
{messages.length === 0 ? (
- <div className="text-xs text-[var(--muted-foreground)]">
- Ask a question about this page. Context (book + chapter) is sent
- automatically.
+ <div className="rounded-2xl border border-dashed border-[var(--border)] bg-[var(--background)]/50 p-4 text-xs leading-5 text-[var(--muted-foreground)]">
+ {t(
+ "Ask a question about this page. The current chapter content is sent to the assistant automatically.",
+ )}
</div>
) : (
<div className="space-y-3">
@@ -190,16 +441,47 @@ export default function BookChatPanel({
<div
key={i}
className={
- m.role === "user"
- ? "ml-6 rounded-2xl rounded-tr-sm bg-[var(--primary)]/10 px-3 py-2 text-sm text-[var(--foreground)]"
- : "mr-6 rounded-2xl rounded-tl-sm bg-[var(--background)] px-3 py-2 text-sm text-[var(--foreground)]"
+ m.role === "user" ? "flex justify-end" : "flex justify-start"
}
>
- {m.role === "assistant" ? (
- <MarkdownRenderer content={m.content} variant="compact" />
- ) : (
- m.content
- )}
+ <div
+ className={
+ m.role === "user"
+ ? "max-w-[82%] rounded-2xl rounded-tr-sm bg-[var(--primary)] px-3 py-2 text-sm text-[var(--primary-foreground)] shadow-sm"
+ : "max-w-[88%] rounded-2xl rounded-tl-sm bg-[var(--background)] px-3 py-2 text-sm text-[var(--foreground)] shadow-sm"
+ }
+ >
+ {m.role === "user" && (
+ <div className="mb-1 text-right text-[10px] font-medium uppercase tracking-wide opacity-75">
+ {t("You")}
+ </div>
+ )}
+ {m.attachments?.length ? (
+ <div className="mb-2 flex flex-wrap justify-end gap-1.5">
+ {m.attachments.map((attachment, idx) => (
+ <span
+ key={`${attachment.filename || idx}-${idx}`}
+ className="inline-flex max-w-full items-center gap-1 rounded-lg bg-black/10 px-2 py-1 text-[10px]"
+ >
+ <FileText className="h-3 w-3 shrink-0" />
+ <span className="truncate">
+ {attachment.filename || t("Attachment")}
+ </span>
+ </span>
+ ))}
+ </div>
+ ) : null}
+ {m.role === "assistant" ? (
+ <AssistantResponse
+ content={m.content}
+ className="text-sm leading-relaxed"
+ />
+ ) : (
+ <div className="whitespace-pre-wrap break-words">
+ {m.content}
+ </div>
+ )}
+ </div>
</div>
))}
</div>
@@ -209,28 +491,86 @@ export default function BookChatPanel({
<form
onSubmit={(e) => {
e.preventDefault();
- send();
+ void send();
}}
className="border-t border-[var(--border)] p-3"
>
- <div className="flex items-end gap-2">
+ <input
+ ref={fileInputRef}
+ type="file"
+ multiple
+ accept={ATTACHMENT_ACCEPT}
+ onChange={handleFileInputChange}
+ className="hidden"
+ aria-hidden="true"
+ tabIndex={-1}
+ />
+ {attachments.length > 0 && (
+ <div className="mb-2 flex flex-wrap gap-1.5">
+ {attachments.map((attachment, index) => (
+ <span
+ key={`${attachment.filename}-${index}`}
+ className="inline-flex max-w-full items-center gap-1.5 rounded-lg border border-[var(--border)] bg-[var(--background)] px-2 py-1 text-[11px] text-[var(--foreground)]"
+ >
+ <FileText className="h-3 w-3 shrink-0 text-[var(--muted-foreground)]" />
+ <span className="truncate">{attachment.filename}</span>
+ <button
+ type="button"
+ onClick={() =>
+ setAttachments((prev) => prev.filter((_, i) => i !== index))
+ }
+ className="opacity-60 hover:opacity-100"
+ >
+ <X className="h-3 w-3" />
+ </button>
+ </span>
+ ))}
+ </div>
+ )}
+ {attachmentError && (
+ <div className="mb-2 text-[11px] text-red-500">{attachmentError}</div>
+ )}
+ <div className="flex items-end gap-2 rounded-2xl border border-[var(--border)] bg-[var(--background)] px-2 py-2 focus-within:border-[var(--primary)]/50 focus-within:ring-2 focus-within:ring-[var(--primary)]/10">
+ <button
+ type="button"
+ onClick={() => fileInputRef.current?.click()}
+ className="mb-0.5 inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-xl text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ title={t("Attach files")}
+ aria-label={t("Attach files")}
+ >
+ <Paperclip className="h-4 w-4" />
+ </button>
<textarea
value={input}
onChange={(e) => setInput(e.target.value)}
- placeholder="Ask about this page…"
- rows={2}
- onKeyDown={(e) => {
- if (e.key === "Enter" && !e.shiftKey) {
+ placeholder={t("Ask about this page…")}
+ rows={1}
+ onPaste={handlePaste}
+ onCompositionStart={() => {
+ isComposingRef.current = true;
+ }}
+ onCompositionEnd={() => {
+ setTimeout(() => {
+ isComposingRef.current = false;
+ }, 0);
+ }}
+ onKeyDown={(e: KeyboardEvent<HTMLTextAreaElement>) => {
+ if (shouldSubmitOnEnter(e, isComposingRef.current)) {
e.preventDefault();
- send();
+ void send();
}
}}
- className="flex-1 resize-none rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1.5 text-sm text-[var(--foreground)] focus:border-[var(--primary)] focus:outline-none"
+ className="max-h-32 min-h-8 flex-1 resize-none bg-transparent px-1 py-1.5 text-sm text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]"
/>
<button
type="submit"
- disabled={busy || !input.trim()}
- className="inline-flex h-9 items-center justify-center rounded-md bg-[var(--primary)] px-3 text-[var(--primary-foreground)] disabled:opacity-50"
+ disabled={
+ busy ||
+ (!input.trim() && attachments.length === 0) ||
+ !book ||
+ !page
+ }
+ className="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-[var(--primary)] text-[var(--primary-foreground)] transition-opacity disabled:opacity-50"
>
{busy ? (
<Loader2 className="h-4 w-4 animate-spin" />
diff --git a/web/app/(workspace)/book/components/BookCreator.tsx b/web/app/(workspace)/book/components/BookCreator.tsx
index de8c61cae..b1375c243 100644
--- a/web/app/(workspace)/book/components/BookCreator.tsx
+++ b/web/app/(workspace)/book/components/BookCreator.tsx
@@ -14,6 +14,8 @@ import {
RefreshCw,
Sparkles,
} from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { useAppShell } from "@/context/AppShellContext";
import type { BookProposal } from "@/lib/book-types";
import {
listKnowledgeBases,
@@ -38,6 +40,8 @@ import {
type SourceTab = "knowledge" | "notebooks" | "questions" | "chats";
+type Translate = (key: string, options?: Record<string, unknown>) => string;
+
type ParentSelection<TChild extends string | number> =
| { mode: "all" }
| { mode: "subset"; ids: Set<TChild> };
@@ -71,8 +75,11 @@ export default function BookCreator({
onConfirmProposal,
confirmLoading = false,
}: BookCreatorProps) {
+ const { t } = useTranslation();
+ const { language: appLanguage } = useAppShell();
const [intent, setIntent] = useState("");
- const [language, setLanguage] = useState("en");
+ const [language, setLanguage] = useState(appLanguage);
+ const languageTouchedRef = useRef(false);
const [tab, setTab] = useState<SourceTab>("knowledge");
// Knowledge bases (flat selection)
@@ -188,6 +195,10 @@ export default function BookCreator({
void refreshSessions();
}, []);
+ useEffect(() => {
+ if (!languageTouchedRef.current) setLanguage(appLanguage);
+ }, [appLanguage]);
+
// ── selection counts ─────────────────────────────────────────────
const countSelection = <P extends string | number, C extends string | number>(
map: ParentMap<P, C>,
@@ -335,15 +346,25 @@ export default function BookCreator({
icon: typeof Database;
count: number;
}> = [
- { key: "knowledge", label: "KB", icon: Database, count: selectedKbs.size },
- { key: "notebooks", label: "Notebooks", icon: NotebookPen, count: nbCount },
+ {
+ key: "knowledge",
+ label: t("KB"),
+ icon: Database,
+ count: selectedKbs.size,
+ },
+ {
+ key: "notebooks",
+ label: t("Notebooks"),
+ icon: NotebookPen,
+ count: nbCount,
+ },
{
key: "questions",
- label: "Questions",
+ label: t("Questions"),
icon: ClipboardList,
count: qCount,
},
- { key: "chats", label: "Chats", icon: MessagesSquare, count: chatCount },
+ { key: "chats", label: t("Chats"), icon: MessagesSquare, count: chatCount },
];
// Summary chips shown in the collapsed form header so users always see what
@@ -352,25 +373,35 @@ export default function BookCreator({
if (selectedKbs.size > 0) {
summaryChips.push({
icon: Database,
- label: `${selectedKbs.size} KB`,
+ label: t("{{count}} KB", { count: selectedKbs.size }),
});
}
if (nbCount > 0) {
summaryChips.push({
icon: NotebookPen,
- label: `${nbCount} notebook record${nbCount === 1 ? "" : "s"}`,
+ label: t(
+ nbCount === 1
+ ? "{{count}} notebook record"
+ : "{{count}} notebook records",
+ { count: nbCount },
+ ),
});
}
if (qCount > 0) {
summaryChips.push({
icon: ClipboardList,
- label: `${qCount} quiz item${qCount === 1 ? "" : "s"}`,
+ label: t(qCount === 1 ? "{{count}} quiz item" : "{{count}} quiz items", {
+ count: qCount,
+ }),
});
}
if (chatCount > 0) {
summaryChips.push({
icon: MessagesSquare,
- label: `${chatCount} chat item${chatCount === 1 ? "" : "s"}`,
+ label: t(
+ chatCount === 1 ? "{{count}} chat item" : "{{count}} chat items",
+ { count: chatCount },
+ ),
});
}
@@ -378,11 +409,12 @@ export default function BookCreator({
<div className="mx-auto w-full max-w-2xl space-y-5 p-6">
<div className="space-y-1.5">
<h1 className="text-2xl font-semibold text-[var(--foreground)]">
- Create a new book
+ {t("Create a new book")}
</h1>
<p className="text-sm text-[var(--muted-foreground)]">
- Describe what you want to learn, then pick the knowledge sources to
- fuse into a structured, interactive book.
+ {t(
+ "Describe what you want to learn, then pick the knowledge sources to fuse into a structured, interactive book.",
+ )}
</p>
</div>
@@ -395,7 +427,7 @@ export default function BookCreator({
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="text-sm font-semibold text-[var(--foreground)]">
- {formCollapsed ? "Inputs" : "Configure inputs"}
+ {formCollapsed ? t("Inputs") : t("Configure inputs")}
</span>
{formCollapsed && intent.trim() && (
<span className="truncate text-xs text-[var(--muted-foreground)]">
@@ -407,7 +439,7 @@ export default function BookCreator({
<div className="mt-1 flex flex-wrap items-center gap-1.5">
{summaryChips.length === 0 ? (
<span className="text-[11px] text-[var(--muted-foreground)]">
- No knowledge sources selected
+ {t("No knowledge sources selected")}
</span>
) : (
summaryChips.map((chip, i) => (
@@ -427,7 +459,7 @@ export default function BookCreator({
{formCollapsed ? (
<>
<Pencil className="h-3 w-3" />
- Edit
+ {t("Edit")}
</>
) : (
<ChevronUp className="h-3.5 w-3.5" />
@@ -439,13 +471,15 @@ export default function BookCreator({
<div className="space-y-4 px-5 pb-5">
<label className="block">
<span className="text-xs font-semibold uppercase tracking-[0.16em] text-[var(--muted-foreground)]">
- Learning intent
+ {t("Learning intent")}
</span>
<textarea
value={intent}
onChange={(e) => setIntent(e.target.value)}
rows={5}
- placeholder="e.g. Build intuition for transformer attention with derivations and exercises."
+ placeholder={t(
+ "e.g. Build intuition for transformer attention with derivations and exercises.",
+ )}
className="mt-1.5 w-full resize-none rounded-xl border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-sm text-[var(--foreground)] outline-none focus:border-[var(--primary)]/50"
/>
</label>
@@ -453,10 +487,10 @@ export default function BookCreator({
<div className="space-y-3">
<div className="flex items-center justify-between gap-2">
<span className="text-xs font-semibold uppercase tracking-[0.16em] text-[var(--muted-foreground)]">
- Knowledge sources
+ {t("Knowledge sources")}
{totalSelected > 0 && (
<span className="ml-2 rounded-full bg-[var(--primary)]/15 px-2 py-0.5 text-[10px] font-semibold text-[var(--primary)]">
- {totalSelected} selected
+ {t("{{count}} selected", { count: totalSelected })}
</span>
)}
</span>
@@ -471,7 +505,7 @@ export default function BookCreator({
className="inline-flex items-center gap-1 rounded-md px-2 py-1 text-[11px] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
>
<RefreshCw className="h-3 w-3" />
- Refresh
+ {t("Refresh")}
</button>
</div>
@@ -508,11 +542,13 @@ export default function BookCreator({
{tab === "knowledge" && (
<FlatList
loading={kbsLoading}
- emptyHint="No knowledge bases yet. Create one in the Knowledge page first."
+ emptyHint={t(
+ "No knowledge bases yet. Create one in the Knowledge page first.",
+ )}
items={kbs.map((kb) => ({
key: kb.name,
primary: kb.name,
- secondary: kb.is_default ? "default" : kb.status || "",
+ secondary: kb.is_default ? t("default") : kb.status || "",
checked: selectedKbs.has(kb.name),
onToggle: () => toggleKb(kb.name),
}))}
@@ -522,7 +558,9 @@ export default function BookCreator({
{tab === "notebooks" && (
<TreeList
loading={notebooksLoading}
- emptyHint="No notebooks yet. Save chat outputs into a notebook first."
+ emptyHint={t(
+ "No notebooks yet. Save chat outputs into a notebook first.",
+ )}
parents={notebooks.map((nb) => {
const records = notebookRecords[nb.id];
return {
@@ -531,13 +569,15 @@ export default function BookCreator({
subtitle: parentSubtitle(
notebookSelection.get(nb.id),
records?.length ?? nb.record_count ?? 0,
- "record",
+ t("record"),
+ t("records"),
+ t,
),
expanded: notebookExpanded.has(nb.id),
childrenLoading: !!notebookRecordsLoading[nb.id],
children: (records ?? []).map((rec) => ({
id: rec.id,
- title: rec.title || "(untitled)",
+ title: rec.title || t("(untitled)"),
subtitle: rec.summary || "",
})),
selection: notebookSelection.get(nb.id),
@@ -568,7 +608,9 @@ export default function BookCreator({
{tab === "questions" && (
<TreeList<number, number>
loading={categoriesLoading}
- emptyHint="No quiz categories yet. Bookmark questions into a category first."
+ emptyHint={t(
+ "No quiz categories yet. Bookmark questions into a category first.",
+ )}
parents={categories.map((cat) => {
const entries = questionEntries[cat.id];
return {
@@ -577,19 +619,22 @@ export default function BookCreator({
subtitle: parentSubtitle(
questionSelection.get(cat.id),
entries?.length ?? cat.entry_count ?? 0,
- "entry",
- "entries",
+ t("entry"),
+ t("entries"),
+ t,
),
expanded: questionExpanded.has(cat.id),
childrenLoading: !!questionEntriesLoading[cat.id],
children: (entries ?? []).map((e) => ({
id: e.id,
- title: e.question || "(no question)",
+ title: e.question || t("(no question)"),
subtitle: `${e.is_correct ? "✓" : "✗"} ${
e.user_answer
- ? `your: ${e.user_answer}`
- : "no attempt"
- } · correct: ${e.correct_answer}`,
+ ? t("your: {{answer}}", { answer: e.user_answer })
+ : t("no attempt")
+ } · ${t("correct: {{answer}}", {
+ answer: e.correct_answer,
+ })}`,
})),
selection: questionSelection.get(cat.id),
};
@@ -619,16 +664,18 @@ export default function BookCreator({
{tab === "chats" && (
<TreeList<string, number>
loading={sessionsLoading}
- emptyHint="No chat sessions yet."
+ emptyHint={t("No chat sessions yet.")}
parents={sessions.map((s) => {
const msgs = chatMessages[s.session_id];
return {
id: s.session_id,
- title: s.title || "(untitled chat)",
+ title: s.title || t("(untitled chat)"),
subtitle: parentSubtitle(
chatSelection.get(s.session_id),
msgs?.length ?? s.message_count ?? 0,
- "message",
+ t("message"),
+ t("messages"),
+ t,
),
expanded: chatExpanded.has(s.session_id),
childrenLoading: !!chatMessagesLoading[s.session_id],
@@ -666,14 +713,17 @@ export default function BookCreator({
<div className="flex items-center justify-between gap-3">
<label className="text-xs text-[var(--muted-foreground)]">
- Language{" "}
+ {t("Language")}{" "}
<select
value={language}
- onChange={(e) => setLanguage(e.target.value)}
+ 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">English</option>
- <option value="zh">中文</option>
+ <option value="en">{t("language.english")}</option>
+ <option value="zh">{t("language.chinese")}</option>
</select>
</label>
<button
@@ -686,7 +736,7 @@ export default function BookCreator({
) : (
<Sparkles className="h-4 w-4" />
)}
- Generate proposal
+ {t("Generate proposal")}
</button>
</div>
</div>
@@ -697,10 +747,12 @@ export default function BookCreator({
<div className="space-y-4 rounded-2xl border border-[var(--border)] bg-[var(--card)] p-5 shadow-sm">
<div>
<h2 className="text-base font-semibold text-[var(--foreground)]">
- Proposal
+ {t("Proposal")}
</h2>
<p className="text-xs text-[var(--muted-foreground)]">
- Edit anything below, then confirm to generate the chapter spine.
+ {t(
+ "Edit anything below, then confirm to generate the chapter spine.",
+ )}
</p>
</div>
<ProposalForm
@@ -719,7 +771,7 @@ export default function BookCreator({
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"
>
{confirmLoading && <Loader2 className="h-4 w-4 animate-spin" />}
- Confirm proposal & build spine
+ {t("Confirm proposal & build spine")}
</button>
</div>
</div>
@@ -741,16 +793,28 @@ function parentSubtitle<C extends string | number>(
total: number,
unit: string,
unitPlural?: string,
+ t?: Translate,
): string {
const plural = unitPlural || `${unit}s`;
const fmt = (n: number) => `${n} ${n === 1 ? unit : plural}`;
if (!sel) return total > 0 ? fmt(total) : `0 ${plural}`;
if (sel.mode === "all") {
- return total > 0 ? `All ${fmt(total)}` : "All";
+ return total > 0
+ ? `${t ? t("All") : "All"} ${fmt(total)}`
+ : t
+ ? t("All")
+ : "All";
}
return total > 0
- ? `${sel.ids.size} of ${fmt(total)}`
- : `${sel.ids.size} selected`;
+ ? t
+ ? t("{{selected}} of {{total}}", {
+ selected: sel.ids.size,
+ total: fmt(total),
+ })
+ : `${sel.ids.size} of ${fmt(total)}`
+ : t
+ ? t("{{count}} selected", { count: sel.ids.size })
+ : `${sel.ids.size} selected`;
}
// ─── checkbox icon ─────────────────────────────────────────────────────
@@ -800,11 +864,12 @@ function FlatList({
onToggle: () => void;
}>;
}) {
+ const { t } = useTranslation();
if (loading)
return (
<div className="flex items-center justify-center gap-2 py-6 text-xs text-[var(--muted-foreground)]">
<Loader2 className="h-3.5 w-3.5 animate-spin" />
- Loading…
+ {t("Loading…")}
</div>
);
if (items.length === 0)
@@ -880,11 +945,12 @@ function TreeList<
onToggleChild: (parentId: P, childId: C, knownChildren: C[]) => void;
onToggleExpand: (id: P) => void;
}) {
+ const { t } = useTranslation();
if (loading)
return (
<div className="flex items-center justify-center gap-2 py-6 text-xs text-[var(--muted-foreground)]">
<Loader2 className="h-3.5 w-3.5 animate-spin" />
- Loading…
+ {t("Loading…")}
</div>
);
if (parents.length === 0)
@@ -915,7 +981,7 @@ function TreeList<
type="button"
onClick={() => onToggleExpand(p.id)}
className="flex h-7 w-6 shrink-0 items-center justify-center text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
- aria-label={p.expanded ? "Collapse" : "Expand"}
+ aria-label={p.expanded ? t("Collapse") : t("Expand")}
>
{p.expanded ? (
<ChevronDown className="h-3.5 w-3.5" />
@@ -947,11 +1013,11 @@ function TreeList<
{p.childrenLoading ? (
<div className="flex items-center gap-2 px-2 py-2 text-[11px] text-[var(--muted-foreground)]">
<Loader2 className="h-3 w-3 animate-spin" />
- Loading…
+ {t("Loading…")}
</div>
) : p.children.length === 0 ? (
<div className="px-2 py-2 text-[11px] text-[var(--muted-foreground)]">
- Nothing inside.
+ {t("Nothing inside.")}
</div>
) : (
<ul className="max-h-56 space-y-0.5 overflow-y-auto pr-0.5">
@@ -1011,13 +1077,14 @@ function ProposalForm({
onChange: (p: BookProposal) => void;
selectedKbs: string[];
}) {
+ const { t } = useTranslation();
const update = (patch: Partial<BookProposal>) =>
onChange({ ...proposal, ...patch });
return (
<div className="grid gap-3 sm:grid-cols-2">
<label className="block sm:col-span-2">
<span className="text-xs uppercase tracking-wider text-[var(--muted-foreground)]">
- Title
+ {t("Title")}
</span>
<input
value={proposal.title}
@@ -1027,7 +1094,7 @@ function ProposalForm({
</label>
<label className="block sm:col-span-2">
<span className="text-xs uppercase tracking-wider text-[var(--muted-foreground)]">
- Description
+ {t("Description")}
</span>
<textarea
value={proposal.description}
@@ -1038,7 +1105,7 @@ function ProposalForm({
</label>
<label className="block">
<span className="text-xs uppercase tracking-wider text-[var(--muted-foreground)]">
- Scope
+ {t("Scope")}
</span>
<input
value={proposal.scope}
@@ -1048,7 +1115,7 @@ function ProposalForm({
</label>
<label className="block">
<span className="text-xs uppercase tracking-wider text-[var(--muted-foreground)]">
- Target level
+ {t("Target level")}
</span>
<input
value={proposal.target_level}
@@ -1058,7 +1125,7 @@ function ProposalForm({
</label>
<label className="block">
<span className="text-xs uppercase tracking-wider text-[var(--muted-foreground)]">
- Estimated chapters
+ {t("Estimated chapters")}
</span>
<input
type="number"
@@ -1073,13 +1140,14 @@ function ProposalForm({
</label>
<div className="block sm:col-span-2">
<span className="text-xs uppercase tracking-wider text-[var(--muted-foreground)]">
- Knowledge bases used
+ {t("Knowledge bases used")}
</span>
<div className="mt-1.5 flex flex-wrap gap-1.5">
{selectedKbs.length === 0 ? (
<span className="text-xs italic text-[var(--muted-foreground)]">
- No knowledge bases selected. The book will rely on general
- knowledge.
+ {t(
+ "No knowledge bases selected. The book will rely on general knowledge.",
+ )}
</span>
) : (
selectedKbs.map((kb) => (
diff --git a/web/app/(workspace)/book/components/BookHealthBanner.tsx b/web/app/(workspace)/book/components/BookHealthBanner.tsx
index f36f6ab2e..d5bbd988b 100644
--- a/web/app/(workspace)/book/components/BookHealthBanner.tsx
+++ b/web/app/(workspace)/book/components/BookHealthBanner.tsx
@@ -2,6 +2,7 @@
import { useEffect, useState } from "react";
import { AlertTriangle, RefreshCcw, X, ScrollText } from "lucide-react";
+import { useTranslation } from "react-i18next";
import { bookApi } from "@/lib/book-api";
export interface BookHealthBannerProps {
@@ -30,6 +31,7 @@ export default function BookHealthBanner({
refreshKey,
onRecompile,
}: BookHealthBannerProps) {
+ const { t } = useTranslation();
const [kbDrift, setKbDrift] = useState<KbDrift | null>(null);
const [logHealth, setLogHealth] = useState<LogHealth | null>(null);
const [dismissed, setDismissed] = useState(false);
@@ -78,7 +80,7 @@ export default function BookHealthBanner({
// Convert technical signatures into a short human label.
const humanizeSignature = (sig: string): string => {
- if (!sig) return "unknown failure";
+ if (!sig) return t("unknown failure");
const stripped = sig.replace(/^[a-z_]+:/i, "").trim();
return stripped.length > 80 ? `${stripped.slice(0, 80)}…` : stripped;
};
@@ -102,12 +104,14 @@ export default function BookHealthBanner({
{hasDrift && (
<div>
<strong>
- Your knowledge bases changed since this book was generated.
+ {t(
+ "Your knowledge bases changed since this book was generated.",
+ )}
</strong>{" "}
<span className="opacity-90">
{kbDrift?.new_kbs?.length ? (
<>
- Newly added:{" "}
+ {t("Newly added")}:{" "}
<code className="rounded bg-white/40 px-1 text-[11px] dark:bg-white/10">
{kbDrift.new_kbs.join(", ")}
</code>
@@ -116,7 +120,7 @@ export default function BookHealthBanner({
) : null}
{kbDrift?.changed_kbs?.length ? (
<>
- Updated:{" "}
+ {t("Updated")}:{" "}
<code className="rounded bg-white/40 px-1 text-[11px] dark:bg-white/10">
{kbDrift.changed_kbs.join(", ")}
</code>
@@ -125,7 +129,7 @@ export default function BookHealthBanner({
) : null}
{kbDrift?.removed_kbs?.length ? (
<>
- Removed:{" "}
+ {t("Removed")}:{" "}
<code className="rounded bg-white/40 px-1 text-[11px] dark:bg-white/10">
{kbDrift.removed_kbs.join(", ")}
</code>
@@ -135,16 +139,26 @@ export default function BookHealthBanner({
</span>
{kbDrift?.stale_page_ids?.length ? (
<div className="mt-1.5 text-xs opacity-90">
- {kbDrift.stale_page_ids.length} previously-compiled page
- {kbDrift.stale_page_ids.length === 1 ? "" : "s"} may be out of
- date.{" "}
+ {kbDrift.stale_page_ids.length === 1
+ ? t(
+ "{{count}} previously-compiled page may be out of date.",
+ {
+ count: kbDrift.stale_page_ids.length,
+ },
+ )
+ : t(
+ "{{count}} previously-compiled pages may be out of date.",
+ {
+ count: kbDrift.stale_page_ids.length,
+ },
+ )}{" "}
{onRecompile && kbDrift.stale_page_ids[0] && (
<button
onClick={() => onRecompile(kbDrift.stale_page_ids![0])}
className="ml-1 inline-flex items-center gap-1 rounded border border-current px-1.5 py-0.5 text-xs hover:bg-white/40"
>
- <RefreshCcw className="h-3 w-3" /> Recompile first stale
- page
+ <RefreshCcw className="h-3 w-3" />{" "}
+ {t("Recompile first stale page")}
</button>
)}
</div>
@@ -156,14 +170,21 @@ export default function BookHealthBanner({
<ScrollText className="h-3.5 w-3.5" />
{blockFailures > 0 && (
<span>
- {blockFailures} block generation{" "}
- {blockFailures === 1 ? "failure" : "failures"} recorded.
+ {blockFailures === 1
+ ? t("{{count}} block generation failure recorded.", {
+ count: blockFailures,
+ })
+ : t("{{count}} block generation failures recorded.", {
+ count: blockFailures,
+ })}
</span>
)}
{repeated.length > 0 && (
<span>
- Recurring issue
- {repeated.length === 1 ? "" : "s"}:{" "}
+ {repeated.length === 1
+ ? t("Recurring issue")
+ : t("Recurring issues")}
+ :{" "}
{repeated
.map(
(r) => `${humanizeSignature(r.signature)} (×${r.count})`,
@@ -180,10 +201,12 @@ export default function BookHealthBanner({
<button
onClick={acknowledge}
disabled={busy}
- title="Mark the current KB state as the new baseline (won't recompile pages — use the recompile button above for that)."
+ title={t(
+ "Mark the current KB state as the new baseline (won't recompile pages — use the recompile button above for that).",
+ )}
className="whitespace-nowrap rounded-md border border-current px-2 py-1 text-xs font-medium hover:bg-white/40 disabled:opacity-60"
>
- {busy ? "…" : "Mark as seen"}
+ {busy ? "…" : t("Mark as seen")}
</button>
)}
<button
diff --git a/web/app/(workspace)/book/components/BookLibrary.tsx b/web/app/(workspace)/book/components/BookLibrary.tsx
index 68c9b6444..3d6d3da33 100644
--- a/web/app/(workspace)/book/components/BookLibrary.tsx
+++ b/web/app/(workspace)/book/components/BookLibrary.tsx
@@ -14,6 +14,7 @@ import {
Trash2,
} from "lucide-react";
import type { CSSProperties } from "react";
+import { useTranslation } from "react-i18next";
import type { Book, BookStatus } from "@/lib/book-types";
@@ -58,19 +59,22 @@ const STATUS_STYLES: Record<
},
};
-function relativeTime(seconds: number): string {
+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 "just now";
+ if (diff < 60) return t("just now");
const mins = Math.floor(diff / 60);
- if (mins < 60) return `${mins}m ago`;
+ if (mins < 60) return t("{{count}}m ago", { count: mins });
const hrs = Math.floor(mins / 60);
- if (hrs < 24) return `${hrs}h ago`;
+ if (hrs < 24) return t("{{count}}h ago", { count: hrs });
const days = Math.floor(hrs / 24);
- if (days < 30) return `${days}d ago`;
+ if (days < 30) return t("{{count}}d ago", { count: days });
const months = Math.floor(days / 30);
- if (months < 12) return `${months}mo ago`;
- return `${Math.floor(months / 12)}y ago`;
+ 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
@@ -142,6 +146,7 @@ export default function BookLibrary({
onSelectBook,
onDeleteBook,
}: BookLibraryProps) {
+ const { t } = useTranslation();
const [query, setQuery] = useState("");
const [pendingDeleteId, setPendingDeleteId] = useState<string | null>(null);
@@ -176,10 +181,10 @@ export default function BookLibrary({
<Library size={18} className="text-[var(--muted-foreground)]" />
<div>
<div className="text-sm font-semibold text-[var(--foreground)]">
- Books
+ {t("Books")}
</div>
<div className="text-xs text-[var(--muted-foreground)]">
- Generate, browse and study your AI-authored books.
+ {t("Generate, browse and study your AI-authored books.")}
</div>
</div>
</div>
@@ -192,7 +197,7 @@ export default function BookLibrary({
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
- placeholder="Search books"
+ placeholder={t("Search books")}
className="h-8 w-56 rounded-md border border-[var(--border)] bg-[var(--secondary)]/30 pl-7 pr-2.5 text-xs text-[var(--foreground)] placeholder:text-[var(--muted-foreground)]/60 focus:border-[var(--primary)]/40 focus:outline-none"
/>
</div>
@@ -202,7 +207,7 @@ export default function BookLibrary({
className="inline-flex items-center gap-1.5 rounded-md bg-[var(--primary)] px-3 py-1.5 text-xs font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90"
>
<Plus size={13} />
- New book
+ {t("New book")}
</button>
</div>
</header>
@@ -212,24 +217,24 @@ export default function BookLibrary({
<div className="mb-6 grid grid-cols-2 gap-3 sm:grid-cols-4">
<StatCard
icon={<BookOpen size={14} />}
- label="Total books"
+ label={t("Total books")}
value={stats.total}
/>
<StatCard
icon={<Sparkles size={14} />}
- label="Ready"
+ label={t("Ready")}
value={stats.ready}
accent="text-emerald-600 dark:text-emerald-400"
/>
<StatCard
icon={<Loader2 size={14} />}
- label="In progress"
+ label={t("In progress")}
value={stats.inProgress}
accent="text-violet-600 dark:text-violet-400"
/>
<StatCard
icon={<Layers size={14} />}
- label="Chapters"
+ label={t("Chapters")}
value={stats.chapters}
/>
</div>
@@ -238,11 +243,14 @@ export default function BookLibrary({
<div className="mb-3 flex items-end justify-between">
<div>
<div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-[var(--muted-foreground)]">
- My library
+ {t("My library")}
</div>
<div className="text-xs text-[var(--muted-foreground)]/80">
- {filtered.length} of {books.length} books
- {query ? ` · matching “${query}”` : ""}
+ {t("{{shown}} of {{total}} books", {
+ shown: filtered.length,
+ total: books.length,
+ })}
+ {query ? ` · ${t("matching “{{query}}”", { query })}` : ""}
</div>
</div>
</div>
@@ -250,13 +258,13 @@ export default function BookLibrary({
{loading ? (
<div className="flex items-center justify-center gap-2 py-20 text-sm text-[var(--muted-foreground)]">
<Loader2 size={16} className="animate-spin" />
- Loading books…
+ {t("Loading books…")}
</div>
) : books.length === 0 ? (
<EmptyState onNewBook={onNewBook} />
) : filtered.length === 0 ? (
<div className="rounded-xl border border-dashed border-[var(--border)] bg-[var(--secondary)]/30 px-6 py-12 text-center text-sm text-[var(--muted-foreground)]">
- No books match “{query}”.
+ {t("No books match “{{query}}”.", { query })}
</div>
) : (
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3">
@@ -346,7 +354,7 @@ export default function BookLibrary({
<span
className={`h-1.5 w-1.5 rounded-full ${status.dot}`}
/>
- {status.label}
+ {t(status.label)}
</span>
<button
type="button"
@@ -361,8 +369,8 @@ export default function BookLibrary({
}}
title={
isPendingDelete
- ? "Click again to confirm"
- : "Delete book"
+ ? t("Click again to confirm")
+ : t("Delete book")
}
className={`absolute right-2 top-2 rounded-md p-1.5 transition-colors ${
isPendingDelete
@@ -378,28 +386,34 @@ export default function BookLibrary({
<div className="flex flex-1 flex-col gap-2 p-4">
<div
className="line-clamp-2 text-sm font-semibold text-[var(--foreground)]"
- title={book.title || "Untitled book"}
+ title={book.title || t("Untitled book")}
>
- {book.title || "Untitled book"}
+ {book.title || t("Untitled book")}
</div>
<p className="line-clamp-3 flex-1 text-xs leading-relaxed text-[var(--muted-foreground)]">
{book.description ||
- "No description yet. Open the book to view its outline."}
+ t(
+ "No description yet. Open the book to view its outline.",
+ )}
</p>
<div className="mt-auto flex items-center justify-between text-[10px] text-[var(--muted-foreground)]/80">
<div className="flex items-center gap-3">
<span className="inline-flex items-center gap-1">
<Layers size={11} />
- {book.chapter_count || 0} ch
+ {t("{{count}} ch", {
+ count: book.chapter_count || 0,
+ })}
</span>
<span className="inline-flex items-center gap-1">
<FileText size={11} />
- {book.page_count || 0} pages
+ {t("{{count}} pages", {
+ count: book.page_count || 0,
+ })}
</span>
</div>
<span className="inline-flex items-center gap-1">
<Clock3 size={11} />
- {relativeTime(book.updated_at) || "—"}
+ {relativeTime(book.updated_at, t) || "—"}
</span>
</div>
</div>
@@ -442,16 +456,18 @@ function StatCard({
}
function EmptyState({ onNewBook }: { onNewBook: () => void }) {
+ const { t } = useTranslation();
return (
<div className="flex flex-col items-center justify-center gap-4 rounded-xl border border-dashed border-[var(--border)] bg-[var(--secondary)]/30 px-8 py-16 text-center">
<BookOpen size={28} className="text-[var(--muted-foreground)]/50" />
<div>
<p className="text-base font-medium text-[var(--foreground)]">
- No books yet
+ {t("No books yet")}
</p>
<p className="mt-1 text-sm text-[var(--muted-foreground)]">
- Create your first AI-generated book from a knowledge base, chat
- selections or simply a topic.
+ {t(
+ "Create your first AI-generated book from a knowledge base, chat selections or simply a topic.",
+ )}
</p>
</div>
<button
@@ -460,7 +476,7 @@ function EmptyState({ onNewBook }: { onNewBook: () => void }) {
className="inline-flex items-center gap-1.5 rounded-md bg-[var(--primary)] px-3 py-1.5 text-sm font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90"
>
<Plus size={14} />
- New book
+ {t("New book")}
</button>
</div>
);
diff --git a/web/app/(workspace)/book/components/BookProgressTimeline.tsx b/web/app/(workspace)/book/components/BookProgressTimeline.tsx
index eefa89eb1..1fb64b25e 100644
--- a/web/app/(workspace)/book/components/BookProgressTimeline.tsx
+++ b/web/app/(workspace)/book/components/BookProgressTimeline.tsx
@@ -11,8 +11,11 @@ import {
BookMarked,
LayoutList,
} from "lucide-react";
+import { useTranslation } from "react-i18next";
import type { BookProgress, StageId, StageView } from "@/lib/book-progress";
+type Translate = (key: string, options?: Record<string, unknown>) => string;
+
export interface BookProgressTimelineProps {
progress: BookProgress;
/** Compact mode — single-line horizontal pill strip (for reader header). */
@@ -83,12 +86,95 @@ function StageIcon({ id, state }: { id: StageId; state: StageView["state"] }) {
return <Icon className={cls} />;
}
+function formatProgressMessage(message: string, t: Translate): string {
+ if (!message) return "";
+ const sourceSweep = message.match(
+ /^Source sweep done — (\d+) queries, (\d+) chunks$/,
+ );
+ if (sourceSweep) {
+ return t("Source sweep done — {{queries}} queries, {{chunks}} chunks", {
+ queries: Number(sourceSweep[1]),
+ chunks: Number(sourceSweep[2]),
+ });
+ }
+ const spineReady = message.match(
+ /^Spine ready — (\d+) chapters · (\d+) concepts$/,
+ );
+ if (spineReady) {
+ return t("Spine ready — {{chapters}} chapters · {{concepts}} concepts", {
+ chapters: Number(spineReady[1]),
+ concepts: Number(spineReady[2]),
+ });
+ }
+ return t(message);
+}
+
+function formatStageDetail(detail: string | undefined, t: Translate): string {
+ if (!detail) return "";
+ const sourceSweep = detail.match(/^(\d+) queries · (\d+) chunks$/);
+ if (sourceSweep) {
+ return t("{{queries}} queries · {{chunks}} chunks", {
+ queries: Number(sourceSweep[1]),
+ chunks: Number(sourceSweep[2]),
+ });
+ }
+ const critique = detail.match(/^(\d+) rounds? · (\d+) issues?$/);
+ if (critique) {
+ const rounds = Number(critique[1]);
+ const issues = Number(critique[2]);
+ const key =
+ rounds === 1
+ ? issues === 1
+ ? "{{rounds}} round · {{issues}} issue"
+ : "{{rounds}} round · {{issues}} issues"
+ : issues === 1
+ ? "{{rounds}} rounds · {{issues}} issue"
+ : "{{rounds}} rounds · {{issues}} issues";
+ return t(key, { rounds, issues });
+ }
+ const synthesis = detail.match(/^(\d+) rounds? · (\d+) chapters?$/);
+ if (synthesis) {
+ const rounds = Number(synthesis[1]);
+ const chapters = Number(synthesis[2]);
+ const key =
+ rounds === 1
+ ? chapters === 1
+ ? "{{rounds}} round · {{chapters}} chapter"
+ : "{{rounds}} round · {{chapters}} chapters"
+ : chapters === 1
+ ? "{{rounds}} rounds · {{chapters}} chapter"
+ : "{{rounds}} rounds · {{chapters}} chapters";
+ return t(key, { rounds, chapters });
+ }
+ const spine = detail.match(/^(\d+) chapters · (\d+) concepts$/);
+ if (spine) {
+ return t("{{chapters}} chapters · {{concepts}} concepts", {
+ chapters: Number(spine[1]),
+ concepts: Number(spine[2]),
+ });
+ }
+ const compilation = detail.match(/^(\d+) pages? · (\d+) blocks$/);
+ if (compilation) {
+ const pages = Number(compilation[1]);
+ const blocks = Number(compilation[2]);
+ return t(
+ pages === 1
+ ? "{{pages}} page · {{blocks}} blocks"
+ : "{{pages}} pages · {{blocks}} blocks",
+ { pages, blocks },
+ );
+ }
+ return t(detail);
+}
+
export default function BookProgressTimeline({
progress,
compact = false,
mini = false,
className = "",
}: BookProgressTimelineProps) {
+ const { t } = useTranslation();
+ const tr: Translate = (key, options) => t(key, options);
const { ordered, stages, message } = progress;
const fraction = stageProgressFraction(progress);
const activeStage =
@@ -96,14 +182,17 @@ export default function BookProgressTimeline({
[...ordered].reverse().find((id) => stages[id].state === "completed") ||
ordered[0];
const activeView = stages[activeStage];
- const counters = collectCounters(progress);
+ const counters = collectCounters(progress, tr);
+ const liveMessage = formatProgressMessage(message, tr);
+ const activeDetail = formatStageDetail(activeView.detail, tr);
// ── Mini mode: thin floating chip (top-right) ───────────────────────
if (mini) {
const allDone = fraction >= 1;
- const tooltip = `${activeView.label}${
- activeView.detail ? ` · ${activeView.detail}` : ""
- }${message && message !== activeView.label ? ` · ${message}` : ""}`;
+ const activeLabel = t(activeView.label);
+ const tooltip = `${activeLabel}${activeDetail ? ` · ${activeDetail}` : ""}${
+ liveMessage && message !== activeView.label ? ` · ${liveMessage}` : ""
+ }`;
return (
<div
className={`pointer-events-auto inline-flex items-center gap-2 rounded-full border border-[var(--border)] bg-[var(--card)]/90 px-2.5 py-1 text-[11px] shadow-sm backdrop-blur ${className}`}
@@ -125,7 +214,7 @@ export default function BookProgressTimeline({
return (
<span
key={id}
- title={`${stages[id].label} · ${s}`}
+ title={`${t(stages[id].label)} · ${t(s)}`}
className={`relative z-10 inline-flex h-3 w-3 items-center justify-center rounded-full ring-1 ${tone.ring} ${tone.bg}`}
>
{s === "running" && (
@@ -142,7 +231,7 @@ export default function BookProgressTimeline({
})}
</div>
<span className="max-w-[160px] truncate text-[10.5px] text-[var(--muted-foreground)]">
- {activeView.label}
+ {activeLabel}
</span>
<span className="tabular-nums text-[10px] font-medium text-[var(--muted-foreground)]">
{Math.round(fraction * 100)}%
@@ -155,7 +244,7 @@ export default function BookProgressTimeline({
return (
<div
className={`flex items-center gap-3 ${className}`}
- title={message || activeView.label}
+ title={liveMessage || t(activeView.label)}
>
{/* Icon strip */}
<div className="flex items-center gap-0.5">
@@ -165,7 +254,7 @@ export default function BookProgressTimeline({
return (
<span
key={id}
- title={`${stages[id].label} · ${s}`}
+ title={`${t(stages[id].label)} · ${t(s)}`}
className={`inline-flex h-5 w-5 items-center justify-center rounded-full ${tone.bg} ${tone.fg}`}
>
<StageIcon id={id} state={s} />
@@ -177,13 +266,13 @@ export default function BookProgressTimeline({
{/* Live caption */}
<div className="min-w-0 flex-1 truncate text-[11px] text-[var(--muted-foreground)]">
<span className="font-medium text-[var(--foreground)]">
- {activeView.label}
+ {t(activeView.label)}
</span>
- {activeView.detail && (
- <span className="ml-1.5 opacity-70">· {activeView.detail}</span>
+ {activeDetail && (
+ <span className="ml-1.5 opacity-70">· {activeDetail}</span>
)}
- {message && message !== activeView.label && (
- <span className="ml-1.5 opacity-70">· {message}</span>
+ {liveMessage && message !== activeView.label && (
+ <span className="ml-1.5 opacity-70">· {liveMessage}</span>
)}
</div>
</div>
@@ -204,19 +293,19 @@ export default function BookProgressTimeline({
fraction < 1 ? "animate-spin" : "opacity-0"
}`}
/>
- Generating book
+ {t("Generating book")}
</div>
<div className="mt-0.5 truncate text-sm font-medium text-[var(--foreground)]">
- {activeView.label}
- {activeView.detail && (
+ {t(activeView.label)}
+ {activeDetail && (
<span className="ml-1.5 text-[12px] font-normal text-[var(--muted-foreground)]">
- · {activeView.detail}
+ · {activeDetail}
</span>
)}
</div>
- {message && message !== activeView.label && (
+ {liveMessage && message !== activeView.label && (
<div className="mt-0.5 truncate text-[11px] text-[var(--muted-foreground)]">
- {message}
+ {liveMessage}
</div>
)}
</div>
@@ -244,7 +333,7 @@ export default function BookProgressTimeline({
return (
<div
key={id}
- title={`${stage.label} — ${stage.description}`}
+ title={`${t(stage.label)} — ${t(stage.description)}`}
className={`group relative flex items-center gap-1.5 rounded-lg px-1.5 py-1.5 ring-1 transition-all ${
isActive
? `${tone.bg} ${tone.ring}`
@@ -260,7 +349,7 @@ export default function BookProgressTimeline({
<div
className={`truncate text-[11px] font-medium ${tone.fg}`}
>
- {stage.label}
+ {t(stage.label)}
</div>
</div>
</div>
@@ -290,38 +379,42 @@ export default function BookProgressTimeline({
function collectCounters(
progress: BookProgress,
+ t: Translate,
): { label: string; value: string | number }[] {
const items: { label: string; value: string | number }[] = [];
if (progress.exploration.queryCount > 0) {
- items.push({ label: "queries", value: progress.exploration.queryCount });
+ items.push({ label: t("queries"), value: progress.exploration.queryCount });
}
if (progress.exploration.chunkCount > 0) {
- items.push({ label: "chunks", value: progress.exploration.chunkCount });
+ items.push({ label: t("chunks"), value: progress.exploration.chunkCount });
}
if (progress.synthesis.chapterCount > 0) {
- items.push({ label: "chapters", value: progress.synthesis.chapterCount });
+ items.push({
+ label: t("chapters"),
+ value: progress.synthesis.chapterCount,
+ });
}
if (progress.synthesis.conceptNodes > 0) {
items.push({
- label: "concepts",
+ label: t("concepts"),
value: `${progress.synthesis.conceptNodes}/${progress.synthesis.conceptEdges}`,
});
}
if (progress.compilation.blocksReady > 0) {
items.push({
- label: "blocks ready",
+ label: t("blocks ready"),
value: progress.compilation.blocksReady,
});
}
if (progress.compilation.pagesReady > 0) {
items.push({
- label: "pages ready",
+ label: t("pages ready"),
value: progress.compilation.pagesReady,
});
}
if (progress.compilation.blocksError > 0) {
items.push({
- label: "block errors",
+ label: t("block errors"),
value: progress.compilation.blocksError,
});
}
diff --git a/web/app/(workspace)/book/components/BookSidebar.tsx b/web/app/(workspace)/book/components/BookSidebar.tsx
index 271d807be..2f4d9f139 100644
--- a/web/app/(workspace)/book/components/BookSidebar.tsx
+++ b/web/app/(workspace)/book/components/BookSidebar.tsx
@@ -1,6 +1,15 @@
"use client";
-import { ArrowLeft, Compass } from "lucide-react";
+import { useState } from "react";
+import {
+ ArrowLeft,
+ ChevronLeft,
+ ChevronRight,
+ Compass,
+ Loader2,
+ RotateCcw,
+} from "lucide-react";
+import { useTranslation } from "react-i18next";
import type { Book, Page } from "@/lib/book-types";
const STATUS_LABEL: Record<string, string> = {
@@ -18,6 +27,8 @@ export interface BookSidebarProps {
pages?: Page[];
selectedPageId?: string | null;
onSelectPage?: (id: string) => void;
+ onRebuild?: () => void;
+ rebuilding?: boolean;
}
export default function BookSidebar({
@@ -26,39 +37,115 @@ export default function BookSidebar({
pages = [],
selectedPageId = null,
onSelectPage,
+ onRebuild,
+ rebuilding = false,
}: BookSidebarProps) {
+ const { t } = useTranslation();
+ const [collapsed, setCollapsed] = useState(false);
+
+ if (collapsed) {
+ return (
+ <aside className="flex h-full w-14 flex-col items-center gap-3 border-r border-[var(--border)] bg-[var(--card)]/40 px-2 py-4">
+ <button
+ onClick={onBackToLibrary}
+ title={t("All books")}
+ className="inline-flex h-8 w-8 items-center justify-center rounded-md text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)]/40 hover:text-[var(--foreground)]"
+ >
+ <ArrowLeft className="h-4 w-4" />
+ </button>
+ <button
+ onClick={() => setCollapsed(false)}
+ title={t("Expand chapters")}
+ className="inline-flex h-8 w-8 items-center justify-center rounded-md text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)]/40 hover:text-[var(--foreground)]"
+ >
+ <ChevronRight className="h-4 w-4" />
+ </button>
+ <div className="mt-1 h-px w-8 bg-[var(--border)]" />
+ <div className="flex flex-1 flex-col items-center gap-1 overflow-y-auto">
+ {pages.map((page, index) => {
+ const active = page.id === selectedPageId;
+ return (
+ <button
+ key={page.id}
+ onClick={() => onSelectPage?.(page.id)}
+ title={page.title || t("Untitled")}
+ className={`inline-flex h-8 w-8 items-center justify-center rounded-md text-[11px] font-semibold ${
+ active
+ ? "bg-[var(--primary)]/15 text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/40 hover:text-[var(--foreground)]"
+ }`}
+ >
+ {page.content_type === "overview" ? (
+ <Compass className="h-3.5 w-3.5" />
+ ) : (
+ index + 1
+ )}
+ </button>
+ );
+ })}
+ </div>
+ </aside>
+ );
+ }
+
return (
<aside className="flex h-full w-[232px] flex-col gap-3 border-r border-[var(--border)] bg-[var(--card)]/40 px-3 py-4">
- <button
- onClick={onBackToLibrary}
- className="inline-flex items-center gap-1.5 self-start rounded-md px-2 py-1 text-xs font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)]/40 hover:text-[var(--foreground)]"
- >
- <ArrowLeft className="h-3.5 w-3.5" /> All books
- </button>
+ <div className="flex items-center justify-between gap-2">
+ <button
+ onClick={onBackToLibrary}
+ className="inline-flex items-center gap-1.5 self-start rounded-md px-2 py-1 text-xs font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)]/40 hover:text-[var(--foreground)]"
+ >
+ <ArrowLeft className="h-3.5 w-3.5" /> {t("All books")}
+ </button>
+ <button
+ onClick={() => setCollapsed(true)}
+ title={t("Collapse chapters")}
+ className="inline-flex h-7 w-7 items-center justify-center rounded-md text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)]/40 hover:text-[var(--foreground)]"
+ >
+ <ChevronLeft className="h-3.5 w-3.5" />
+ </button>
+ </div>
{book && (
<div className="px-1">
<div
className="line-clamp-2 text-sm font-semibold text-[var(--foreground)]"
- title={book.title || "Untitled book"}
+ title={book.title || t("Untitled book")}
>
- {book.title || "Untitled book"}
+ {book.title || t("Untitled book")}
</div>
<div className="mt-0.5 text-[10px] uppercase tracking-wider text-[var(--muted-foreground)]">
- {book.status} · {book.chapter_count || 0} chapters
+ {t(book.status)} ·{" "}
+ {t("{{count}} chapters", { count: book.chapter_count || 0 })}
</div>
</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"
+ >
+ {rebuilding ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <RotateCcw className="h-3.5 w-3.5" />
+ )}
+ {t("Rebuild book")}
+ </button>
+ )}
+
<section className="flex-1 overflow-y-auto">
{pages.length === 0 ? (
<div className="rounded-md border border-dashed border-[var(--border)] px-2 py-3 text-xs text-[var(--muted-foreground)]">
- Pages will appear here once the spine is confirmed.
+ {t("Pages will appear here once the spine is confirmed.")}
</div>
) : (
<>
<div className="mb-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-[var(--muted-foreground)]">
- Chapters
+ {t("Chapters")}
</div>
<ul className="space-y-1">
{pages.map((page) => {
@@ -83,11 +170,11 @@ export default function BookSidebar({
<Compass className="mt-[1px] h-3 w-3 shrink-0 text-[var(--primary)]" />
)}
<span className="line-clamp-2">
- {page.title || "Untitled"}
+ {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)]">
- {STATUS_LABEL[page.status] || page.status}
+ {t(STATUS_LABEL[page.status] || page.status)}
</span>
</button>
</li>
diff --git a/web/app/(workspace)/book/components/PageOutlineNav.tsx b/web/app/(workspace)/book/components/PageOutlineNav.tsx
index db730c72f..95603033b 100644
--- a/web/app/(workspace)/book/components/PageOutlineNav.tsx
+++ b/web/app/(workspace)/book/components/PageOutlineNav.tsx
@@ -19,6 +19,7 @@ import {
Sparkles,
Sticker,
} from "lucide-react";
+import { useTranslation } from "react-i18next";
import type { Block, BlockType, BlockStatus } from "@/lib/book-types";
@@ -54,30 +55,6 @@ const TYPE_LABEL_EN: Record<BlockType, string> = {
concept_graph: "Concept graph",
};
-const TYPE_LABEL_ZH: Record<BlockType, string> = {
- text: "文本",
- section: "章节",
- callout: "要点",
- quiz: "测验",
- user_note: "笔记",
- figure: "图示",
- interactive: "交互",
- animation: "动画",
- code: "代码",
- timeline: "时间线",
- flash_cards: "闪卡",
- deep_dive: "深入",
- concept_graph: "概念图",
-};
-
-const HEADER_EN = "On this page";
-const HEADER_ZH = "本页内容";
-
-const COLLAPSE_TIP_EN = "Hide outline";
-const COLLAPSE_TIP_ZH = "隐藏目录";
-const EXPAND_TIP_EN = "Show outline";
-const EXPAND_TIP_ZH = "展开目录";
-
function shortLabel(block: Block, fallback: string): string {
const title = (block.title || "").trim();
if (title) return title;
@@ -120,14 +97,13 @@ export interface PageOutlineNavProps {
export default function PageOutlineNav({
blocks,
scrollContainer,
- language,
+ language: _language,
resetKey,
}: PageOutlineNavProps) {
- const isZh = (language || "").toLowerCase().startsWith("zh");
- const labelMap = isZh ? TYPE_LABEL_ZH : TYPE_LABEL_EN;
- const headerText = isZh ? HEADER_ZH : HEADER_EN;
- const collapseTip = isZh ? COLLAPSE_TIP_ZH : COLLAPSE_TIP_EN;
- const expandTip = isZh ? EXPAND_TIP_ZH : EXPAND_TIP_EN;
+ const { t } = useTranslation();
+ const headerText = t("On this page");
+ const collapseTip = t("Hide outline");
+ const expandTip = t("Show outline");
// Default: expanded. Reset whenever the page changes.
const [collapsed, setCollapsed] = useState(false);
@@ -248,7 +224,7 @@ export default function PageOutlineNav({
<ol className="flex-1 overflow-y-auto px-1.5 py-1.5">
{visibleBlocks.map((block, idx) => {
const Icon = TYPE_ICON[block.type] || FileText;
- const fallbackLabel = labelMap[block.type] || block.type;
+ const fallbackLabel = t(TYPE_LABEL_EN[block.type] || block.type);
const label = shortLabel(block, fallbackLabel);
const isActive = block.id === activeId;
const isError = block.status === "error";
diff --git a/web/app/(workspace)/book/components/PageReader.tsx b/web/app/(workspace)/book/components/PageReader.tsx
index 5e3205fb0..9451e0d66 100644
--- a/web/app/(workspace)/book/components/PageReader.tsx
+++ b/web/app/(workspace)/book/components/PageReader.tsx
@@ -8,6 +8,7 @@ import {
ChevronDown,
ChevronUp,
} from "lucide-react";
+import { useTranslation } from "react-i18next";
import type { Block, BlockType, Page } from "@/lib/book-types";
import BlockRenderer from "./blocks/BlockRenderer";
import PageOutlineNav from "./PageOutlineNav";
@@ -60,6 +61,7 @@ export default function PageReader({
bookId,
bookLanguage,
}: PageReaderProps) {
+ const { t } = useTranslation();
const [showInsertMenu, setShowInsertMenu] = useState(false);
const [inserting, setInserting] = useState(false);
const [scrollContainer, setScrollContainer] = useState<HTMLDivElement | null>(
@@ -106,14 +108,15 @@ export default function PageReader({
if (!page) {
return (
<div className="flex h-full items-center justify-center text-[var(--muted-foreground)]">
- Select a chapter to start reading.
+ {t("Select a chapter to start reading.")}
</div>
);
}
- const isZh = (bookLanguage || "").toLowerCase().startsWith("zh");
- const expandTip = isZh ? "展开标题栏" : "Expand header";
- const collapseTip = isZh ? "折叠标题栏" : "Collapse header";
+ const expandTip = t("Expand header");
+ const collapseTip = t("Collapse header");
+ const failedBlocks = page.blocks.filter((block) => block.status === "error");
+ const hasFailedBlocks = failedBlocks.length > 0;
return (
// The outer container is `relative` so the floating outline nav can
@@ -133,9 +136,9 @@ export default function PageReader({
"font-semibold leading-tight tracking-tight text-[var(--foreground)] transition-all duration-200",
headerCollapsed ? "truncate text-[15px]" : "text-[26px]",
].join(" ")}
- title={page.title || "Untitled chapter"}
+ title={page.title || t("Untitled chapter")}
>
- {page.title || "Untitled chapter"}
+ {page.title || t("Untitled chapter")}
</h1>
{!headerCollapsed && page.learning_objectives.length > 0 && (
<ul className="mt-3 space-y-0.5 text-[12.5px] text-[var(--muted-foreground)]">
@@ -148,7 +151,7 @@ export default function PageReader({
<div className="flex shrink-0 items-center gap-2">
{!headerCollapsed && (
<span className="rounded-full bg-[var(--muted)] px-2.5 py-0.5 text-[11px] uppercase tracking-wider text-[var(--muted-foreground)]">
- {page.status}
+ {t(page.status)}
</span>
)}
{!headerCollapsed && onRecompile && (
@@ -156,7 +159,7 @@ export default function PageReader({
onClick={onRecompile}
className="inline-flex 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)]"
>
- <RefreshCcw className="h-3.5 w-3.5" /> Recompile
+ <RefreshCcw className="h-3.5 w-3.5" /> {t("Force regenerate")}
</button>
)}
<button
@@ -186,10 +189,65 @@ export default function PageReader({
{loading && page.blocks.length === 0 ? (
<div className="mx-auto flex w-full max-w-[78ch] items-center gap-2 text-sm text-[var(--muted-foreground)]">
<Loader2 className="h-4 w-4 animate-spin" />
- Compiling page…
+ {t("Compiling page…")}
</div>
) : (
<article className="mx-auto flex w-full max-w-[78ch] flex-col gap-6 [&>:first-child]:mt-0">
+ {hasFailedBlocks && (
+ <div className="rounded-2xl border border-amber-300/70 bg-amber-50 px-4 py-3 text-sm text-amber-950 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-100">
+ <div className="mb-2 flex items-center justify-between gap-3">
+ <div className="font-semibold">
+ {failedBlocks.length === 1
+ ? t("{{count}} block failed", {
+ count: failedBlocks.length,
+ })
+ : t("{{count}} blocks failed", {
+ count: failedBlocks.length,
+ })}
+ </div>
+ {onRecompile && (
+ <button
+ onClick={onRecompile}
+ className="inline-flex items-center gap-1 rounded-md border border-current px-2 py-1 text-xs font-medium hover:bg-white/40 dark:hover:bg-white/10"
+ >
+ <RefreshCcw className="h-3.5 w-3.5" />
+ {t("Regenerate page")}
+ </button>
+ )}
+ </div>
+ <div className="space-y-1.5 text-xs opacity-90">
+ {failedBlocks.slice(0, 5).map((block) => {
+ const failure = block.metadata?.failure as
+ | { kind?: string; message?: string }
+ | undefined;
+ return (
+ <div
+ key={block.id}
+ className="flex flex-wrap items-center gap-2"
+ >
+ <code className="rounded bg-white/50 px-1.5 py-0.5 dark:bg-white/10">
+ {block.type}
+ </code>
+ <span>
+ {failure?.kind || t("error")}:{" "}
+ {block.error ||
+ failure?.message ||
+ t("Unknown error")}
+ </span>
+ {onRegenerateBlock && (
+ <button
+ onClick={() => onRegenerateBlock(block)}
+ className="rounded border border-current px-1.5 py-0.5 text-[11px] font-medium hover:bg-white/40 dark:hover:bg-white/10"
+ >
+ {t("Retry block")}
+ </button>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ )}
{page.blocks.map((block) => (
<div
key={block.id}
@@ -213,7 +271,7 @@ export default function PageReader({
))}
{page.blocks.length === 0 && (
<div className="text-sm text-[var(--muted-foreground)]">
- This page has no blocks yet.
+ {t("This page has no blocks yet.")}
</div>
)}
@@ -229,25 +287,25 @@ export default function PageReader({
) : (
<Plus className="h-3.5 w-3.5" />
)}
- Insert block
+ {t("Insert block")}
</button>
{showInsertMenu && (
<div className="absolute top-full mt-1 z-10 grid w-72 grid-cols-2 gap-1 rounded-lg border border-[var(--border)] bg-[var(--card)] p-2 shadow-lg">
- {INSERTABLE_TYPES.map((t) => (
+ {INSERTABLE_TYPES.map((blockType) => (
<button
- key={t}
+ key={blockType}
onClick={async () => {
setShowInsertMenu(false);
setInserting(true);
try {
- await onInsertBlock(t);
+ await onInsertBlock(blockType);
} finally {
setInserting(false);
}
}}
className="rounded px-2 py-1 text-left text-xs text-[var(--foreground)] hover:bg-[var(--background)]"
>
- {t}
+ {t(blockType)}
</button>
))}
</div>
diff --git a/web/app/(workspace)/book/components/SpineEditor.tsx b/web/app/(workspace)/book/components/SpineEditor.tsx
index 28a310d72..2adee0463 100644
--- a/web/app/(workspace)/book/components/SpineEditor.tsx
+++ b/web/app/(workspace)/book/components/SpineEditor.tsx
@@ -9,6 +9,7 @@ import {
Loader2,
} from "lucide-react";
import { useState } from "react";
+import { useTranslation } from "react-i18next";
import type { Chapter, ContentType, Spine } from "@/lib/book-types";
/**
@@ -66,6 +67,7 @@ export default function SpineEditor({
onConfirm,
loading = false,
}: SpineEditorProps) {
+ const { t } = useTranslation();
const [chapters, setChapters] = useState<Chapter[]>(spine.chapters);
const updateChapter = (idx: number, patch: Partial<Chapter>) => {
@@ -95,7 +97,7 @@ export default function SpineEditor({
...prev,
{
id: `ch_new_${prev.length + 1}_${Date.now().toString(36)}`,
- title: "New chapter",
+ title: t("New chapter"),
learning_objectives: [],
content_type: "theory",
source_anchors: [],
@@ -118,10 +120,12 @@ export default function SpineEditor({
<div className="flex h-full flex-col">
<header className="border-b border-[var(--border)] bg-[var(--card)]/60 px-6 py-4">
<h2 className="text-lg font-semibold text-[var(--foreground)]">
- Review the chapter spine
+ {t("Review the chapter spine")}
</h2>
<p className="mt-1 text-sm text-[var(--muted-foreground)]">
- Reorder, rename, or remove chapters before the book starts compiling.
+ {t(
+ "Reorder, rename, or remove chapters before the book starts compiling.",
+ )}
</p>
</header>
@@ -167,10 +171,12 @@ export default function SpineEditor({
<div className="mt-3 grid gap-3 sm:grid-cols-2">
<label className="text-xs text-[var(--muted-foreground)]">
<span className="flex items-center gap-1">
- Content type
+ {t("Content type")}
<span
className="cursor-help text-[10px] opacity-60"
- title="Hint that drives the chapter's block plan (text length, whether to include diagrams / quizzes / code, etc.)."
+ title={t(
+ "Hint that drives the chapter's block plan (text length, whether to include diagrams / quizzes / code, etc.).",
+ )}
>
ⓘ
</span>
@@ -186,32 +192,34 @@ export default function SpineEditor({
>
{CONTENT_TYPE_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>
- {opt.label}
+ {t(opt.label)}
</option>
))}
</select>
<span className="mt-1 block text-[11px] leading-snug text-[var(--muted-foreground)]/80">
- {CONTENT_TYPE_OPTIONS.find(
- (o) => o.value === chapter.content_type,
- )?.description ||
- "Hint for the architect about what blocks to plan."}
+ {t(
+ CONTENT_TYPE_OPTIONS.find(
+ (o) => o.value === chapter.content_type,
+ )?.description ||
+ "Hint for the architect about what blocks to plan.",
+ )}
</span>
</label>
<label className="text-xs text-[var(--muted-foreground)]">
- Summary
+ {t("Summary")}
<input
value={chapter.summary}
onChange={(e) =>
updateChapter(idx, { summary: e.target.value })
}
- placeholder="Optional one-line description"
+ placeholder={t("Optional one-line description")}
className="mt-1 w-full rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1.5 text-sm text-[var(--foreground)]"
/>
</label>
</div>
<label className="mt-3 block text-xs text-[var(--muted-foreground)]">
- Learning objectives (one per line)
+ {t("Learning objectives (one per line)")}
<textarea
value={chapter.learning_objectives.join("\n")}
onChange={(e) =>
@@ -233,7 +241,7 @@ export default function SpineEditor({
onClick={addChapter}
className="inline-flex items-center justify-center gap-1.5 rounded-xl border border-dashed border-[var(--border)] bg-[var(--card)] px-3 py-2 text-sm font-medium text-[var(--muted-foreground)] hover:border-[var(--primary)]/40 hover:text-[var(--primary)]"
>
- <Plus className="h-4 w-4" /> Add chapter
+ <Plus className="h-4 w-4" /> {t("Add chapter")}
</button>
</div>
</div>
@@ -249,7 +257,7 @@ export default function SpineEditor({
) : (
<CheckCircle2 className="h-4 w-4" />
)}
- Confirm spine & start compiling
+ {t("Confirm spine & start compiling")}
</button>
</footer>
</div>
diff --git a/web/app/(workspace)/book/components/blocks/AnimationBlock.tsx b/web/app/(workspace)/book/components/blocks/AnimationBlock.tsx
index 62445540a..060848fc5 100644
--- a/web/app/(workspace)/book/components/blocks/AnimationBlock.tsx
+++ b/web/app/(workspace)/book/components/blocks/AnimationBlock.tsx
@@ -1,6 +1,7 @@
"use client";
import { Download, ExternalLink } from "lucide-react";
+import { useTranslation } from "react-i18next";
import MarkdownRenderer from "@/components/common/MarkdownRenderer";
import { apiUrl } from "@/lib/api";
@@ -25,6 +26,7 @@ function resolveAssetUrl(url: string): string {
}
export default function AnimationBlock({ block }: AnimationBlockProps) {
+ const { t } = useTranslation();
const payload = (block.payload || {}) as Record<string, unknown>;
const rawVideoUrl = String(payload.video_url || "");
const summary = String(payload.summary || "");
@@ -34,7 +36,7 @@ export default function AnimationBlock({ block }: AnimationBlockProps) {
if (!rawVideoUrl && artifacts.length === 0) {
return (
<div className="rounded-2xl border border-dashed border-[var(--border)] bg-[var(--card)]/40 p-4 text-xs italic text-[var(--muted-foreground)]">
- (Animation payload is empty)
+ {t("(Animation payload is empty)")}
</div>
);
}
@@ -62,7 +64,7 @@ export default function AnimationBlock({ block }: AnimationBlockProps) {
) : (
<img
src={primary}
- alt={description || "Animation frame"}
+ alt={description || t("Animation frame")}
className="h-auto w-full"
/>
)}
@@ -72,17 +74,17 @@ export default function AnimationBlock({ block }: AnimationBlockProps) {
href={primary}
target="_blank"
rel="noopener noreferrer"
- title="Open in new tab"
+ title={t("Open in new tab")}
className="inline-flex items-center gap-1 rounded-md bg-black/40 px-2 py-1 text-[10px] font-medium text-white/90 backdrop-blur-sm transition-colors hover:bg-black/60 hover:text-white"
>
<ExternalLink size={11} strokeWidth={1.8} />
- Open
+ {t("Open")}
</a>
{isVideo && (
<a
href={primary}
download={filename || true}
- title="Download video"
+ title={t("Download video")}
className="inline-flex items-center gap-1 rounded-md bg-black/40 px-2 py-1 text-[10px] font-medium text-white/90 backdrop-blur-sm transition-colors hover:bg-black/60 hover:text-white"
>
<Download size={11} strokeWidth={1.8} />
diff --git a/web/app/(workspace)/book/components/blocks/BlockRenderer.tsx b/web/app/(workspace)/book/components/blocks/BlockRenderer.tsx
index 7da603478..af2b8dc95 100644
--- a/web/app/(workspace)/book/components/blocks/BlockRenderer.tsx
+++ b/web/app/(workspace)/book/components/blocks/BlockRenderer.tsx
@@ -10,6 +10,7 @@ import {
ArrowDown,
Replace,
} from "lucide-react";
+import { useTranslation } from "react-i18next";
import type { Block, BlockType } from "@/lib/book-types";
import MarkdownRenderer from "@/components/common/MarkdownRenderer";
@@ -72,32 +73,42 @@ export default function BlockRenderer({
currentPageId,
bookLanguage,
}: BlockRendererProps) {
+ const { t } = useTranslation();
const [showTypeMenu, setShowTypeMenu] = useState(false);
if (block.status === "pending" || block.status === "generating") {
return (
<div className="flex items-center gap-2 rounded-2xl border border-dashed border-[var(--border)] bg-[var(--card)] px-4 py-3 text-sm text-[var(--muted-foreground)]">
<Loader2 className="h-4 w-4 animate-spin" />
- <span>Generating {block.type}…</span>
+ <span>{t("Generating {{type}}…", { type: t(block.type) })}</span>
</div>
);
}
if (block.status === "error") {
+ const failure = block.metadata?.failure as
+ | { kind?: string; message?: string; retryable?: boolean }
+ | undefined;
return (
<div className="rounded-2xl border border-rose-300/60 bg-rose-50 px-4 py-3 text-sm text-rose-900 dark:border-rose-500/40 dark:bg-rose-500/10 dark:text-rose-100">
<div className="mb-1 flex items-center gap-2 font-medium">
<AlertTriangle className="h-4 w-4" />
- {block.type} block failed
+ {t("{{type}} block failed", { type: t(block.type) })}
</div>
+ {failure?.kind && (
+ <div className="mb-1 text-[11px] uppercase tracking-wider opacity-70">
+ {failure.kind}
+ {failure.retryable === false ? ` · ${t("not retryable")}` : ""}
+ </div>
+ )}
<div className="text-xs opacity-80">
- {block.error || "Unknown error"}
+ {block.error || failure?.message || t("Unknown error")}
</div>
{onRegenerate && (
<button
onClick={() => onRegenerate(block)}
className="mt-2 inline-flex rounded-md border border-rose-400/60 bg-white/40 px-2 py-1 text-xs font-medium hover:bg-white/60 dark:bg-white/10"
>
- Retry
+ {t("Retry")}
</button>
)}
</div>
@@ -183,14 +194,14 @@ export default function BlockRenderer({
<button
onClick={() => onMove(block, "up")}
className="pointer-events-auto rounded p-1 hover:bg-[var(--background)] hover:text-[var(--foreground)]"
- title="Move up"
+ title={t("Move up")}
>
<ArrowUp className="h-3.5 w-3.5" />
</button>
<button
onClick={() => onMove(block, "down")}
className="pointer-events-auto rounded p-1 hover:bg-[var(--background)] hover:text-[var(--foreground)]"
- title="Move down"
+ title={t("Move down")}
>
<ArrowDown className="h-3.5 w-3.5" />
</button>
@@ -201,24 +212,26 @@ export default function BlockRenderer({
<button
onClick={() => setShowTypeMenu((v) => !v)}
className="rounded p-1 hover:bg-[var(--background)] hover:text-[var(--foreground)]"
- title="Change type"
+ title={t("Change type")}
>
<Replace className="h-3.5 w-3.5" />
</button>
{showTypeMenu && (
<div className="absolute right-0 top-full mt-1 max-h-60 w-44 overflow-y-auto rounded-md border border-[var(--border)] bg-[var(--card)] p-1 shadow-lg">
- {CHANGEABLE_TYPES.filter((t) => t !== block.type).map((t) => (
- <button
- key={t}
- onClick={() => {
- setShowTypeMenu(false);
- onChangeType(block, t);
- }}
- className="block w-full rounded px-2 py-1 text-left text-xs hover:bg-[var(--background)] hover:text-[var(--foreground)]"
- >
- {t}
- </button>
- ))}
+ {CHANGEABLE_TYPES.filter((type) => type !== block.type).map(
+ (type) => (
+ <button
+ key={type}
+ onClick={() => {
+ setShowTypeMenu(false);
+ onChangeType(block, type);
+ }}
+ className="block w-full rounded px-2 py-1 text-left text-xs hover:bg-[var(--background)] hover:text-[var(--foreground)]"
+ >
+ {t(type)}
+ </button>
+ ),
+ )}
</div>
)}
</div>
@@ -227,7 +240,7 @@ export default function BlockRenderer({
<button
onClick={() => onRegenerate(block)}
className="pointer-events-auto rounded p-1 hover:bg-[var(--background)] hover:text-[var(--foreground)]"
- title="Regenerate"
+ title={t("Regenerate")}
>
<RefreshCw className="h-3.5 w-3.5" />
</button>
@@ -236,7 +249,7 @@ export default function BlockRenderer({
<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="Delete"
+ title={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.tsx
index a2f045e0e..a5e0eaaa4 100644
--- a/web/app/(workspace)/book/components/blocks/ConceptGraphBlock.tsx
+++ b/web/app/(workspace)/book/components/blocks/ConceptGraphBlock.tsx
@@ -3,6 +3,7 @@
import { useMemo } from "react";
import Link from "next/link";
import { Compass } from "lucide-react";
+import { useTranslation } from "react-i18next";
import MarkdownRenderer from "@/components/common/MarkdownRenderer";
import type { Block, ConceptGraph } from "@/lib/book-types";
@@ -14,34 +15,6 @@ export interface ConceptGraphBlockProps {
language?: string;
}
-const LABELS: Record<
- string,
- {
- chapterMap: (n: number, e: number) => string;
- conceptMap: (n: number, e: number) => string;
- chapterIndex: string;
- noChapters: string;
- }
-> = {
- zh: {
- chapterMap: (n, e) => `章节图谱 · ${n} 章 · ${e} 条依赖`,
- conceptMap: (n, e) => `概念图 · ${n} 个概念 · ${e} 条关系`,
- chapterIndex: "章节索引",
- noChapters: "(暂无章节)",
- },
- en: {
- chapterMap: (n, e) => `Chapter map · ${n} chapters · ${e} dependencies`,
- conceptMap: (n, e) => `Concept map · ${n} concepts · ${e} relations`,
- chapterIndex: "Chapter index",
- noChapters: "(No chapters yet)",
- },
-};
-
-function pickLabels(language?: string) {
- const code = (language || "en").toLowerCase().split("-")[0];
- return LABELS[code] ?? LABELS.en;
-}
-
interface ChapterIndexEntry {
id: string;
title: string;
@@ -84,9 +57,9 @@ export default function ConceptGraphBlock({
block,
bookId,
currentPageId: _currentPageId,
- language,
+ language: _language,
}: ConceptGraphBlockProps) {
- const labels = pickLabels(language);
+ const { t } = useTranslation();
const code =
(block.payload?.code as
| { language?: string; content?: string }
@@ -115,8 +88,20 @@ export default function ConceptGraphBlock({
<Compass className="h-3.5 w-3.5" />
<span>
{isChapterMap
- ? labels.chapterMap(chapterNodes.length, edgeCount)
- : labels.conceptMap(nodeCount, edgeCount)}
+ ? t(
+ "Chapter map · {{chapters}} chapters · {{dependencies}} dependencies",
+ {
+ chapters: chapterNodes.length,
+ dependencies: edgeCount,
+ },
+ )
+ : t(
+ "Concept map · {{concepts}} concepts · {{relations}} relations",
+ {
+ concepts: nodeCount,
+ relations: edgeCount,
+ },
+ )}
</span>
</header>
<div className="max-h-[60vh] overflow-auto">
@@ -126,12 +111,12 @@ export default function ConceptGraphBlock({
<aside className="rounded-2xl border border-[var(--border)] bg-[var(--card)]/60 p-3 shadow-sm">
<h3 className="mb-2 text-xs font-semibold uppercase tracking-wider text-[var(--muted-foreground)]">
- {labels.chapterIndex}
+ {t("Chapter index")}
</h3>
<ol className="space-y-1.5">
{index.chapters.length === 0 && (
<li className="text-xs italic text-[var(--muted-foreground)]">
- {labels.noChapters}
+ {t("(No chapters yet)")}
</li>
)}
{index.chapters.map((chapter, idx) => {
diff --git a/web/app/(workspace)/book/components/blocks/DeepDiveBlock.tsx b/web/app/(workspace)/book/components/blocks/DeepDiveBlock.tsx
index 680c5d7e4..76a05e3ce 100644
--- a/web/app/(workspace)/book/components/blocks/DeepDiveBlock.tsx
+++ b/web/app/(workspace)/book/components/blocks/DeepDiveBlock.tsx
@@ -2,6 +2,7 @@
import { useState } from "react";
import { ChevronRight, Sparkles, Loader2 } from "lucide-react";
+import { useTranslation } from "react-i18next";
import type { Block } from "@/lib/book-types";
interface Suggestion {
@@ -20,6 +21,7 @@ export default function DeepDiveBlock({
onDeepDive,
pendingTopic,
}: DeepDiveBlockProps) {
+ const { t } = useTranslation();
const suggestions =
(block.payload?.suggestions as Suggestion[] | undefined) || [];
const linkedPageId = block.metadata?.deep_dive_page_id as string | undefined;
@@ -32,7 +34,7 @@ export default function DeepDiveBlock({
<div className="mb-3 flex items-center gap-2">
<Sparkles className="h-4 w-4 text-[var(--primary)]" />
<span className="text-[11px] font-semibold uppercase tracking-[0.16em] text-[var(--primary)]">
- Go Deeper
+ {t("Go Deeper")}
</span>
</div>
<ul className="space-y-2">
@@ -76,7 +78,7 @@ export default function DeepDiveBlock({
</ul>
{linkedPageId && (
<p className="mt-2 text-[11px] text-[var(--muted-foreground)]">
- Linked sub-page already exists.
+ {t("Linked sub-page already exists.")}
</p>
)}
</div>
diff --git a/web/app/(workspace)/book/components/blocks/FigureBlock.tsx b/web/app/(workspace)/book/components/blocks/FigureBlock.tsx
index 5dc4f9d33..89be7dcd4 100644
--- a/web/app/(workspace)/book/components/blocks/FigureBlock.tsx
+++ b/web/app/(workspace)/book/components/blocks/FigureBlock.tsx
@@ -2,6 +2,7 @@
import VisualizationViewer from "@/components/visualize/VisualizationViewer";
import MarkdownRenderer from "@/components/common/MarkdownRenderer";
+import { useTranslation } from "react-i18next";
import type { Block } from "@/lib/book-types";
import type {
VisualizeRenderType,
@@ -34,6 +35,7 @@ function coerceRenderType(
}
export default function FigureBlock({ block }: FigureBlockProps) {
+ const { t } = useTranslation();
const code =
(block.payload?.code as
| { language?: string; content?: string }
@@ -50,7 +52,7 @@ export default function FigureBlock({ block }: FigureBlockProps) {
if (!content.trim()) {
return (
<div className="rounded-2xl border border-dashed border-[var(--border)] bg-[var(--card)]/40 p-4 text-xs italic text-[var(--muted-foreground)]">
- (Figure payload is empty)
+ {t("(Figure payload is empty)")}
</div>
);
}
diff --git a/web/app/(workspace)/book/components/blocks/FlashCardsBlock.tsx b/web/app/(workspace)/book/components/blocks/FlashCardsBlock.tsx
index e99a14ccd..abf323e81 100644
--- a/web/app/(workspace)/book/components/blocks/FlashCardsBlock.tsx
+++ b/web/app/(workspace)/book/components/blocks/FlashCardsBlock.tsx
@@ -2,6 +2,7 @@
import { useState } from "react";
import { ChevronLeft, ChevronRight, RotateCcw } from "lucide-react";
+import { useTranslation } from "react-i18next";
import type { Block } from "@/lib/book-types";
interface Card {
@@ -15,6 +16,7 @@ export interface FlashCardsBlockProps {
}
export default function FlashCardsBlock({ block }: FlashCardsBlockProps) {
+ const { t } = useTranslation();
const cards = (block.payload?.cards as Card[] | undefined) || [];
const [idx, setIdx] = useState(0);
const [showBack, setShowBack] = useState(false);
@@ -25,7 +27,7 @@ export default function FlashCardsBlock({ block }: FlashCardsBlockProps) {
<div className="rounded-2xl border border-[var(--border)] bg-[var(--card)] p-4 shadow-sm">
<div className="flex items-center justify-between">
<span className="text-[11px] font-semibold uppercase tracking-[0.16em] text-[var(--primary)]">
- Flash Cards
+ {t("Flash Cards")}
</span>
<span className="text-xs text-[var(--muted-foreground)]">
{idx + 1} / {cards.length}
@@ -36,14 +38,14 @@ export default function FlashCardsBlock({ block }: FlashCardsBlockProps) {
className="mt-3 flex h-40 w-full flex-col items-center justify-center gap-2 rounded-xl border border-[var(--border)] bg-[var(--background)] px-6 text-center transition hover:border-[var(--primary)]/40"
>
<span className="text-[10px] uppercase tracking-wider text-[var(--muted-foreground)]">
- {showBack ? "Answer" : "Question"}
+ {showBack ? t("Answer") : t("Question")}
</span>
<span className="text-base font-medium text-[var(--foreground)]">
{showBack ? card.back : card.front}
</span>
{!showBack && card.hint && (
<span className="text-xs italic text-[var(--muted-foreground)]">
- Hint: {card.hint}
+ {t("Hint")}: {card.hint}
</span>
)}
</button>
@@ -56,13 +58,13 @@ export default function FlashCardsBlock({ block }: FlashCardsBlockProps) {
disabled={idx === 0}
className="inline-flex items-center gap-1 rounded-md border border-[var(--border)] px-2 py-1 text-xs disabled:opacity-30"
>
- <ChevronLeft className="h-3.5 w-3.5" /> Prev
+ <ChevronLeft className="h-3.5 w-3.5" /> {t("Prev")}
</button>
<button
onClick={() => setShowBack((v) => !v)}
className="inline-flex items-center gap-1 rounded-md border border-[var(--border)] px-2 py-1 text-xs hover:border-[var(--primary)]/40 hover:text-[var(--primary)]"
>
- <RotateCcw className="h-3.5 w-3.5" /> Flip
+ <RotateCcw className="h-3.5 w-3.5" /> {t("Flip")}
</button>
<button
onClick={() => {
@@ -72,7 +74,7 @@ export default function FlashCardsBlock({ block }: FlashCardsBlockProps) {
disabled={idx >= cards.length - 1}
className="inline-flex items-center gap-1 rounded-md border border-[var(--border)] px-2 py-1 text-xs disabled:opacity-30"
>
- Next <ChevronRight className="h-3.5 w-3.5" />
+ {t("Next")} <ChevronRight className="h-3.5 w-3.5" />
</button>
</div>
</div>
diff --git a/web/app/(workspace)/book/components/blocks/InteractiveBlock.tsx b/web/app/(workspace)/book/components/blocks/InteractiveBlock.tsx
index 4d82d54d3..9eb864469 100644
--- a/web/app/(workspace)/book/components/blocks/InteractiveBlock.tsx
+++ b/web/app/(workspace)/book/components/blocks/InteractiveBlock.tsx
@@ -2,6 +2,7 @@
import VisualizationViewer from "@/components/visualize/VisualizationViewer";
import MarkdownRenderer from "@/components/common/MarkdownRenderer";
+import { useTranslation } from "react-i18next";
import type { Block } from "@/lib/book-types";
import type { VisualizeResult } from "@/lib/visualize-types";
@@ -10,6 +11,7 @@ export interface InteractiveBlockProps {
}
export default function InteractiveBlock({ block }: InteractiveBlockProps) {
+ const { t } = useTranslation();
const code =
(block.payload?.code as
| { language?: string; content?: string }
@@ -25,7 +27,7 @@ export default function InteractiveBlock({ block }: InteractiveBlockProps) {
if (!content.trim()) {
return (
<div className="rounded-2xl border border-dashed border-[var(--border)] bg-[var(--card)]/40 p-4 text-xs italic text-[var(--muted-foreground)]">
- (Interactive payload is empty)
+ {t("(Interactive payload is empty)")}
</div>
);
}
diff --git a/web/app/(workspace)/book/components/blocks/PlaceholderBlock.tsx b/web/app/(workspace)/book/components/blocks/PlaceholderBlock.tsx
index a64359d85..af8cade5c 100644
--- a/web/app/(workspace)/book/components/blocks/PlaceholderBlock.tsx
+++ b/web/app/(workspace)/book/components/blocks/PlaceholderBlock.tsx
@@ -1,6 +1,7 @@
"use client";
import { Sparkles } from "lucide-react";
+import { useTranslation } from "react-i18next";
import type { Block } from "@/lib/book-types";
export interface PlaceholderBlockProps {
@@ -18,6 +19,7 @@ const LABELS: Record<string, string> = {
};
export default function PlaceholderBlock({ block }: PlaceholderBlockProps) {
+ const { t } = useTranslation();
const label = LABELS[block.type] || block.type;
const intended = block.params?.intended_block_type
? String(block.params.intended_block_type)
@@ -26,10 +28,12 @@ export default function PlaceholderBlock({ block }: PlaceholderBlockProps) {
<div className="flex items-center gap-3 rounded-2xl border border-dashed border-[var(--border)] bg-[var(--muted)]/30 px-4 py-3 text-sm text-[var(--muted-foreground)]">
<Sparkles className="h-4 w-4 text-[var(--primary)]" />
<div>
- <div className="font-medium text-[var(--foreground)]">{label}</div>
+ <div className="font-medium text-[var(--foreground)]">{t(label)}</div>
<div className="text-xs">
- Coming in Phase 2 – {intended} block will appear here once the
- generator is wired.
+ {t(
+ "Coming in Phase 2 – {{type}} block will appear here once the generator is wired.",
+ { type: t(intended) },
+ )}
</div>
</div>
</div>
diff --git a/web/app/(workspace)/book/components/blocks/QuizBlock.tsx b/web/app/(workspace)/book/components/blocks/QuizBlock.tsx
index 5cf403b87..fe964e004 100644
--- a/web/app/(workspace)/book/components/blocks/QuizBlock.tsx
+++ b/web/app/(workspace)/book/components/blocks/QuizBlock.tsx
@@ -2,6 +2,7 @@
import { useEffect, useState } from "react";
import { CheckCircle2, Eye, EyeOff, XCircle } from "lucide-react";
+import { useTranslation } from "react-i18next";
import MarkdownRenderer from "@/components/common/MarkdownRenderer";
import type { Block } from "@/lib/book-types";
@@ -33,12 +34,13 @@ export interface QuizBlockProps {
}
export default function QuizBlock({ block, onAttempt }: QuizBlockProps) {
+ const { t } = useTranslation();
const questions =
(block.payload?.questions as QuizQuestion[] | undefined) || [];
if (questions.length === 0) {
return (
<div className="text-sm text-[var(--muted-foreground)]">
- No quiz questions generated.
+ {t("No quiz questions generated.")}
</div>
);
}
@@ -46,7 +48,7 @@ export default function QuizBlock({ block, onAttempt }: QuizBlockProps) {
<section>
<div className="mb-3 flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-[var(--primary)]">
<span className="h-px flex-1 bg-[var(--primary)]/20" />
- Quick Check
+ {t("Quick Check")}
<span className="h-px flex-1 bg-[var(--primary)]/20" />
</div>
<div className="space-y-3">
@@ -72,6 +74,7 @@ function QuizQuestionCard({
question: QuizQuestion;
onAttempt?: (args: QuizAttemptArgs) => void;
}) {
+ const { t } = useTranslation();
const [selected, setSelected] = useState<string | null>(null);
const [revealed, setRevealed] = useState(false);
const [reported, setReported] = useState(false);
@@ -108,7 +111,7 @@ function QuizQuestionCard({
</span>
<div className="min-w-0 flex-1">
<MarkdownRenderer
- content={String(question.question || "(missing)")}
+ content={String(question.question || t("(missing)"))}
variant="compact"
className="font-sans text-sm font-medium text-[var(--foreground)] [&_ol]:my-2 [&_p:first-child]:mt-0 [&_p:last-child]:mb-0 [&_p]:my-1.5 [&_pre]:my-2 [&_ul]:my-2"
/>
@@ -158,8 +161,8 @@ function QuizQuestionCard({
) : (
<div className="mt-2 text-xs text-[var(--muted-foreground)]">
{normalizedType === "written"
- ? "Think about your answer, then reveal the solution."
- : "Open response — click reveal to see the model answer."}
+ ? t("Think about your answer, then reveal the solution.")
+ : t("Open response — click reveal to see the model answer.")}
</div>
)}
@@ -173,11 +176,11 @@ function QuizQuestionCard({
) : (
<Eye className="h-3.5 w-3.5" />
)}
- {revealed ? "Hide answer" : "Reveal answer"}
+ {revealed ? t("Hide answer") : t("Reveal answer")}
</button>
{revealed && correct && isChoice && (
<span className="text-xs text-[var(--muted-foreground)]">
- Answer:{" "}
+ {t("Answer")}:{" "}
<span className="font-mono text-[var(--foreground)]">
{correctChoiceKey || correct}
</span>
@@ -188,7 +191,7 @@ function QuizQuestionCard({
{revealed && correct && !isChoice && (
<div className="mt-2 rounded-lg border border-[var(--border)] bg-[var(--card)]/70 p-2">
<div className="mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-[var(--muted-foreground)]">
- Answer
+ {t("Answer")}
</div>
<MarkdownRenderer
content={correct}
diff --git a/web/app/(workspace)/book/components/blocks/SectionBlock.tsx b/web/app/(workspace)/book/components/blocks/SectionBlock.tsx
index eb8b4d85b..0244e4d98 100644
--- a/web/app/(workspace)/book/components/blocks/SectionBlock.tsx
+++ b/web/app/(workspace)/book/components/blocks/SectionBlock.tsx
@@ -1,6 +1,7 @@
"use client";
import { Sparkles } from "lucide-react";
+import { useTranslation } from "react-i18next";
import MarkdownRenderer from "@/components/common/MarkdownRenderer";
import type { Block } from "@/lib/book-types";
@@ -17,6 +18,7 @@ interface Subsection {
}
export default function SectionBlock({ block }: SectionBlockProps) {
+ const { t } = useTranslation();
const payload = block.payload || {};
const intro = String(payload.intro ?? "").trim();
const keyTakeaway = String(payload.key_takeaway ?? "").trim();
@@ -34,7 +36,7 @@ export default function SectionBlock({ block }: SectionBlockProps) {
{focus && (
<div className="mb-4 text-[11px] uppercase tracking-wider text-[var(--muted-foreground)]">
- Section focus · {focus}
+ {t("Section focus")} · {focus}
</div>
)}
@@ -54,7 +56,7 @@ export default function SectionBlock({ block }: SectionBlockProps) {
<div className="mt-6 flex items-start gap-2 rounded-xl border border-[var(--border)] bg-[var(--muted)]/30 px-3 py-2 text-sm">
<Sparkles className="mt-0.5 h-4 w-4 flex-shrink-0 text-[var(--muted-foreground)]" />
<div className="flex-1">
- <span className="mr-1 font-medium">Key takeaway:</span>
+ <span className="mr-1 font-medium">{t("Key takeaway:")}</span>
<span className="text-[var(--foreground)]">{keyTakeaway}</span>
</div>
</div>
diff --git a/web/app/(workspace)/book/components/blocks/UserNoteBlock.tsx b/web/app/(workspace)/book/components/blocks/UserNoteBlock.tsx
index 58626b6d3..ae084c821 100644
--- a/web/app/(workspace)/book/components/blocks/UserNoteBlock.tsx
+++ b/web/app/(workspace)/book/components/blocks/UserNoteBlock.tsx
@@ -1,6 +1,7 @@
"use client";
import { StickyNote } from "lucide-react";
+import { useTranslation } from "react-i18next";
import MarkdownRenderer from "@/components/common/MarkdownRenderer";
import type { Block } from "@/lib/book-types";
@@ -9,19 +10,20 @@ export interface UserNoteBlockProps {
}
export default function UserNoteBlock({ block }: UserNoteBlockProps) {
+ const { t } = useTranslation();
const body = String(block.payload?.body || "");
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">
<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)]">
- Your note
+ {t("Your note")}
</div>
{body ? (
<MarkdownRenderer content={body} variant="compact" />
) : (
<div className="text-xs text-[var(--muted-foreground)]">
- Empty note – start writing your own annotation.
+ {t("Empty note – start writing your own annotation.")}
</div>
)}
</div>
diff --git a/web/app/(workspace)/book/page.tsx b/web/app/(workspace)/book/page.tsx
index 71e855670..e37caf1ce 100644
--- a/web/app/(workspace)/book/page.tsx
+++ b/web/app/(workspace)/book/page.tsx
@@ -11,6 +11,7 @@ import {
} from "react";
import { useSearchParams } from "next/navigation";
import { Loader2, MessageSquare } from "lucide-react";
+import { useTranslation } from "react-i18next";
import { bookApi, openBookSocket } from "@/lib/book-api";
import type {
@@ -48,7 +49,7 @@ export default function BookPage() {
<Suspense
fallback={
<div className="flex h-screen w-full items-center justify-center text-[var(--muted-foreground)]">
- <Loader2 className="mr-2 h-4 w-4 animate-spin" /> Loading…
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" /> <BookLoadingText />
</div>
}
>
@@ -57,7 +58,13 @@ export default function BookPage() {
);
}
+function BookLoadingText() {
+ const { t } = useTranslation();
+ return <>{t("Loading…")}</>;
+}
+
function BookPageInner() {
+ const { t } = useTranslation();
const [books, setBooks] = useState<Book[]>([]);
const [loadingBooks, setLoadingBooks] = useState(false);
const [view, setView] = useState<View>("list");
@@ -85,6 +92,7 @@ function BookPageInner() {
string | null
>(null);
const [chatOpen, setChatOpen] = useState(false);
+ const [rebuildingBook, setRebuildingBook] = useState(false);
// Phase 5 — live BookEngine progress timeline state.
const [progress, dispatchProgress] = useReducer(
@@ -154,6 +162,12 @@ function BookPageInner() {
return detail.pages.find((p) => p.id === selectedPageId) || null;
}, [detail, selectedPageId]);
+ const selectedPageChatSessionId = useMemo(() => {
+ if (!detail?.book || !selectedPage) return null;
+ const sessions = detail.book.metadata?.page_chat_sessions;
+ return sessions?.[selectedPage.id] || null;
+ }, [detail?.book, selectedPage]);
+
// ── Handlers ───────────────────────────────────────────────────────
const handleNewBook = () => {
@@ -206,7 +220,7 @@ function BookPageInner() {
}, [requestedBookId, selectedBookId, handleSelectBook]);
const handleDeleteBook = async (id: string) => {
- if (!confirm("Delete this book? This cannot be undone.")) return;
+ if (!confirm(t("Delete this book? This cannot be undone."))) return;
await bookApi.delete(id);
if (selectedBookId === id) {
setSelectedBookId(null);
@@ -216,6 +230,29 @@ function BookPageInner() {
await refreshBooks();
};
+ const handleRebuildBook = async () => {
+ if (!detail) return;
+ if (
+ !confirm(
+ t(
+ "Rebuild this book using the current chapter structure? Existing generated pages will be replaced.",
+ ),
+ )
+ ) {
+ 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;
@@ -302,7 +339,8 @@ function BookPageInner() {
const handleDeleteBlock = async (block: Block) => {
if (!detail || !selectedPage) return;
- if (!confirm(`Delete this ${block.type} block?`)) 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);
};
@@ -385,6 +423,23 @@ function BookPageInner() {
}
};
+ 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 (
@@ -396,6 +451,8 @@ function BookPageInner() {
pages={detail?.pages || []}
selectedPageId={selectedPageId}
onSelectPage={handleSelectPage}
+ onRebuild={detail ? () => void handleRebuildBook() : undefined}
+ rebuilding={rebuildingBook}
/>
)}
@@ -488,7 +545,8 @@ function BookPageInner() {
{view === "spine" && !detail?.spine && (
<div className="flex h-full items-center justify-center text-[var(--muted-foreground)]">
- <Loader2 className="mr-2 h-4 w-4 animate-spin" /> Loading spine…
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />{" "}
+ {t("Loading spine…")}
</div>
)}
</div>
@@ -499,7 +557,7 @@ function BookPageInner() {
className="absolute bottom-4 right-4 inline-flex items-center gap-2 rounded-full bg-[var(--primary)] px-4 py-2 text-sm font-medium text-[var(--primary-foreground)] shadow-lg hover:opacity-90"
>
<MessageSquare className="h-4 w-4" />
- Chat
+ {t("Chat")}
</button>
)}
@@ -509,6 +567,10 @@ function BookPageInner() {
page={selectedPage}
open={chatOpen}
onClose={() => setChatOpen(false)}
+ initialSessionId={selectedPageChatSessionId}
+ onSessionResolved={(sessionId) =>
+ void handlePageChatSession(sessionId)
+ }
/>
)}
</main>
diff --git a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx b/web/app/(workspace)/chat/[[...sessionId]]/page.tsx
index ee1a56ff4..02ba16f9c 100644
--- a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx
+++ b/web/app/(workspace)/chat/[[...sessionId]]/page.tsx
@@ -80,6 +80,10 @@ import {
import { listKnowledgeBases } from "@/lib/knowledge-api";
import { downloadChatMarkdown } from "@/lib/chat-export";
import type { SpaceMemoryFile } from "@/lib/space-items";
+import {
+ selectedBooksToPayload,
+ type SelectedBookReference,
+} from "@/lib/book-references";
const NotebookRecordPicker = dynamic(
() => import("@/components/notebook/NotebookRecordPicker"),
@@ -105,6 +109,12 @@ const SkillsPicker = dynamic(() => import("@/components/chat/SkillsPicker"), {
const MemoryPicker = dynamic(() => import("@/components/chat/MemoryPicker"), {
ssr: false,
});
+const BookReferencePicker = dynamic(
+ () => import("@/components/chat/BookReferencePicker"),
+ {
+ ssr: false,
+ },
+);
const SaveToNotebookModal = dynamic(
() => import("@/components/notebook/SaveToNotebookModal"),
{
@@ -249,7 +259,7 @@ export default function ChatPage() {
const router = useRouter();
const { t } = useTranslation();
const sessionIdParam = params.sessionId?.[0] ?? null;
- const { setActiveSessionId } = useAppShell();
+ const { setActiveSessionId, language: appLanguage } = useAppShell();
const {
state,
@@ -296,6 +306,7 @@ export default function ChatPage() {
const [panelCollapsed, setPanelCollapsed] = useState(true);
const [showSaveModal, setShowSaveModal] = useState(false);
const [showNotebookPicker, setShowNotebookPicker] = useState(false);
+ const [showBookPicker, setShowBookPicker] = useState(false);
const [showHistoryPicker, setShowHistoryPicker] = useState(false);
const [showQuestionBankPicker, setShowQuestionBankPicker] = useState(false);
const [showSkillsPicker, setShowSkillsPicker] = useState(false);
@@ -305,6 +316,9 @@ export default function ChatPage() {
const [selectedNotebookRecords, setSelectedNotebookRecords] = useState<
SelectedRecord[]
>([]);
+ const [selectedBookReferences, setSelectedBookReferences] = useState<
+ SelectedBookReference[]
+ >([]);
const [selectedHistorySessions, setSelectedHistorySessions] = useState<
SelectedHistorySession[]
>([]);
@@ -381,6 +395,10 @@ export default function ChatPage() {
record_ids,
}));
}, [selectedNotebookRecords]);
+ const bookReferencesPayload = useMemo(
+ () => selectedBooksToPayload(selectedBookReferences),
+ [selectedBookReferences],
+ );
const historyReferencesPayload = useMemo(
() => selectedHistorySessions.map((session) => session.sessionId),
[selectedHistorySessions],
@@ -468,6 +486,7 @@ export default function ChatPage() {
// back to ``chat`` if the requested capability is missing.
const answerNowSnapshot: MessageRequestSnapshot = {
...snapshot,
+ language: appLanguage,
config: {
...(snapshot.config || {}),
answer_now_context: {
@@ -488,6 +507,7 @@ export default function ChatPage() {
displayUserMessage: false,
persistUserMessage: false,
requestSnapshotOverride: answerNowSnapshot,
+ bookReferences: answerNowSnapshot.bookReferences,
},
answerNowSnapshot.questionNotebookReferences,
answerNowSnapshot.skills,
@@ -496,7 +516,13 @@ export default function ChatPage() {
shouldAutoScrollRef.current = true;
}, 0);
},
- [cancelStreamingTurn, sendMessage, shouldAutoScrollRef, state.isStreaming],
+ [
+ appLanguage,
+ cancelStreamingTurn,
+ sendMessage,
+ shouldAutoScrollRef,
+ state.isStreaming,
+ ],
);
/* ---- URL-driven session loading ---- */
@@ -861,6 +887,7 @@ export default function ChatPage() {
if (
(!content &&
!attachments.length &&
+ !selectedBookReferences.length &&
!selectedNotebookRecords.length &&
!selectedHistorySessions.length &&
!selectedQuestionEntries.length &&
@@ -906,18 +933,21 @@ export default function ChatPage() {
const messageContent =
content ||
(selectedNotebookRecords.length ||
+ selectedBookReferences.length ||
selectedHistorySessions.length ||
selectedQuestionEntries.length ||
skillsPayload.length ||
memoryPayload.length
- ? "Please use the selected context to help with this request."
+ ? t("Please use the selected context to help with this request.")
: "") ||
(isMathAnimatorMode
? attachments.some((a) => a.type === "image")
- ? "Generate a math animation from the attached reference image(s)."
+ ? t(
+ "Generate a math animation from the attached reference image(s).",
+ )
: ""
: attachments.some((a) => a.type === "image")
- ? "Please analyze the attached image(s)."
+ ? t("Please analyze the attached image(s).")
: "");
sendMessage(
messageContent,
@@ -925,7 +955,7 @@ export default function ChatPage() {
config,
notebookReferencesPayload,
historyReferencesPayload,
- undefined,
+ { bookReferences: bookReferencesPayload },
questionNotebookReferencesPayload,
skillsPayload,
memoryPayload,
@@ -935,6 +965,7 @@ export default function ChatPage() {
// composer stays compact during conversation.
setPanelCollapsed(true);
setAttachments([]);
+ setSelectedBookReferences([]);
setSelectedNotebookRecords([]);
setSelectedHistorySessions([]);
setSelectedQuestionEntries([]);
@@ -944,6 +975,7 @@ export default function ChatPage() {
},
[
attachments,
+ bookReferencesPayload,
historyReferencesPayload,
isMathAnimatorMode,
isQuizMode,
@@ -958,6 +990,7 @@ export default function ChatPage() {
researchConfig,
selectedHistorySessions.length,
selectedMemoryFiles.length,
+ selectedBookReferences.length,
selectedNotebookRecords.length,
selectedQuestionEntries.length,
selectedSkills,
@@ -965,6 +998,7 @@ export default function ChatPage() {
sendMessage,
shouldAutoScrollRef,
state.isStreaming,
+ t,
visualizeConfig,
],
);
@@ -1005,6 +1039,9 @@ export default function ChatPage() {
const handleSelectNotebookPicker = useCallback(() => {
setShowNotebookPicker(true);
}, []);
+ const handleSelectBookPicker = useCallback(() => {
+ setShowBookPicker(true);
+ }, []);
const handleSelectHistoryPicker = useCallback(() => {
setShowHistoryPicker(true);
}, []);
@@ -1027,6 +1064,11 @@ export default function ChatPage() {
prev.filter((record) => record.notebookId !== notebookId),
);
}, []);
+ const handleRemoveBookReference = useCallback((bookId: string) => {
+ setSelectedBookReferences((prev) =>
+ prev.filter((record) => record.bookId !== bookId),
+ );
+ }, []);
const handleRemoveQuestion = useCallback((entryId: number) => {
setSelectedQuestionEntries((prev) =>
prev.filter((entry) => entry.id !== entryId),
@@ -1058,6 +1100,15 @@ export default function ChatPage() {
const handleCloseNotebookPicker = useCallback(() => {
setShowNotebookPicker(false);
}, []);
+ const handleCloseBookPicker = useCallback(() => {
+ setShowBookPicker(false);
+ }, []);
+ const handleApplyBookReferences = useCallback(
+ (references: SelectedBookReference[]) => {
+ setSelectedBookReferences(references);
+ },
+ [],
+ );
const handleApplyNotebookRecords = useCallback(
(records: SelectedRecord[]) => {
setSelectedNotebookRecords(records);
@@ -1224,6 +1275,7 @@ export default function ChatPage() {
selectedTools={selectedTools}
ragActive={ragActive}
knowledgeBases={knowledgeBases}
+ selectedBookReferences={selectedBookReferences}
selectedNotebookRecords={selectedNotebookRecords}
selectedHistorySessions={selectedHistorySessions}
selectedQuestionEntries={selectedQuestionEntries}
@@ -1251,6 +1303,7 @@ export default function ChatPage() {
onSetSpaceMenuOpen={setSpaceMenuOpen}
onSetKB={handleSetKB}
onSelectNotebookPicker={handleSelectNotebookPicker}
+ onSelectBookPicker={handleSelectBookPicker}
onSelectHistoryPicker={handleSelectHistoryPicker}
onSelectQuestionBankPicker={handleSelectQuestionBankPicker}
onSelectSkillsPicker={handleSelectSkillsPicker}
@@ -1264,6 +1317,7 @@ export default function ChatPage() {
onRemoveAttachment={removeAttachment}
onPreviewAttachment={handlePreviewPendingAttachment}
onRemoveHistory={handleRemoveHistory}
+ onRemoveBookReference={handleRemoveBookReference}
onRemoveNotebook={handleRemoveNotebook}
onRemoveQuestion={handleRemoveQuestion}
onDragEnter={handleDragEnter}
@@ -1287,6 +1341,12 @@ export default function ChatPage() {
onClose={handleCloseNotebookPicker}
onApply={handleApplyNotebookRecords}
/>
+ <BookReferencePicker
+ open={showBookPicker}
+ initialReferences={selectedBookReferences}
+ onClose={handleCloseBookPicker}
+ onApply={handleApplyBookReferences}
+ />
<HistorySessionPicker
open={showHistoryPicker}
onClose={handleCloseHistoryPicker}
diff --git a/web/components/chat/BookReferencePicker.tsx b/web/components/chat/BookReferencePicker.tsx
new file mode 100644
index 000000000..e298a382f
--- /dev/null
+++ b/web/components/chat/BookReferencePicker.tsx
@@ -0,0 +1,412 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import {
+ BookOpen,
+ Check,
+ ChevronRight,
+ Layers3,
+ Loader2,
+ Search,
+ X,
+} from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { bookApi } from "@/lib/book-api";
+import type { Book, BookDetail, Chapter, Page } from "@/lib/book-types";
+import type {
+ SelectedBookPage,
+ SelectedBookReference,
+} from "@/lib/book-references";
+
+interface BookReferencePickerProps {
+ open: boolean;
+ initialReferences: SelectedBookReference[];
+ onClose: () => void;
+ onApply: (references: SelectedBookReference[]) => void;
+}
+
+function pageKey(bookId: string, pageId: string): string {
+ return `${bookId}:${pageId}`;
+}
+
+function groupPages(detail: BookDetail | null): Array<{
+ chapter: Chapter | null;
+ pages: Page[];
+}> {
+ if (!detail) return [];
+ const byId = new Map(detail.pages.map((page) => [page.id, page]));
+ const used = new Set<string>();
+ const groups: Array<{ chapter: Chapter | null; pages: Page[] }> = (
+ detail.spine?.chapters || []
+ ).map((chapter) => {
+ const pages = chapter.page_ids
+ .map((pageId) => byId.get(pageId))
+ .filter((page): page is Page => Boolean(page));
+ pages.forEach((page) => used.add(page.id));
+ return { chapter, pages };
+ });
+ const orphanPages = detail.pages.filter((page) => !used.has(page.id));
+ if (orphanPages.length) groups.push({ chapter: null, pages: orphanPages });
+ return groups.filter((group) => group.pages.length > 0);
+}
+
+export default function BookReferencePicker({
+ open,
+ initialReferences,
+ onClose,
+ onApply,
+}: BookReferencePickerProps) {
+ const { t } = useTranslation();
+ const [books, setBooks] = useState<Book[]>([]);
+ const [details, setDetails] = useState<Record<string, BookDetail>>({});
+ const [activeBookId, setActiveBookId] = useState<string | null>(null);
+ const [selected, setSelected] = useState<SelectedBookReference[]>([]);
+ const [query, setQuery] = useState("");
+ const [loadingBooks, setLoadingBooks] = useState(false);
+ const [loadingDetail, setLoadingDetail] = useState(false);
+
+ useEffect(() => {
+ if (!open) return;
+ let mounted = true;
+ setSelected(initialReferences);
+ setLoadingBooks(true);
+ void bookApi
+ .list()
+ .then((data) => {
+ if (!mounted) return;
+ setBooks(data.books || []);
+ setActiveBookId((current) => current || data.books?.[0]?.id || null);
+ })
+ .catch(() => {
+ if (mounted) setBooks([]);
+ })
+ .finally(() => {
+ if (mounted) setLoadingBooks(false);
+ });
+ return () => {
+ mounted = false;
+ };
+ }, [initialReferences, open]);
+
+ useEffect(() => {
+ if (!open || !activeBookId || details[activeBookId]) return;
+ let mounted = true;
+ setLoadingDetail(true);
+ void bookApi
+ .get(activeBookId)
+ .then((detail) => {
+ if (!mounted) return;
+ setDetails((prev) => ({ ...prev, [activeBookId]: detail }));
+ })
+ .catch(() => undefined)
+ .finally(() => {
+ if (mounted) setLoadingDetail(false);
+ });
+ return () => {
+ mounted = false;
+ };
+ }, [activeBookId, details, open]);
+
+ const filteredBooks = useMemo(() => {
+ const keyword = query.trim().toLowerCase();
+ if (!keyword) return books;
+ return books.filter((book) =>
+ `${book.title} ${book.description}`.toLowerCase().includes(keyword),
+ );
+ }, [books, query]);
+
+ const activeBook = books.find((book) => book.id === activeBookId) || null;
+ const activeDetail = activeBookId ? details[activeBookId] || null : null;
+ const pageGroups = useMemo(() => groupPages(activeDetail), [activeDetail]);
+ const selectedKeys = useMemo(() => {
+ const keys = new Set<string>();
+ selected.forEach((book) =>
+ book.pages.forEach((page) => keys.add(pageKey(book.bookId, page.pageId))),
+ );
+ return keys;
+ }, [selected]);
+
+ const togglePage = (book: Book, page: Page, chapter: Chapter | null) => {
+ const nextPage: SelectedBookPage = {
+ bookId: book.id,
+ bookTitle: book.title || t("Untitled book"),
+ pageId: page.id,
+ pageTitle: page.title || t("Untitled chapter"),
+ chapterId: chapter?.id || page.chapter_id,
+ chapterTitle: chapter?.title || page.title || t("Untitled chapter"),
+ };
+ setSelected((prev) => {
+ const existing = prev.find((ref) => ref.bookId === book.id);
+ const selectedAlready = existing?.pages.some((p) => p.pageId === page.id);
+ if (selectedAlready) {
+ return prev
+ .map((ref) =>
+ ref.bookId === book.id
+ ? { ...ref, pages: ref.pages.filter((p) => p.pageId !== page.id) }
+ : ref,
+ )
+ .filter((ref) => ref.pages.length > 0);
+ }
+ if (existing) {
+ return prev.map((ref) =>
+ ref.bookId === book.id ? { ...ref, pages: [...ref.pages, nextPage] } : ref,
+ );
+ }
+ return [
+ ...prev,
+ { bookId: book.id, bookTitle: book.title || t("Untitled book"), pages: [nextPage] },
+ ];
+ });
+ };
+
+ const toggleChapter = (book: Book, chapter: Chapter | null, pages: Page[]) => {
+ const allSelected = pages.every((page) => selectedKeys.has(pageKey(book.id, page.id)));
+ setSelected((prev) => {
+ const existing = prev.find((ref) => ref.bookId === book.id);
+ const existingPages = existing?.pages || [];
+ const pageIds = new Set(pages.map((page) => page.id));
+ const remaining = allSelected
+ ? existingPages.filter((page) => !pageIds.has(page.pageId))
+ : [
+ ...existingPages,
+ ...pages
+ .filter((page) => !existingPages.some((p) => p.pageId === page.id))
+ .map((page) => ({
+ bookId: book.id,
+ bookTitle: book.title || t("Untitled book"),
+ pageId: page.id,
+ pageTitle: page.title || t("Untitled chapter"),
+ chapterId: chapter?.id || page.chapter_id,
+ chapterTitle: chapter?.title || page.title || t("Untitled chapter"),
+ })),
+ ];
+ const nextRef = {
+ bookId: book.id,
+ bookTitle: book.title || t("Untitled book"),
+ pages: remaining,
+ };
+ const others = prev.filter((ref) => ref.bookId !== book.id);
+ return nextRef.pages.length ? [...others, nextRef] : others;
+ });
+ };
+
+ const selectedCount = selected.reduce((total, ref) => total + ref.pages.length, 0);
+
+ if (!open) return null;
+
+ return (
+ <div className="fixed inset-0 z-[85] flex items-center justify-center bg-[var(--background)]/65 p-4 backdrop-blur-md">
+ <div className="surface-card flex h-[78vh] w-full max-w-5xl flex-col overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--card)] text-[var(--card-foreground)] shadow-[0_22px_70px_rgba(0,0,0,0.18)]">
+ <div className="flex items-start justify-between gap-3 border-b border-[var(--border)] px-5 py-4">
+ <div className="min-w-0">
+ <div className="mb-1 inline-flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] text-[var(--primary)]">
+ <BookOpen className="h-3 w-3" />
+ {t("Book Reference")}
+ </div>
+ <h2 className="text-lg font-semibold text-[var(--foreground)]">
+ {t("Select Book Chapters")}
+ </h2>
+ <p className="mt-0.5 text-sm text-[var(--muted-foreground)]">
+ {t("Choose generated book chapters to ground the next answer.")}
+ </p>
+ </div>
+ <button
+ onClick={onClose}
+ className="rounded-lg p-2 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ aria-label={t("Close")}
+ >
+ <X size={18} />
+ </button>
+ </div>
+
+ <div className="grid min-h-0 flex-1 grid-cols-[300px_minmax(0,1fr)]">
+ <aside className="flex min-h-0 flex-col border-r border-[var(--border)] bg-[var(--background)]/40 p-4">
+ <div className="relative mb-3">
+ <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[var(--muted-foreground)]" />
+ <input
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ placeholder={t("Search books")}
+ className="w-full rounded-xl border border-[var(--border)] bg-[var(--card)] py-2.5 pl-9 pr-3 text-[13px] outline-none transition focus:border-[var(--primary)]/50 focus:ring-2 focus:ring-[var(--primary)]/15"
+ />
+ </div>
+ <div className="min-h-0 flex-1 overflow-y-auto rounded-2xl border border-[var(--border)] bg-[var(--card)]">
+ {loadingBooks ? (
+ <div className="flex h-full min-h-[220px] items-center justify-center">
+ <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
+ </div>
+ ) : filteredBooks.length ? (
+ <div className="divide-y divide-[var(--border)]">
+ {filteredBooks.map((book) => {
+ const active = book.id === activeBookId;
+ const selectedPages =
+ selected.find((ref) => ref.bookId === book.id)?.pages.length || 0;
+ return (
+ <button
+ key={book.id}
+ onClick={() => setActiveBookId(book.id)}
+ className={`flex w-full items-center gap-3 px-3 py-3 text-left transition-colors ${
+ active ? "bg-[var(--primary)]/8" : "hover:bg-[var(--muted)]/40"
+ }`}
+ >
+ <BookOpen className="h-4 w-4 shrink-0 text-[var(--muted-foreground)]" />
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-[13px] font-medium text-[var(--foreground)]">
+ {book.title || t("Untitled book")}
+ </span>
+ <span className="mt-0.5 block text-[11px] text-[var(--muted-foreground)]">
+ {book.page_count || 0} {t("chapters")}
+ </span>
+ </span>
+ {selectedPages > 0 && (
+ <span className="rounded-full bg-[var(--primary)]/10 px-1.5 py-px text-[9px] font-semibold text-[var(--primary)]">
+ {selectedPages}
+ </span>
+ )}
+ <ChevronRight className="h-4 w-4 text-[var(--muted-foreground)]" />
+ </button>
+ );
+ })}
+ </div>
+ ) : (
+ <div className="px-5 py-12 text-center text-[13px] text-[var(--muted-foreground)]">
+ {t("No books found.")}
+ </div>
+ )}
+ </div>
+ </aside>
+
+ <section className="min-h-0 overflow-y-auto p-5">
+ {!activeBook ? (
+ <div className="flex h-full items-center justify-center text-sm text-[var(--muted-foreground)]">
+ {t("Select a book to view chapters.")}
+ </div>
+ ) : loadingDetail && !activeDetail ? (
+ <div className="flex h-full items-center justify-center">
+ <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
+ </div>
+ ) : (
+ <div className="space-y-4">
+ <div>
+ <h3 className="text-base font-semibold text-[var(--foreground)]">
+ {activeBook.title || t("Untitled book")}
+ </h3>
+ {activeBook.description && (
+ <p className="mt-1 line-clamp-2 text-sm text-[var(--muted-foreground)]">
+ {activeBook.description}
+ </p>
+ )}
+ </div>
+ {pageGroups.map(({ chapter, pages }) => {
+ const allSelected = pages.every((page) =>
+ selectedKeys.has(pageKey(activeBook.id, page.id)),
+ );
+ const showPageRows = pages.length > 1;
+ const firstPage = pages[0];
+ return (
+ <div
+ key={chapter?.id || pages[0]?.id}
+ className="overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--background)]/35"
+ >
+ <button
+ onClick={() => toggleChapter(activeBook, chapter, pages)}
+ className={`flex w-full items-start gap-3 px-4 py-3 text-left transition-colors hover:bg-[var(--muted)]/35 ${
+ showPageRows ? "border-b border-[var(--border)]" : ""
+ }`}
+ >
+ <span
+ className={`mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-md border transition-colors ${
+ allSelected
+ ? "border-[var(--primary)] bg-[var(--primary)] text-[var(--primary-foreground)]"
+ : "border-[var(--border)] text-transparent"
+ }`}
+ >
+ <Check size={12} />
+ </span>
+ <Layers3 className="mt-0.5 h-4 w-4 shrink-0 text-[var(--muted-foreground)]" />
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-[13px] font-medium text-[var(--foreground)]">
+ {chapter?.title || firstPage?.title || t("Unassigned pages")}
+ </span>
+ <span className="text-[11px] text-[var(--muted-foreground)]">
+ {pages.length} {t("pages")}
+ </span>
+ {!showPageRows && firstPage?.learning_objectives?.length ? (
+ <span className="mt-1 line-clamp-2 text-[12px] leading-5 text-[var(--muted-foreground)]">
+ {firstPage.learning_objectives.join("; ")}
+ </span>
+ ) : null}
+ </span>
+ </button>
+ {showPageRows && (
+ <div className="divide-y divide-[var(--border)]">
+ {pages.map((page) => {
+ const checked = selectedKeys.has(pageKey(activeBook.id, page.id));
+ return (
+ <button
+ key={page.id}
+ onClick={() => togglePage(activeBook, page, chapter)}
+ className={`flex w-full items-start gap-3 px-5 py-3 text-left transition-colors ${
+ checked ? "bg-[var(--primary)]/8" : "hover:bg-[var(--muted)]/30"
+ }`}
+ >
+ <span
+ className={`mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-md border transition-colors ${
+ checked
+ ? "border-[var(--primary)] bg-[var(--primary)] text-[var(--primary-foreground)]"
+ : "border-[var(--border)] text-transparent"
+ }`}
+ >
+ <Check size={12} />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block text-[13px] font-medium text-[var(--foreground)]">
+ {page.title || t("Untitled chapter")}
+ </span>
+ {page.learning_objectives?.length ? (
+ <span className="mt-1 line-clamp-2 text-[12px] leading-5 text-[var(--muted-foreground)]">
+ {page.learning_objectives.join("; ")}
+ </span>
+ ) : null}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </section>
+ </div>
+
+ <div className="flex items-center justify-between gap-3 border-t border-[var(--border)] px-5 py-4">
+ <div className="text-sm text-[var(--muted-foreground)]">
+ {selectedCount
+ ? t("{{count}} chapters selected", { count: selectedCount })
+ : t("No chapters selected")}
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ onClick={() => setSelected([])}
+ className="rounded-xl border border-[var(--border)] px-4 py-2 text-sm font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ >
+ {t("Clear")}
+ </button>
+ <button
+ onClick={() => {
+ onApply(selected);
+ onClose();
+ }}
+ className="rounded-xl bg-[var(--primary)] px-4 py-2 text-sm font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90"
+ >
+ {t("Apply")}
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/web/components/chat/home/ChatComposer.tsx b/web/components/chat/home/ChatComposer.tsx
index f1b1558d3..192f1f6a6 100644
--- a/web/components/chat/home/ChatComposer.tsx
+++ b/web/components/chat/home/ChatComposer.tsx
@@ -41,9 +41,11 @@ import type {
} from "@/lib/research-types";
import ChatSpaceMenu from "@/components/chat/space/ChatSpaceMenu";
import type { SpaceMemoryFile } from "@/lib/space-items";
+import type { SelectedBookReference } from "@/lib/book-references";
type SpaceSelectionCounts = {
chatHistory: number;
+ books: number;
notebooks: number;
questionBank: number;
skills: number;
@@ -126,6 +128,7 @@ export default memo(function ChatComposer({
ragActive,
knowledgeBases,
selectedNotebookRecords,
+ selectedBookReferences,
selectedHistorySessions,
selectedQuestionEntries,
notebookReferenceGroups,
@@ -152,6 +155,7 @@ export default memo(function ChatComposer({
onSetSpaceMenuOpen,
onSetKB,
onSelectNotebookPicker,
+ onSelectBookPicker,
onSelectHistoryPicker,
onSelectQuestionBankPicker,
onSelectSkillsPicker,
@@ -165,6 +169,7 @@ export default memo(function ChatComposer({
onRemoveAttachment,
onPreviewAttachment,
onRemoveHistory,
+ onRemoveBookReference,
onRemoveNotebook,
onRemoveQuestion,
onDragEnter,
@@ -203,6 +208,7 @@ export default memo(function ChatComposer({
ragActive: boolean;
knowledgeBases: KnowledgeBase[];
selectedNotebookRecords: SelectedRecord[];
+ selectedBookReferences: SelectedBookReference[];
selectedHistorySessions: SelectedHistorySession[];
selectedQuestionEntries: SelectedQuestionEntry[];
notebookReferenceGroups: Array<{
@@ -233,6 +239,7 @@ export default memo(function ChatComposer({
onSetSpaceMenuOpen: (open: boolean | ((prev: boolean) => boolean)) => void;
onSetKB: (kb: string) => void;
onSelectNotebookPicker: () => void;
+ onSelectBookPicker: () => void;
onSelectHistoryPicker: () => void;
onSelectQuestionBankPicker: () => void;
onSelectSkillsPicker: () => void;
@@ -246,6 +253,7 @@ export default memo(function ChatComposer({
onRemoveAttachment: (index: number) => void;
onPreviewAttachment?: (index: number) => void;
onRemoveHistory: (sessionId: string) => void;
+ onRemoveBookReference: (bookId: string) => void;
onRemoveNotebook: (notebookId: string) => void;
onRemoveQuestion: (entryId: number) => void;
onDragEnter: (event: React.DragEvent) => void;
@@ -310,6 +318,7 @@ export default memo(function ChatComposer({
const hasReferences =
!!attachments.length ||
+ !!selectedBookReferences.length ||
!!selectedNotebookRecords.length ||
!!selectedHistorySessions.length ||
!!selectedQuestionEntries.length ||
@@ -325,6 +334,10 @@ export default memo(function ChatComposer({
const skillsCount = skillsAutoMode ? 1 : selectedSkills.length;
const spaceSelectionCounts: SpaceSelectionCounts = {
chatHistory: selectedHistorySessions.length,
+ books: selectedBookReferences.reduce(
+ (total, ref) => total + ref.pages.length,
+ 0,
+ ),
notebooks: selectedNotebookRecords.length,
questionBank: selectedQuestionEntries.length,
skills: skillsCount,
@@ -332,6 +345,7 @@ export default memo(function ChatComposer({
};
const spaceSelectionCount =
spaceSelectionCounts.chatHistory +
+ spaceSelectionCounts.books +
spaceSelectionCounts.notebooks +
spaceSelectionCounts.questionBank +
spaceSelectionCounts.skills +
@@ -438,12 +452,14 @@ export default memo(function ChatComposer({
<div className="px-4 pt-3.5 [&>div]:mb-0">
<SpaceContextChips
historySessions={selectedHistorySessions}
+ bookReferences={selectedBookReferences}
notebookGroups={notebookReferenceGroups}
questionEntries={selectedQuestionEntries}
selectedSkills={selectedSkills}
skillsAutoMode={skillsAutoMode}
memoryFiles={selectedMemoryFiles}
onRemoveHistory={onRemoveHistory}
+ onRemoveBookReference={onRemoveBookReference}
onRemoveNotebook={onRemoveNotebook}
onRemoveQuestion={onRemoveQuestion}
onRemoveSkill={onToggleSkill}
@@ -464,6 +480,7 @@ export default memo(function ChatComposer({
onPaste={onPaste}
selectedCounts={spaceSelectionCounts}
onSelectNotebookPicker={onSelectNotebookPicker}
+ onSelectBookPicker={onSelectBookPicker}
onSelectHistoryPicker={onSelectHistoryPicker}
onSelectQuestionBankPicker={onSelectQuestionBankPicker}
onSelectSkillsPicker={onSelectSkillsPicker}
@@ -799,6 +816,7 @@ export default memo(function ChatComposer({
onSelectItem={(key) => {
onSetSpaceMenuOpen(false);
if (key === "chat_history") onSelectHistoryPicker();
+ else if (key === "books") onSelectBookPicker();
else if (key === "notebooks")
onSelectNotebookPicker();
else if (key === "question_bank")
diff --git a/web/components/chat/home/ChatMessages.tsx b/web/components/chat/home/ChatMessages.tsx
index db5ebddfd..ad0369749 100644
--- a/web/components/chat/home/ChatMessages.tsx
+++ b/web/components/chat/home/ChatMessages.tsx
@@ -30,6 +30,7 @@ import { extractQuizQuestions } from "@/lib/quiz-types";
import { extractVisualizeResult } from "@/lib/visualize-types";
import type { StreamEvent } from "@/lib/unified-ws";
import { hasVisibleMarkdownContent } from "@/lib/markdown-display";
+import type { SelectedBookReference } from "@/lib/book-references";
import type { SpaceMemoryFile } from "@/lib/space-items";
import { CallTracePanel } from "./TracePanels";
@@ -386,6 +387,7 @@ const UserMessage = memo(function UserMessage({
{(() => {
const snap = msg.requestSnapshot;
const hasNotebook = Boolean(snap?.notebookReferences?.length);
+ const hasBooks = Boolean(snap?.bookReferences?.length);
const hasHistory = Boolean(snap?.historyReferences?.length);
const hasQuestions = Boolean(
snap?.questionNotebookReferences?.length,
@@ -394,6 +396,7 @@ const UserMessage = memo(function UserMessage({
const hasMemory = Boolean(snap?.memoryReferences?.length);
if (
!hasNotebook &&
+ !hasBooks &&
!hasHistory &&
!hasQuestions &&
!hasSkills &&
@@ -411,6 +414,15 @@ const UserMessage = memo(function UserMessage({
{t("Notebook")} · {ref.record_ids.length} {t("records")}
</span>
))}
+ {snap?.bookReferences?.map((ref) => (
+ <span
+ key={ref.book_id}
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"
+ >
+ <BookOpen size={11} strokeWidth={1.8} />
+ {t("Book")} · {ref.page_ids.length} {t("chapters")}
+ </span>
+ ))}
{snap?.historyReferences?.map((sid) => (
<span
key={sid}
@@ -460,12 +472,14 @@ UserMessage.displayName = "UserMessage";
export const SpaceContextChips = memo(function SpaceContextChips({
historySessions,
+ bookReferences,
notebookGroups,
questionEntries,
selectedSkills,
skillsAutoMode,
memoryFiles,
onRemoveHistory,
+ onRemoveBookReference,
onRemoveNotebook,
onRemoveQuestion,
onRemoveSkill,
@@ -473,12 +487,14 @@ export const SpaceContextChips = memo(function SpaceContextChips({
onRemoveMemoryFile,
}: {
historySessions: SelectedHistorySession[];
+ bookReferences: SelectedBookReference[];
notebookGroups: NotebookReferenceGroup[];
questionEntries: SelectedQuestionEntry[];
selectedSkills: string[];
skillsAutoMode: boolean;
memoryFiles: SpaceMemoryFile[];
onRemoveHistory: (sessionId: string) => void;
+ onRemoveBookReference: (bookId: string) => void;
onRemoveNotebook: (notebookId: string) => void;
onRemoveQuestion: (entryId: number) => void;
onRemoveSkill: (skill: string) => void;
@@ -488,6 +504,7 @@ export const SpaceContextChips = memo(function SpaceContextChips({
const { t } = useTranslation();
if (
historySessions.length === 0 &&
+ bookReferences.length === 0 &&
notebookGroups.length === 0 &&
questionEntries.length === 0 &&
selectedSkills.length === 0 &&
@@ -516,6 +533,24 @@ export const SpaceContextChips = memo(function SpaceContextChips({
</button>
</span>
))}
+ {bookReferences.map((book) => (
+ <span
+ key={book.bookId}
+ className="inline-flex max-w-full items-center gap-2 rounded-xl border border-teal-200 bg-teal-50 px-3 py-1.5 text-[12px] text-teal-800 shadow-sm dark:border-teal-900/60 dark:bg-teal-950/30 dark:text-teal-200"
+ >
+ <BookOpen size={12} strokeWidth={1.8} className="shrink-0" />
+ <span className="shrink-0 font-medium">{t("Book")}</span>
+ <span className="truncate text-teal-700/90 dark:text-teal-200/90">
+ {book.bookTitle} ({book.pages.length})
+ </span>
+ <button
+ onClick={() => onRemoveBookReference(book.bookId)}
+ className="shrink-0 opacity-60 transition hover:opacity-100"
+ >
+ <X size={12} />
+ </button>
+ </span>
+ ))}
{notebookGroups.map((group) => (
<span
key={group.notebookId}
diff --git a/web/components/chat/home/ComposerInput.tsx b/web/components/chat/home/ComposerInput.tsx
index 5bf96e7be..b66f5c5f7 100644
--- a/web/components/chat/home/ComposerInput.tsx
+++ b/web/components/chat/home/ComposerInput.tsx
@@ -30,6 +30,7 @@ interface ComposerInputProps {
onPaste: (e: React.ClipboardEvent) => void;
selectedCounts: ChatSpaceSelectionCounts;
onSelectNotebookPicker: () => void;
+ onSelectBookPicker: () => void;
onSelectHistoryPicker: () => void;
onSelectQuestionBankPicker: () => void;
onSelectSkillsPicker: () => void;
@@ -63,6 +64,7 @@ export const ComposerInput = memo(
onPaste,
selectedCounts,
onSelectNotebookPicker,
+ onSelectBookPicker,
onSelectHistoryPicker,
onSelectQuestionBankPicker,
onSelectSkillsPicker,
@@ -179,6 +181,7 @@ export const ComposerInput = memo(
(
key:
| "chat_history"
+ | "books"
| "notebooks"
| "question_bank"
| "skills"
@@ -187,6 +190,7 @@ export const ComposerInput = memo(
clearTrailingMention();
setShowAtPopup(false);
if (key === "chat_history") onSelectHistoryPicker();
+ else if (key === "books") onSelectBookPicker();
else if (key === "notebooks") onSelectNotebookPicker();
else if (key === "question_bank") onSelectQuestionBankPicker();
else if (key === "skills") onSelectSkillsPicker();
@@ -195,6 +199,7 @@ export const ComposerInput = memo(
[
clearTrailingMention,
onSelectHistoryPicker,
+ onSelectBookPicker,
onSelectNotebookPicker,
onSelectQuestionBankPicker,
onSelectSkillsPicker,
diff --git a/web/components/chat/space/ChatSpaceMenu.tsx b/web/components/chat/space/ChatSpaceMenu.tsx
index 72b130d1e..4e4382e9d 100644
--- a/web/components/chat/space/ChatSpaceMenu.tsx
+++ b/web/components/chat/space/ChatSpaceMenu.tsx
@@ -1,16 +1,21 @@
"use client";
import { memo } from "react";
+import { BookOpen } from "lucide-react";
import { useTranslation } from "react-i18next";
-import { SPACE_ITEMS, type SpaceItemKey } from "@/lib/space-items";
+import { SPACE_ITEMS } from "@/lib/space-items";
-type SelectableSpaceKey = Extract<
- SpaceItemKey,
- "chat_history" | "notebooks" | "question_bank" | "skills" | "memory"
->;
+type SelectableSpaceKey =
+ | "chat_history"
+ | "books"
+ | "notebooks"
+ | "question_bank"
+ | "skills"
+ | "memory";
export interface ChatSpaceSelectionCounts {
chatHistory: number;
+ books: number;
notebooks: number;
questionBank: number;
skills: number;
@@ -25,6 +30,7 @@ interface ChatSpaceMenuProps {
const ITEM_ORDER: SelectableSpaceKey[] = [
"chat_history",
+ "books",
"notebooks",
"question_bank",
"skills",
@@ -38,6 +44,8 @@ function countFor(
switch (key) {
case "chat_history":
return counts.chatHistory;
+ case "books":
+ return counts.books;
case "notebooks":
return counts.notebooks;
case "question_bank":
@@ -61,8 +69,15 @@ export default memo(function ChatSpaceMenu({
// Render the items in a fixed, hand-tuned order so the menu always reads
// the same regardless of how SPACE_ITEMS may be reordered for navigation.
- const items = ITEM_ORDER.map(
- (key) => SPACE_ITEMS.find((it) => it.key === key)!,
+ const items = ITEM_ORDER.map((key) =>
+ key === "books"
+ ? {
+ key,
+ label: "Books",
+ description: "Reference generated book chapters in chat.",
+ icon: BookOpen,
+ }
+ : SPACE_ITEMS.find((it) => it.key === key)!,
).filter(Boolean);
return (
diff --git a/web/components/knowledge/KbIndexVersionsSection.tsx b/web/components/knowledge/KbIndexVersionsSection.tsx
index 02954a4a2..e14b023a5 100644
--- a/web/components/knowledge/KbIndexVersionsSection.tsx
+++ b/web/components/knowledge/KbIndexVersionsSection.tsx
@@ -14,6 +14,7 @@ import {
} from "lucide-react";
import {
formatKnowledgeTimestamp,
+ kbCanReindex,
kbNeedsReindex,
resolveProgressPercent,
type IndexVersion,
@@ -54,9 +55,7 @@ export default function KbIndexVersionsSection({
}
};
- const showReindexCta =
- Boolean(kb.statistics?.needs_reindex) ||
- kb.statistics?.active_match === false;
+ const showReindexCta = kbCanReindex(kb);
return (
<div className="space-y-4">
@@ -78,7 +77,7 @@ export default function KbIndexVersionsSection({
</div>
</div>
- {showReindexCta && kb.statistics?.rag_initialized && (
+ {showReindexCta && (
<button
type="button"
onClick={handleReindex}
diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsx
index 1ca56bce1..378eddf7c 100644
--- a/web/context/UnifiedChatContext.tsx
+++ b/web/context/UnifiedChatContext.tsx
@@ -11,6 +11,9 @@ import React, {
useRef,
} from "react";
import {
+ LANGUAGE_EVENT,
+ LANGUAGE_STORAGE_KEY,
+ normalizeLanguage,
readStoredLanguage,
writeStoredActiveSessionId,
} from "@/context/app-shell-storage";
@@ -20,6 +23,10 @@ import { getSession, type SessionMessage } from "@/lib/session-api";
import { normalizeMarkdownForDisplay } from "@/lib/markdown-display";
import { normalizeMessageContent } from "@/lib/message-content";
import { shouldAppendEventContent } from "@/lib/stream";
+import {
+ normalizeBookReferences,
+ type BookReferencePayload,
+} from "@/lib/book-references";
type SessionRuntimeStatus =
| "idle"
@@ -52,6 +59,7 @@ export interface SendMessageOptions {
displayUserMessage?: boolean;
persistUserMessage?: boolean;
requestSnapshotOverride?: MessageRequestSnapshot;
+ bookReferences?: BookReferencePayload[];
}
export interface ChatState {
@@ -96,6 +104,7 @@ export interface MessageRequestSnapshot {
notebookReferences?: NotebookReferencePayload[];
historyReferences?: HistoryReferencePayload;
questionNotebookReferences?: QuestionNotebookReferencePayload;
+ bookReferences?: BookReferencePayload[];
skills?: string[];
memoryReferences?: MemoryReferencePayload;
}
@@ -602,6 +611,7 @@ function hydrateRequestSnapshot(
);
const skills = asStringArray(stored.skills);
const memoryReferences = asMemoryReferences(stored.memoryReferences);
+ const bookReferences = normalizeBookReferences(stored.bookReferences);
if (config && Object.keys(config).length) snapshot.config = config;
if (notebookReferences.length)
@@ -610,6 +620,7 @@ function hydrateRequestSnapshot(
if (questionNotebookReferences.length) {
snapshot.questionNotebookReferences = questionNotebookReferences;
}
+ if (bookReferences.length) snapshot.bookReferences = bookReferences;
if (skills.length) snapshot.skills = skills;
if (memoryReferences.length) snapshot.memoryReferences = memoryReferences;
return snapshot;
@@ -855,7 +866,10 @@ export function UnifiedChatProvider({
knowledgeBases: Array.isArray(session.preferences?.knowledge_bases)
? session.preferences.knowledge_bases
: [],
- language: session.preferences?.language || "en",
+ // The Settings language is global UI state. Historical sessions may
+ // have stale persisted preferences, so new turns follow the current
+ // app language rather than the language saved when the session began.
+ language: readStoredLanguage(),
});
if (activeTurn?.turn_id || activeTurn?.id) {
const key = session.session_id || session.id;
@@ -877,6 +891,28 @@ export function UnifiedChatProvider({
writeStoredActiveSessionId(current?.sessionId ?? null);
}, [state.selectedKey, state.sessions]);
+ useEffect(() => {
+ if (typeof window === "undefined") return;
+
+ const syncLanguage = (language: string | null | undefined) => {
+ dispatch({ type: "SET_LANGUAGE", lang: normalizeLanguage(language) });
+ };
+ const onLanguage = (event: Event) => {
+ const detail = (event as CustomEvent<{ language?: string }>).detail;
+ syncLanguage(detail?.language);
+ };
+ const onStorage = (event: StorageEvent) => {
+ if (event.key === LANGUAGE_STORAGE_KEY) syncLanguage(event.newValue);
+ };
+
+ window.addEventListener(LANGUAGE_EVENT, onLanguage);
+ window.addEventListener("storage", onStorage);
+ return () => {
+ window.removeEventListener(LANGUAGE_EVENT, onLanguage);
+ window.removeEventListener("storage", onStorage);
+ };
+ }, []);
+
// 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.
@@ -957,7 +993,8 @@ export function UnifiedChatProvider({
replaySnapshot?.enabledTools ?? session.enabledTools;
const effectiveKnowledgeBases =
replaySnapshot?.knowledgeBases ?? session.knowledgeBases;
- const effectiveLanguage = replaySnapshot?.language ?? session.language;
+ const effectiveLanguage =
+ replaySnapshot?.language ?? readStoredLanguage();
const researchSources = Array.isArray(config?.sources)
? config.sources.filter(
(value): value is string => typeof value === "string",
@@ -970,6 +1007,8 @@ export function UnifiedChatProvider({
const effectiveSkills = replaySnapshot?.skills ?? skills;
const effectiveMemoryReferences =
replaySnapshot?.memoryReferences ?? memoryReferences;
+ const effectiveBookReferences =
+ replaySnapshot?.bookReferences ?? options?.bookReferences;
const requestSnapshot: MessageRequestSnapshot = replaySnapshot ?? {
content,
capability: effectiveCapability,
@@ -987,6 +1026,9 @@ export function UnifiedChatProvider({
...(questionNotebookReferences?.length
? { questionNotebookReferences: [...questionNotebookReferences] }
: {}),
+ ...(effectiveBookReferences?.length
+ ? { bookReferences: effectiveBookReferences }
+ : {}),
...(effectiveSkills?.length ? { skills: [...effectiveSkills] } : {}),
...(effectiveMemoryReferences?.length
? { memoryReferences: [...effectiveMemoryReferences] }
@@ -1027,6 +1069,9 @@ export function UnifiedChatProvider({
...(questionNotebookReferences?.length
? { question_notebook_references: questionNotebookReferences }
: {}),
+ ...(effectiveBookReferences?.length
+ ? { book_references: effectiveBookReferences }
+ : {}),
...(effectiveSkills?.length ? { skills: effectiveSkills } : {}),
...(effectiveMemoryReferences?.length
? { memory_references: effectiveMemoryReferences }
@@ -1080,6 +1125,9 @@ export function UnifiedChatProvider({
sendThroughRunner(key, {
type: "regenerate",
session_id: session.sessionId,
+ overrides: {
+ language: readStoredLanguage(),
+ },
});
}, [sendThroughRunner]);
diff --git a/web/lib/book-api.ts b/web/lib/book-api.ts
index 407641fe3..513daa642 100644
--- a/web/lib/book-api.ts
+++ b/web/lib/book-api.ts
@@ -166,6 +166,18 @@ export const bookApi = {
body: JSON.stringify({ book_id, page_id, topic }),
}),
+ setPageChatSession: (book_id: string, page_id: string, session_id: string) =>
+ request<{ book: Book }>("/books/page-chat-session", {
+ method: "POST",
+ body: JSON.stringify({ book_id, page_id, session_id }),
+ }),
+
+ rebuild: (book_id: string, auto_compile = true) =>
+ request<{ pages: Page[] }>("/books/rebuild", {
+ method: "POST",
+ body: JSON.stringify({ book_id, auto_compile }),
+ }),
+
health: (book_id: string) =>
request<{
kb_drift: {
@@ -197,6 +209,22 @@ export const bookApi = {
}),
};
+export interface LegacyChatSession {
+ session_id: string;
+ messages?: Array<{ role: string; content: string }>;
+}
+
+export async function getLegacyChatSession(
+ session_id: string,
+): Promise<LegacyChatSession | null> {
+ const res = await fetch(
+ apiUrl(`/api/v1/chat/sessions/${encodeURIComponent(session_id)}`),
+ );
+ if (res.status === 404) return null;
+ if (!res.ok) throw new Error(`chat session ${session_id} → ${res.status}`);
+ return (await res.json()) as LegacyChatSession;
+}
+
// ── WebSocket helper ─────────────────────────────────────────────────
export type BookWsEvent = { type: string; [key: string]: unknown };
diff --git a/web/lib/book-references.ts b/web/lib/book-references.ts
new file mode 100644
index 000000000..1b6e18874
--- /dev/null
+++ b/web/lib/book-references.ts
@@ -0,0 +1,61 @@
+"use client";
+
+export interface SelectedBookPage {
+ bookId: string;
+ bookTitle: string;
+ pageId: string;
+ pageTitle: string;
+ chapterId?: string;
+ chapterTitle?: string;
+}
+
+export interface SelectedBookReference {
+ bookId: string;
+ bookTitle: string;
+ pages: SelectedBookPage[];
+}
+
+export interface BookReferencePayload {
+ book_id: string;
+ page_ids: string[];
+}
+
+export function selectedBooksToPayload(
+ refs: SelectedBookReference[],
+): BookReferencePayload[] {
+ return refs
+ .map((ref) => ({
+ book_id: ref.bookId,
+ page_ids: Array.from(new Set(ref.pages.map((page) => page.pageId))).filter(
+ Boolean,
+ ),
+ }))
+ .filter((ref) => ref.book_id && ref.page_ids.length > 0);
+}
+
+export function countSelectedBookPages(refs: SelectedBookReference[]): number {
+ return refs.reduce((total, ref) => total + ref.pages.length, 0);
+}
+
+export function normalizeBookReferences(value: unknown): BookReferencePayload[] {
+ if (!Array.isArray(value)) return [];
+ return value
+ .map((item) => {
+ const record: Record<string, unknown> =
+ item && typeof item === "object" ? (item as Record<string, unknown>) : {};
+ const bookId =
+ typeof record.book_id === "string"
+ ? record.book_id
+ : "";
+ const pageIds =
+ Array.isArray(record.page_ids)
+ ? record.page_ids.filter(
+ (pageId): pageId is string => typeof pageId === "string" && !!pageId,
+ )
+ : [];
+ return bookId && pageIds.length
+ ? { book_id: bookId, page_ids: Array.from(new Set(pageIds)) }
+ : null;
+ })
+ .filter((item): item is BookReferencePayload => item !== null);
+}
diff --git a/web/lib/book-types.ts b/web/lib/book-types.ts
index 3d5dc57f0..f73924a40 100644
--- a/web/lib/book-types.ts
+++ b/web/lib/book-types.ts
@@ -147,7 +147,9 @@ export interface Book {
chapter_count: number;
created_at: number;
updated_at: number;
- metadata: Record<string, unknown>;
+ metadata: Record<string, unknown> & {
+ page_chat_sessions?: Record<string, string>;
+ };
}
export interface Progress {
diff --git a/web/lib/knowledge-helpers.ts b/web/lib/knowledge-helpers.ts
index 27ea87928..295102759 100644
--- a/web/lib/knowledge-helpers.ts
+++ b/web/lib/knowledge-helpers.ts
@@ -1,5 +1,11 @@
import type { TFunction } from "i18next";
-import type { KnowledgeUploadPolicy } from "@/lib/knowledge-api";
+
+export interface KnowledgeUploadPolicy {
+ extensions: string[];
+ accept: string;
+ max_file_size_bytes: number;
+ max_pdf_size_bytes: number;
+}
export const DEFAULT_UPLOAD_POLICY: KnowledgeUploadPolicy = {
extensions: [],
@@ -123,6 +129,20 @@ export const kbNeedsReindex = (kb: KnowledgeBase): boolean =>
export const kbIsUploadable = (kb: KnowledgeBase): boolean =>
resolveKbStatus(kb) === "ready" && !kbNeedsReindex(kb);
+export const kbCanReindex = (kb: KnowledgeBase): boolean => {
+ const status = resolveKbStatus(kb);
+ const hasSourceFiles =
+ typeof kb.statistics?.raw_documents === "number"
+ ? kb.statistics.raw_documents > 0
+ : true;
+ if (!hasSourceFiles) return false;
+ if (status === "error") return true;
+ return (
+ Boolean(kb.statistics?.needs_reindex) ||
+ kb.statistics?.active_match === false
+ );
+};
+
const LIVE_PROGRESS_STAGES = new Set([
"initializing",
"starting",
diff --git a/web/lib/unified-ws.ts b/web/lib/unified-ws.ts
index 9bf7fa38b..33845562e 100644
--- a/web/lib/unified-ws.ts
+++ b/web/lib/unified-ws.ts
@@ -65,6 +65,10 @@ export interface StartTurnMessage {
}[];
history_references?: string[];
question_notebook_references?: number[];
+ book_references?: {
+ book_id: string;
+ page_ids: string[];
+ }[];
skills?: string[];
}
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 9c1470998..5d85a6809 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -367,10 +367,12 @@
"Selected {n} items": "Selected {n} items",
"Import Selected": "Import Selected",
"Backend Service": "Backend Service",
+ "Backend status": "Backend status",
"LLM Model": "LLM Model",
"Embeddings": "Embeddings",
"TTS Model": "TTS Model",
"Checking...": "Checking...",
+ "Checking": "Checking",
"Online": "Online",
"Offline": "Offline",
"Configured": "Configured",
@@ -1161,6 +1163,13 @@
"Clear history": "Clear history",
"No logs captured.": "No logs captured.",
"Active": "Active",
+ "Pending": "Pending",
+ "No profile": "No profile",
+ "No provider": "No provider",
+ "No model selected": "No model selected",
+ "Active provider": "Active provider",
+ "Active model": "Active model",
+ "{{count}} models": "{{count}} models",
"Stale": "Stale",
"Legacy": "Legacy",
"Active version": "Active version",
@@ -1298,5 +1307,263 @@
"Inject the learner profile (preferences, goals, background).": "Inject the learner profile (preferences, goals, background).",
"1 memory artifact selected": "1 memory artifact selected",
"{{n}} memory artifacts selected": "{{n}} memory artifacts selected",
- "Use Selected Memory ({{n}})": "Use Selected Memory ({{n}})"
+ "Use Selected Memory ({{n}})": "Use Selected Memory ({{n}})",
+ "Please use the selected context to help with this request.": "Please use the selected context to help with this request.",
+ "Generate a math animation from the attached reference image(s).": "Generate a math animation from the attached reference image(s).",
+ "Please analyze the attached image(s).": "Please analyze the attached image(s).",
+ "Book Reference": "Book Reference",
+ "Select Book Chapters": "Select Book Chapters",
+ "Choose generated book chapters to ground the next answer.": "Choose generated book chapters to ground the next answer.",
+ "No books found.": "No books found.",
+ "Select a book to view chapters.": "Select a book to view chapters.",
+ "Unassigned pages": "Unassigned pages",
+ "pages": "pages",
+ "{{count}} chapters selected": "{{count}} chapters selected",
+ "No chapters selected": "No chapters selected",
+ "Books": "Books",
+ "Generate, browse and study your AI-authored books.": "Generate, browse and study your AI-authored books.",
+ "Search books": "Search books",
+ "New book": "New book",
+ "Total books": "Total books",
+ "In progress": "In progress",
+ "Chapters": "Chapters",
+ "My library": "My library",
+ "{{shown}} of {{total}} books": "{{shown}} of {{total}} books",
+ "matching “{{query}}”": "matching “{{query}}”",
+ "Loading books…": "Loading books…",
+ "No books match “{{query}}”.": "No books match “{{query}}”.",
+ "Delete book": "Delete book",
+ "Untitled book": "Untitled book",
+ "No description yet. Open the book to view its outline.": "No description yet. Open the book to view its outline.",
+ "{{count}} ch": "{{count}} ch",
+ "{{count}} pages": "{{count}} pages",
+ "just now": "just now",
+ "{{count}}m ago": "{{count}}m ago",
+ "{{count}}h ago": "{{count}}h ago",
+ "{{count}}d ago": "{{count}}d ago",
+ "{{count}}mo ago": "{{count}}mo ago",
+ "{{count}}y ago": "{{count}}y ago",
+ "No books yet": "No books yet",
+ "Create your first AI-generated book from a knowledge base, chat selections or simply a topic.": "Create your first AI-generated book from a knowledge base, chat selections or simply a topic.",
+ "Create a new book": "Create a new book",
+ "Describe what you want to learn, then pick the knowledge sources to fuse into a structured, interactive book.": "Describe what you want to learn, then pick the knowledge sources to fuse into a structured, interactive book.",
+ "Inputs": "Inputs",
+ "Configure inputs": "Configure inputs",
+ "No knowledge sources selected": "No knowledge sources selected",
+ "Learning intent": "Learning intent",
+ "e.g. Build intuition for transformer attention with derivations and exercises.": "e.g. Build intuition for transformer attention with derivations and exercises.",
+ "Knowledge sources": "Knowledge sources",
+ "{{count}} selected": "{{count}} selected",
+ "Chats": "Chats",
+ "{{count}} KB": "{{count}} KB",
+ "{{count}} notebook record": "{{count}} notebook record",
+ "{{count}} notebook records": "{{count}} notebook records",
+ "{{count}} quiz item": "{{count}} quiz item",
+ "{{count}} quiz items": "{{count}} quiz items",
+ "{{count}} chat item": "{{count}} chat item",
+ "{{count}} chat items": "{{count}} chat items",
+ "No knowledge bases yet. Create one in the Knowledge page first.": "No knowledge bases yet. Create one in the Knowledge page first.",
+ "No notebooks yet. Save chat outputs into a notebook first.": "No notebooks yet. Save chat outputs into a notebook first.",
+ "record": "record",
+ "entry": "entry",
+ "entries": "entries",
+ "message": "message",
+ "{{selected}} of {{total}}": "{{selected}} of {{total}}",
+ "(untitled)": "(untitled)",
+ "No quiz categories yet. Bookmark questions into a category first.": "No quiz categories yet. Bookmark questions into a category first.",
+ "(no question)": "(no question)",
+ "your: {{answer}}": "your: {{answer}}",
+ "no attempt": "no attempt",
+ "correct: {{answer}}": "correct: {{answer}}",
+ "No chat sessions yet.": "No chat sessions yet.",
+ "(untitled chat)": "(untitled chat)",
+ "Generate proposal": "Generate proposal",
+ "Proposal": "Proposal",
+ "Edit anything below, then confirm to generate the chapter spine.": "Edit anything below, then confirm to generate the chapter spine.",
+ "Confirm proposal & build spine": "Confirm proposal & build spine",
+ "Loading…": "Loading…",
+ "Nothing inside.": "Nothing inside.",
+ "Scope": "Scope",
+ "Target level": "Target level",
+ "Estimated chapters": "Estimated chapters",
+ "Knowledge bases used": "Knowledge bases used",
+ "No knowledge bases selected. The book will rely on general knowledge.": "No knowledge bases selected. The book will rely on general knowledge.",
+ "Delete this book? This cannot be undone.": "Delete this book? This cannot be undone.",
+ "Rebuild this book using the current chapter structure? Existing generated pages will be replaced.": "Rebuild this book using the current chapter structure? Existing generated pages will be replaced.",
+ "Delete this {{type}} block?": "Delete this {{type}} block?",
+ "Loading spine…": "Loading spine…",
+ "All books": "All books",
+ "Expand chapters": "Expand chapters",
+ "Collapse chapters": "Collapse chapters",
+ "{{count}} chapters": "{{count}} chapters",
+ "Rebuild book": "Rebuild book",
+ "Pages will appear here once the spine is confirmed.": "Pages will appear here once the spine is confirmed.",
+ "Page Chat": "Page Chat",
+ "Drag to resize": "Drag to resize",
+ "Ask a question about this page. Context (book + chapter) is sent automatically.": "Ask a question about this page. Context (book + chapter) is sent automatically.",
+ "Ask about this page…": "Ask about this page…",
+ "Book": "Book",
+ "Objectives": "Objectives",
+ "error": "error",
+ "Select a chapter to start reading.": "Select a chapter to start reading.",
+ "Expand header": "Expand header",
+ "Collapse header": "Collapse header",
+ "Untitled chapter": "Untitled chapter",
+ "Force regenerate": "Force regenerate",
+ "{{count}} block failed": "{{count}} block failed",
+ "{{count}} blocks failed": "{{count}} blocks failed",
+ "Regenerate page": "Regenerate page",
+ "Retry block": "Retry block",
+ "Compiling page…": "Compiling page…",
+ "This page has no blocks yet.": "This page has no blocks yet.",
+ "Insert block": "Insert block",
+ "Your knowledge bases changed since this book was generated.": "Your knowledge bases changed since this book was generated.",
+ "Newly added": "Newly added",
+ "Removed": "Removed",
+ "{{count}} previously-compiled page may be out of date.": "{{count}} previously-compiled page may be out of date.",
+ "{{count}} previously-compiled pages may be out of date.": "{{count}} previously-compiled pages may be out of date.",
+ "Recompile first stale page": "Recompile first stale page",
+ "{{count}} block generation failure recorded.": "{{count}} block generation failure recorded.",
+ "{{count}} block generation failures recorded.": "{{count}} block generation failures recorded.",
+ "Recurring issue": "Recurring issue",
+ "Recurring issues": "Recurring issues",
+ "unknown failure": "unknown failure",
+ "Mark the current KB state as the new baseline (won't recompile pages — use the recompile button above for that).": "Mark the current KB state as the new baseline (won't recompile pages — use the recompile button above for that).",
+ "Mark as seen": "Mark as seen",
+ "Generating book": "Generating book",
+ "queries": "queries",
+ "chunks": "chunks",
+ "chapters": "chapters",
+ "concepts": "concepts",
+ "blocks ready": "blocks ready",
+ "block errors": "block errors",
+ "Source sweep done — {{queries}} queries, {{chunks}} chunks": "Source sweep done — {{queries}} queries, {{chunks}} chunks",
+ "Spine ready — {{chapters}} chapters · {{concepts}} concepts": "Spine ready — {{chapters}} chapters · {{concepts}} concepts",
+ "{{queries}} queries · {{chunks}} chunks": "{{queries}} queries · {{chunks}} chunks",
+ "{{rounds}} round · {{issues}} issue": "{{rounds}} round · {{issues}} issue",
+ "{{rounds}} round · {{issues}} issues": "{{rounds}} round · {{issues}} issues",
+ "{{rounds}} rounds · {{issues}} issue": "{{rounds}} rounds · {{issues}} issue",
+ "{{rounds}} rounds · {{issues}} issues": "{{rounds}} rounds · {{issues}} issues",
+ "{{rounds}} round · {{chapters}} chapter": "{{rounds}} round · {{chapters}} chapter",
+ "{{rounds}} round · {{chapters}} chapters": "{{rounds}} round · {{chapters}} chapters",
+ "{{rounds}} rounds · {{chapters}} chapter": "{{rounds}} rounds · {{chapters}} chapter",
+ "{{rounds}} rounds · {{chapters}} chapters": "{{rounds}} rounds · {{chapters}} chapters",
+ "{{chapters}} chapters · {{concepts}} concepts": "{{chapters}} chapters · {{concepts}} concepts",
+ "{{pages}} page · {{blocks}} blocks": "{{pages}} page · {{blocks}} blocks",
+ "{{pages}} pages · {{blocks}} blocks": "{{pages}} pages · {{blocks}} blocks",
+ "Proposal ready": "Proposal ready",
+ "Book compilation complete": "Book compilation complete",
+ "Ideation": "Ideation",
+ "Source sweep": "Source sweep",
+ "Synthesis": "Synthesis",
+ "Critique": "Critique",
+ "Overview chapter": "Overview chapter",
+ "Compilation": "Compilation",
+ "Drafting the proposal from your inputs.": "Drafting the proposal from your inputs.",
+ "Parallel multi-query retrieval across your KBs.": "Parallel multi-query retrieval across your KBs.",
+ "Spine + concept graph (draft → revise).": "Spine + concept graph (draft → revise).",
+ "Self-review rounds tightening the spine.": "Self-review rounds tightening the spine.",
+ "Auto-built table of contents + concept map.": "Auto-built table of contents + concept map.",
+ "Per-page block planning + generation.": "Per-page block planning + generation.",
+ "pending": "pending",
+ "running": "running",
+ "completed": "completed",
+ "draft": "draft",
+ "spine_ready": "outline ready",
+ "archived": "archived",
+ "Queued": "Queued",
+ "Compiling": "Compiling",
+ "Partial": "Partial",
+ "Move up": "Move up",
+ "Move down": "Move down",
+ "Change type": "Change type",
+ "Generating {{type}}…": "Generating {{type}}…",
+ "{{type}} block failed": "{{type}} block failed",
+ "not retryable": "not retryable",
+ "(Animation payload is empty)": "(Animation payload is empty)",
+ "Animation frame": "Animation frame",
+ "Open in new tab": "Open in new tab",
+ "Download video": "Download video",
+ "(Figure payload is empty)": "(Figure payload is empty)",
+ "(Interactive payload is empty)": "(Interactive payload is empty)",
+ "Flash Cards": "Flash Cards",
+ "Answer": "Answer",
+ "Hint": "Hint",
+ "Prev": "Prev",
+ "Flip": "Flip",
+ "No quiz questions generated.": "No quiz questions generated.",
+ "Quick Check": "Quick Check",
+ "(missing)": "(missing)",
+ "Think about your answer, then reveal the solution.": "Think about your answer, then reveal the solution.",
+ "Open response — click reveal to see the model answer.": "Open response — click reveal to see the model answer.",
+ "Hide answer": "Hide answer",
+ "Reveal answer": "Reveal answer",
+ "Section focus": "Section focus",
+ "Key takeaway:": "Key takeaway:",
+ "Coming in Phase 2 – {{type}} block will appear here once the generator is wired.": "Coming in Phase 2 – {{type}} block will appear here once the generator is wired.",
+ "Go Deeper": "Go Deeper",
+ "Linked sub-page already exists.": "Linked sub-page already exists.",
+ "Your note": "Your note",
+ "Empty note – start writing your own annotation.": "Empty note – start writing your own annotation.",
+ "On this page": "On this page",
+ "Hide outline": "Hide outline",
+ "Show outline": "Show outline",
+ "Chapter index": "Chapter index",
+ "(No chapters yet)": "(No chapters yet)",
+ "Chapter map · {{chapters}} chapters · {{dependencies}} dependencies": "Chapter map · {{chapters}} chapters · {{dependencies}} dependencies",
+ "Concept map · {{concepts}} concepts · {{relations}} relations": "Concept map · {{concepts}} concepts · {{relations}} relations",
+ "Review the chapter spine": "Review the chapter spine",
+ "Reorder, rename, or remove chapters before the book starts compiling.": "Reorder, rename, or remove chapters before the book starts compiling.",
+ "New chapter": "New chapter",
+ "Content type": "Content type",
+ "Hint that drives the chapter's block plan (text length, whether to include diagrams / quizzes / code, etc.).": "Hint that drives the chapter's block plan (text length, whether to include diagrams / quizzes / code, etc.).",
+ "Hint for the architect about what blocks to plan.": "Hint for the architect about what blocks to plan.",
+ "Optional one-line description": "Optional one-line description",
+ "Learning objectives (one per line)": "Learning objectives (one per line)",
+ "Add chapter": "Add chapter",
+ "Confirm spine & start compiling": "Confirm spine & start compiling",
+ "Theory": "Theory",
+ "Derivation": "Derivation",
+ "Practice": "Practice",
+ "Concept": "Concept",
+ "Long-form explanation with diagrams + flash cards + a quiz.": "Long-form explanation with diagrams + flash cards + a quiz.",
+ "Step-by-step derivation, often with animation + verifying code.": "Step-by-step derivation, often with animation + verifying code.",
+ "Narrative + timeline + period image, ends with a recap quiz.": "Narrative + timeline + period image, ends with a recap quiz.",
+ "Quiz-heavy chapter with a runnable code scaffold + explanation.": "Quiz-heavy chapter with a runnable code scaffold + explanation.",
+ "Definition + figure + flash cards + common-pitfall callout.": "Definition + figure + flash cards + common-pitfall callout.",
+ "Text": "Text",
+ "Section": "Section",
+ "Callout": "Callout",
+ "Quiz": "Quiz",
+ "Note": "Note",
+ "Figure": "Figure",
+ "Interactive": "Interactive",
+ "Animation": "Animation",
+ "Timeline": "Timeline",
+ "Deep Dive": "Deep Dive",
+ "Code Sandbox": "Code Sandbox",
+ "text": "text",
+ "section": "section",
+ "callout": "callout",
+ "quiz": "quiz",
+ "user_note": "user note",
+ "figure": "figure",
+ "interactive": "interactive",
+ "animation": "animation",
+ "code": "code",
+ "timeline": "timeline",
+ "flash_cards": "flash cards",
+ "deep_dive": "deep dive",
+ "concept_graph": "concept graph",
+ "compiling": "compiling",
+ "ready": "ready",
+ "Connection failed. Please try again.": "Connection failed. Please try again.",
+ "Unsupported file type.": "Unsupported file type.",
+ "File is too large ({{size}}).": "File is too large ({{size}}).",
+ "Attachments exceed the total upload limit.": "Attachments exceed the total upload limit.",
+ "Please analyze the attached image(s) using this chapter as context.": "Please analyze the attached image(s) using this chapter as context.",
+ "Please use the attached file(s) and this chapter as context.": "Please use the attached file(s) and this chapter as context.",
+ "Context": "Context",
+ "Ask a question about this page. The current chapter content is sent to the assistant automatically.": "Ask a question about this page. The current chapter content is sent to the assistant automatically.",
+ "Ask about this page...": "Ask about this page..."
}
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 2b341ba3d..30d80988b 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -367,10 +367,12 @@
"Selected {n} items": "已选择 {n} 项",
"Import Selected": "导入已选",
"Backend Service": "后端服务",
+ "Backend status": "后端状态",
"LLM Model": "LLM 模型",
"Embeddings": "向量模型",
"TTS Model": "TTS 模型",
"Checking...": "检测中…",
+ "Checking": "检测中",
"Online": "在线",
"Offline": "离线",
"Configured": "已配置",
@@ -1161,6 +1163,13 @@
"Clear history": "清空历史",
"No logs captured.": "没有日志记录。",
"Active": "已激活",
+ "Pending": "待应用",
+ "No profile": "无配置档",
+ "No provider": "无提供商",
+ "No model selected": "未选择模型",
+ "Active provider": "当前提供商",
+ "Active model": "当前模型",
+ "{{count}} models": "{{count}} 个模型",
"Stale": "已失效",
"Legacy": "旧版",
"Active version": "当前激活版本",
@@ -1298,5 +1307,263 @@
"Inject the learner profile (preferences, goals, background).": "注入学习者画像(偏好、目标、背景)。",
"1 memory artifact selected": "已选 1 项记忆",
"{{n}} memory artifacts selected": "已选 {{n}} 项记忆",
- "Use Selected Memory ({{n}})": "使用所选记忆({{n}})"
+ "Use Selected Memory ({{n}})": "使用所选记忆({{n}})",
+ "Please use the selected context to help with this request.": "请使用所选上下文帮助完成这次请求。",
+ "Generate a math animation from the attached reference image(s).": "请根据附件参考图片生成数学动画。",
+ "Please analyze the attached image(s).": "请分析附件中的图片。",
+ "Book Reference": "书籍引用",
+ "Select Book Chapters": "选择书籍章节",
+ "Choose generated book chapters to ground the next answer.": "选择已生成的书籍章节,作为下一次回答的依据。",
+ "No books found.": "未找到书籍。",
+ "Select a book to view chapters.": "选择一本书查看章节。",
+ "Unassigned pages": "未分配页面",
+ "pages": "页",
+ "{{count}} chapters selected": "已选 {{count}} 个章节",
+ "No chapters selected": "尚未选择章节",
+ "Books": "书籍",
+ "Generate, browse and study your AI-authored books.": "生成、浏览并学习你的 AI 编写书籍。",
+ "Search books": "搜索书籍",
+ "New book": "新建书籍",
+ "Total books": "书籍总数",
+ "In progress": "进行中",
+ "Chapters": "章节",
+ "My library": "我的书库",
+ "{{shown}} of {{total}} books": "共 {{total}} 本,显示 {{shown}} 本",
+ "matching “{{query}}”": "匹配“{{query}}”",
+ "Loading books…": "正在加载书籍…",
+ "No books match “{{query}}”.": "没有书籍匹配“{{query}}”。",
+ "Delete book": "删除书籍",
+ "Untitled book": "未命名书籍",
+ "No description yet. Open the book to view its outline.": "暂无描述。打开书籍查看大纲。",
+ "{{count}} ch": "{{count}} 章",
+ "{{count}} pages": "{{count}} 页",
+ "just now": "刚刚",
+ "{{count}}m ago": "{{count}} 分钟前",
+ "{{count}}h ago": "{{count}} 小时前",
+ "{{count}}d ago": "{{count}} 天前",
+ "{{count}}mo ago": "{{count}} 个月前",
+ "{{count}}y ago": "{{count}} 年前",
+ "No books yet": "暂无书籍",
+ "Create your first AI-generated book from a knowledge base, chat selections or simply a topic.": "从知识库、聊天片段,或一个主题开始创建你的第一本 AI 书籍。",
+ "Create a new book": "创建新书",
+ "Describe what you want to learn, then pick the knowledge sources to fuse into a structured, interactive book.": "描述你想学习的内容,然后选择知识来源,融合成一本结构化、可交互的书。",
+ "Inputs": "输入",
+ "Configure inputs": "配置输入",
+ "No knowledge sources selected": "尚未选择知识来源",
+ "Learning intent": "学习意图",
+ "e.g. Build intuition for transformer attention with derivations and exercises.": "例如:通过推导和练习建立对 Transformer 注意力机制的直觉。",
+ "Knowledge sources": "知识来源",
+ "{{count}} selected": "已选择 {{count}} 项",
+ "Chats": "聊天",
+ "{{count}} KB": "{{count}} 个知识库",
+ "{{count}} notebook record": "{{count}} 条笔记记录",
+ "{{count}} notebook records": "{{count}} 条笔记记录",
+ "{{count}} quiz item": "{{count}} 道题目",
+ "{{count}} quiz items": "{{count}} 道题目",
+ "{{count}} chat item": "{{count}} 条聊天内容",
+ "{{count}} chat items": "{{count}} 条聊天内容",
+ "No knowledge bases yet. Create one in the Knowledge page first.": "暂无知识库。请先在“知识”页面创建一个。",
+ "No notebooks yet. Save chat outputs into a notebook first.": "暂无笔记本。请先将聊天输出保存到笔记本。",
+ "record": "条记录",
+ "entry": "条目",
+ "entries": "条目",
+ "message": "条消息",
+ "{{selected}} of {{total}}": "已选 {{selected}} / {{total}}",
+ "(untitled)": "(未命名)",
+ "No quiz categories yet. Bookmark questions into a category first.": "暂无题目分类。请先将题目收藏到某个分类。",
+ "(no question)": "(无题干)",
+ "your: {{answer}}": "你的答案:{{answer}}",
+ "no attempt": "未作答",
+ "correct: {{answer}}": "正确答案:{{answer}}",
+ "No chat sessions yet.": "暂无聊天会话。",
+ "(untitled chat)": "(未命名聊天)",
+ "Generate proposal": "生成方案",
+ "Proposal": "方案",
+ "Edit anything below, then confirm to generate the chapter spine.": "可编辑下方内容,确认后生成章节主线。",
+ "Confirm proposal & build spine": "确认方案并生成主线",
+ "Loading…": "加载中…",
+ "Nothing inside.": "里面暂无内容。",
+ "Scope": "范围",
+ "Target level": "目标水平",
+ "Estimated chapters": "预计章节数",
+ "Knowledge bases used": "使用的知识库",
+ "No knowledge bases selected. The book will rely on general knowledge.": "未选择知识库。本书将依赖通用知识生成。",
+ "Delete this book? This cannot be undone.": "确定删除这本书吗?此操作无法撤销。",
+ "Rebuild this book using the current chapter structure? Existing generated pages will be replaced.": "使用当前章节结构重建这本书吗?现有生成页面将被替换。",
+ "Delete this {{type}} block?": "确定删除这个 {{type}} 内容块吗?",
+ "Loading spine…": "正在加载主线…",
+ "All books": "全部书籍",
+ "Expand chapters": "展开章节",
+ "Collapse chapters": "折叠章节",
+ "{{count}} chapters": "{{count}} 章",
+ "Rebuild book": "重建书籍",
+ "Pages will appear here once the spine is confirmed.": "确认章节主线后,页面会出现在这里。",
+ "Page Chat": "页面问答",
+ "Drag to resize": "拖动调整宽度",
+ "Ask a question about this page. Context (book + chapter) is sent automatically.": "可以询问本页内容。系统会自动发送书籍与章节上下文。",
+ "Ask about this page…": "询问本页内容…",
+ "Book": "书籍",
+ "Objectives": "学习目标",
+ "error": "错误",
+ "Select a chapter to start reading.": "选择一个章节开始阅读。",
+ "Expand header": "展开标题栏",
+ "Collapse header": "折叠标题栏",
+ "Untitled chapter": "未命名章节",
+ "Force regenerate": "强制重新生成",
+ "{{count}} block failed": "{{count}} 个内容块生成失败",
+ "{{count}} blocks failed": "{{count}} 个内容块生成失败",
+ "Regenerate page": "重新生成本页",
+ "Retry block": "重试该块",
+ "Compiling page…": "正在编译页面…",
+ "This page has no blocks yet.": "此页面还没有内容块。",
+ "Insert block": "插入内容块",
+ "Your knowledge bases changed since this book was generated.": "自本书生成后,你的知识库发生了变化。",
+ "Newly added": "新增",
+ "Removed": "已移除",
+ "{{count}} previously-compiled page may be out of date.": "{{count}} 个已编译页面可能已过期。",
+ "{{count}} previously-compiled pages may be out of date.": "{{count}} 个已编译页面可能已过期。",
+ "Recompile first stale page": "重新编译第一个过期页面",
+ "{{count}} block generation failure recorded.": "记录到 {{count}} 次内容块生成失败。",
+ "{{count}} block generation failures recorded.": "记录到 {{count}} 次内容块生成失败。",
+ "Recurring issue": "重复问题",
+ "Recurring issues": "重复问题",
+ "unknown failure": "未知失败",
+ "Mark the current KB state as the new baseline (won't recompile pages — use the recompile button above for that).": "将当前知识库状态标记为新的基线(不会重新编译页面;如需重编译请使用上方按钮)。",
+ "Mark as seen": "标记为已查看",
+ "Generating book": "正在生成书籍",
+ "queries": "次查询",
+ "chunks": "个片段",
+ "chapters": "章",
+ "concepts": "个概念",
+ "blocks ready": "个内容块就绪",
+ "block errors": "个内容块错误",
+ "Source sweep done — {{queries}} queries, {{chunks}} chunks": "资料扫描完成:{{queries}} 次查询,{{chunks}} 个片段",
+ "Spine ready — {{chapters}} chapters · {{concepts}} concepts": "章节主线就绪:{{chapters}} 章 · {{concepts}} 个概念",
+ "{{queries}} queries · {{chunks}} chunks": "{{queries}} 次查询 · {{chunks}} 个片段",
+ "{{rounds}} round · {{issues}} issue": "{{rounds}} 轮 · {{issues}} 个问题",
+ "{{rounds}} round · {{issues}} issues": "{{rounds}} 轮 · {{issues}} 个问题",
+ "{{rounds}} rounds · {{issues}} issue": "{{rounds}} 轮 · {{issues}} 个问题",
+ "{{rounds}} rounds · {{issues}} issues": "{{rounds}} 轮 · {{issues}} 个问题",
+ "{{rounds}} round · {{chapters}} chapter": "{{rounds}} 轮 · {{chapters}} 章",
+ "{{rounds}} round · {{chapters}} chapters": "{{rounds}} 轮 · {{chapters}} 章",
+ "{{rounds}} rounds · {{chapters}} chapter": "{{rounds}} 轮 · {{chapters}} 章",
+ "{{rounds}} rounds · {{chapters}} chapters": "{{rounds}} 轮 · {{chapters}} 章",
+ "{{chapters}} chapters · {{concepts}} concepts": "{{chapters}} 章 · {{concepts}} 个概念",
+ "{{pages}} page · {{blocks}} blocks": "{{pages}} 页 · {{blocks}} 个内容块",
+ "{{pages}} pages · {{blocks}} blocks": "{{pages}} 页 · {{blocks}} 个内容块",
+ "Proposal ready": "方案已就绪",
+ "Book compilation complete": "书籍编译完成",
+ "Ideation": "构思",
+ "Source sweep": "资料扫描",
+ "Synthesis": "综合",
+ "Critique": "自检",
+ "Overview chapter": "导览章节",
+ "Compilation": "编译",
+ "Drafting the proposal from your inputs.": "根据你的输入起草方案。",
+ "Parallel multi-query retrieval across your KBs.": "在知识库中并行执行多查询检索。",
+ "Spine + concept graph (draft → revise).": "章节主线与概念图(草稿 → 修订)。",
+ "Self-review rounds tightening the spine.": "通过自检轮次优化章节主线。",
+ "Auto-built table of contents + concept map.": "自动构建目录与概念图。",
+ "Per-page block planning + generation.": "逐页规划并生成内容块。",
+ "pending": "待处理",
+ "running": "运行中",
+ "completed": "已完成",
+ "draft": "草稿",
+ "spine_ready": "大纲就绪",
+ "compiling": "编译中",
+ "ready": "就绪",
+ "archived": "已归档",
+ "Queued": "排队中",
+ "Compiling": "编译中",
+ "Partial": "部分完成",
+ "Move up": "上移",
+ "Move down": "下移",
+ "Change type": "更改类型",
+ "Generating {{type}}…": "正在生成{{type}}…",
+ "{{type}} block failed": "{{type}} 内容块生成失败",
+ "not retryable": "不可重试",
+ "(Animation payload is empty)": "(动画内容为空)",
+ "Animation frame": "动画帧",
+ "Open in new tab": "在新标签页打开",
+ "Download video": "下载视频",
+ "(Figure payload is empty)": "(图示内容为空)",
+ "(Interactive payload is empty)": "(交互内容为空)",
+ "Flash Cards": "闪卡",
+ "Answer": "答案",
+ "Hint": "提示",
+ "Prev": "上一张",
+ "Flip": "翻转",
+ "No quiz questions generated.": "未生成测验题。",
+ "Quick Check": "快速检查",
+ "(missing)": "(缺失)",
+ "Think about your answer, then reveal the solution.": "先思考你的答案,然后查看解答。",
+ "Open response — click reveal to see the model answer.": "开放题回答——点击显示查看参考答案。",
+ "Hide answer": "隐藏答案",
+ "Reveal answer": "显示答案",
+ "Section focus": "章节重点",
+ "Key takeaway:": "关键收获:",
+ "Coming in Phase 2 – {{type}} block will appear here once the generator is wired.": "第二阶段上线后,{{type}} 内容块会显示在这里。",
+ "Go Deeper": "深入学习",
+ "Linked sub-page already exists.": "关联子页面已存在。",
+ "Your note": "你的笔记",
+ "Empty note – start writing your own annotation.": "空笔记——开始写下你的批注吧。",
+ "On this page": "本页内容",
+ "Hide outline": "隐藏目录",
+ "Show outline": "显示目录",
+ "Chapter index": "章节索引",
+ "(No chapters yet)": "(暂无章节)",
+ "Chapter map · {{chapters}} chapters · {{dependencies}} dependencies": "章节图谱 · {{chapters}} 章 · {{dependencies}} 条依赖",
+ "Concept map · {{concepts}} concepts · {{relations}} relations": "概念图 · {{concepts}} 个概念 · {{relations}} 条关系",
+ "Review the chapter spine": "检查章节主线",
+ "Reorder, rename, or remove chapters before the book starts compiling.": "在书籍开始编译前,可调整顺序、重命名或删除章节。",
+ "New chapter": "新章节",
+ "Content type": "内容类型",
+ "Hint that drives the chapter's block plan (text length, whether to include diagrams / quizzes / code, etc.).": "用于指导章节内容块规划的提示(文本长度、是否包含图示/测验/代码等)。",
+ "Hint for the architect about what blocks to plan.": "给章节架构器的内容块规划提示。",
+ "Optional one-line description": "可选的一行描述",
+ "Learning objectives (one per line)": "学习目标(每行一个)",
+ "Add chapter": "添加章节",
+ "Confirm spine & start compiling": "确认主线并开始编译",
+ "Theory": "理论",
+ "Derivation": "推导",
+ "Practice": "练习",
+ "Concept": "概念",
+ "Long-form explanation with diagrams + flash cards + a quiz.": "长篇解释,包含图示、闪卡和测验。",
+ "Step-by-step derivation, often with animation + verifying code.": "分步推导,通常包含动画和验证代码。",
+ "Narrative + timeline + period image, ends with a recap quiz.": "叙事、时间线与时期图示,并以回顾测验收尾。",
+ "Quiz-heavy chapter with a runnable code scaffold + explanation.": "以测验为主,包含可运行代码脚手架和解释。",
+ "Definition + figure + flash cards + common-pitfall callout.": "定义、图示、闪卡与常见误区提示。",
+ "Text": "文本",
+ "Section": "章节",
+ "Callout": "提示",
+ "Quiz": "测验",
+ "Note": "笔记",
+ "Figure": "图示",
+ "Interactive": "交互",
+ "Animation": "动画",
+ "Timeline": "时间线",
+ "Deep Dive": "深入学习",
+ "Code Sandbox": "代码沙盒",
+ "text": "文本",
+ "section": "章节",
+ "callout": "提示",
+ "quiz": "测验",
+ "user_note": "用户笔记",
+ "figure": "图示",
+ "interactive": "交互",
+ "animation": "动画",
+ "code": "代码",
+ "timeline": "时间线",
+ "flash_cards": "闪卡",
+ "deep_dive": "深入学习",
+ "concept_graph": "概念图",
+ "Connection failed. Please try again.": "连接失败,请重试。",
+ "Unsupported file type.": "不支持的文件类型。",
+ "File is too large ({{size}}).": "文件过大({{size}})。",
+ "Attachments exceed the total upload limit.": "附件超过总上传限制。",
+ "Please analyze the attached image(s) using this chapter as context.": "请结合本章节上下文分析附件中的图片。",
+ "Please use the attached file(s) and this chapter as context.": "请结合附件文件和本章节上下文回答。",
+ "Context": "上下文",
+ "Ask a question about this page. The current chapter content is sent to the assistant automatically.": "可以询问本页内容。当前章节内容会自动发送给助手。",
+ "Ask about this page...": "询问本页内容…"
}
diff --git a/web/next-env.d.ts b/web/next-env.d.ts
index c4b7818fb..9edff1c7c 100644
--- a/web/next-env.d.ts
+++ b/web/next-env.d.ts
@@ -1,6 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
-import "./.next/dev/types/routes.d.ts";
+import "./.next/types/routes.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
diff --git a/web/tests/knowledge-helpers.test.ts b/web/tests/knowledge-helpers.test.ts
new file mode 100644
index 000000000..2809d289c
--- /dev/null
+++ b/web/tests/knowledge-helpers.test.ts
@@ -0,0 +1,52 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import { kbCanReindex, type KnowledgeBase } from "../lib/knowledge-helpers";
+
+function kb(overrides: Partial<KnowledgeBase>): KnowledgeBase {
+ return {
+ name: "kb",
+ status: "ready",
+ statistics: { raw_documents: 1 },
+ ...overrides,
+ };
+}
+
+test("kbCanReindex allows failed knowledge bases with source files", () => {
+ assert.equal(
+ kbCanReindex(
+ kb({
+ status: "error",
+ statistics: { raw_documents: 1, active_match: true },
+ }),
+ ),
+ true,
+ );
+});
+
+test("kbCanReindex keeps empty failed knowledge bases disabled", () => {
+ assert.equal(
+ kbCanReindex(
+ kb({
+ status: "error",
+ statistics: { raw_documents: 0, active_match: false },
+ }),
+ ),
+ false,
+ );
+});
+
+test("kbCanReindex preserves mismatch and needs-reindex behavior", () => {
+ assert.equal(
+ kbCanReindex(kb({ statistics: { raw_documents: 1, needs_reindex: true } })),
+ true,
+ );
+ assert.equal(
+ kbCanReindex(kb({ statistics: { raw_documents: 1, active_match: false } })),
+ true,
+ );
+ assert.equal(
+ kbCanReindex(kb({ statistics: { raw_documents: 1, active_match: true } })),
+ false,
+ );
+});